@r_masseater/masseater-utils 0.12.0 → 0.13.1

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 (49) hide show
  1. package/dist/{client-DX2jXirb.mjs → client-BSzBrLkG.mjs} +4 -4
  2. package/dist/{client-DX2jXirb.mjs.map → client-BSzBrLkG.mjs.map} +1 -1
  3. package/dist/desktop-shell/media-notes.mjs +9 -3
  4. package/dist/desktop-shell/media-notes.mjs.map +1 -1
  5. package/dist/desktop-shell/release-cli.mjs +3 -4
  6. package/dist/desktop-shell/release-cli.mjs.map +1 -1
  7. package/dist/{headers-Bpv9DhNS.mjs → headers-B6rDlN_n.mjs} +4 -4
  8. package/dist/headers-B6rDlN_n.mjs.map +1 -0
  9. package/dist/model-server/process.mjs +12 -9
  10. package/dist/model-server/process.mjs.map +1 -1
  11. package/dist/model-server.mjs +1 -1
  12. package/dist/{node-main-BrhzkUvP.mjs → node-main-Cx8sevy0.mjs} +5 -2
  13. package/dist/{node-main-BrhzkUvP.mjs.map → node-main-Cx8sevy0.mjs.map} +1 -1
  14. package/dist/node-main.mjs +2 -2
  15. package/dist/plugin-kit.mjs +4 -4
  16. package/dist/plugin-kit.mjs.map +1 -1
  17. package/dist/{run-main-Chtieg-p.mjs → run-main-CfugYs_u.mjs} +9 -6
  18. package/dist/{run-main-Chtieg-p.mjs.map → run-main-CfugYs_u.mjs.map} +1 -1
  19. package/dist/security-headers/http.mjs +1 -1
  20. package/dist/security-headers/response.mjs +1 -1
  21. package/dist/security-headers/static.mjs +1 -1
  22. package/dist/security-headers/vite.mjs +1 -1
  23. package/dist/security-headers.mjs +1 -1
  24. package/dist/{static-page-headers-muClDOhu.mjs → static-page-headers-gBsEgnqj.mjs} +2 -2
  25. package/dist/{static-page-headers-muClDOhu.mjs.map → static-page-headers-gBsEgnqj.mjs.map} +1 -1
  26. package/dist/{usage-meter-B196tKiM.mjs → usage-meter-ifuOWUth.mjs} +3 -3
  27. package/dist/usage-meter-ifuOWUth.mjs.map +1 -0
  28. package/dist/usage-meter.mjs +1 -1
  29. package/dist/vitest-otlp/setup.mjs +1 -2
  30. package/dist/vitest-otlp/setup.mjs.map +1 -1
  31. package/dist/workers-tracing/alchemy.d.mts +2 -0
  32. package/dist/workers-tracing/alchemy.mjs +6 -0
  33. package/dist/workers-tracing/alchemy.mjs.map +1 -1
  34. package/package.json +1 -1
  35. package/skills/add-scroll-chip-row/SKILL.md +1 -1
  36. package/skills/assert-exported-telemetry/SKILL.md +1 -1
  37. package/skills/build-tauri-app/SKILL.md +1 -1
  38. package/skills/find-cache-folder/SKILL.md +1 -1
  39. package/skills/import-custom-format/SKILL.md +1 -1
  40. package/skills/name-stack-resources/SKILL.md +1 -1
  41. package/skills/read-hook-input/SKILL.md +1 -1
  42. package/skills/read-node-ecosystem/SKILL.md +1 -1
  43. package/skills/run-effect-main/SKILL.md +1 -1
  44. package/skills/share-types-with-rust/SKILL.md +1 -1
  45. package/skills/trace-workers/SKILL.md +4 -1
  46. package/skills/use-model-server/SKILL.md +1 -1
  47. package/skills/write-actions-steps/SKILL.md +1 -1
  48. package/dist/headers-Bpv9DhNS.mjs.map +0 -1
  49. package/dist/usage-meter-B196tKiM.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"process.mjs","names":["empty","Random","Context.Reference","TypeId","empty","make","set","get","Option.some","Option.none","hash","Hash.hash","Equal.equals","Context.Reference","Context.get","random.Random","Effect.withFiber","Effect.succeed","TypeId","makeWith","effect.contextWith","Proto","effect.updateContext","Context.merge","MutableHashMap.make","Duration.fromInputUnsafe","effect.succeed","Duration.infinity","get","core.withFiber","MutableHashMap.get","Option.isSome","MutableHashMap.remove","MutableHashMap.set","effect.ClockRef","effect.exitHasInterrupts","Duration.isZero","Duration.isFinite","Duration.toMillis","effect.forkUnsafe","effect.onExitUnsafe","effect.void","effect.fiberInterrupt","effect.fiberJoin","MutableHashMap.size","effect.ConsoleRef","core.withFiber","effect.sync","TypeId","Predicate.hasProperty","Proto","Iterable.empty","makeUnsafe","make","Effect.acquireRelease","Effect.sync","Deferred.makeUnsafe","Effect.suspend","Effect.void","Fiber.interruptAll","Deferred.into","Filter.toPredicate","Filter.compose","Cause.filterInterruptors","Filter.has","Exit.isFailure","Cause.hasInterruptsOnly","Deferred.doneUnsafe","Effect.runFork","Effect.interrupt","Effect.isEffect","Effect.withFiber","internalEffect.forkUnsafe","Effect.succeed","effect.CurrentLoggers","make","effect.loggerMake","layer","Layer.effect","withFiber","effect.fnUntraced","isEffect","MutableRef.make","make","Effect.sync","MutableRef.set","Context.Service","Exit.isSuccess","Cause.hasInterruptsOnly","Context.getOrUndefined","Cause.reasonAnnotations","Cause.squash","Effect.isEffect","Effect.tapCause","Effect.void","Effect.logError","Effect.runFork","Effect.withFiber","TypeId","Proto","Inspectable.NodeInspectSymbol","empty","Uint8Array","compressBody","Effect.succeed","Effect.map","Effect.promise","HttpBody.uint8Array","HttpBody.stream","Stream.fromReadableStream","Stream.toReadableStream","Headers.remove","Headers.set","Data.TaggedError","make","Result.try","internal.unwrap","TypeId","Proto","Inspectable.BaseProto","UrlParams.redactUrl","makeWith","UrlParams.empty","Option.none","Headers.empty","HttpBody.empty","make","Headers.set","Headers.setAll","UrlParams.fromInput","Option.fromNullishOr","UrlParams.setAll","Option.some","bodyInternal.updateHeaders","Effect.succeed","Effect.map","compression.compressBody","bodyInternal.updateContentLength","Url.make","Option.getOrUndefined","Result.isSuccess","TypeId","TypeId","filterStatusOk","Effect.succeed","Effect.fail","Error.HttpClientError","Error.StatusCodeError","Inspectable.Class","HttpIncomingMessage.TypeId","HttpIncomingMessage.inspect","HttpClientRequest.toUrl","Option.isNone","Headers.fromInput","Cookies.fromSetCookie","Option.none","Stream.fromReadableStream","Error.DecodeError","Stream.fail","Error.EmptyBodyError","Effect.flatMap","Effect.try","Effect.map","UrlParams.fromInput","internalUrlParams.fromBody","Effect.tryPromise","Effect.cached","Effect.runSync","Headers.fromRecordUnsafe","Option.match","UrlParams.redactUrl","Headers.isRedactedName","Context.Service","Effect.flatMap","HttpClientResponse.filterStatusOk","Inspectable.BaseProto","HttpClientRequest.make","make","Effect.withFiber","UrlParams.CurrentRedactedNames","Url.make","Option.getOrUndefined","Result.isFailure","Cause.fail","Error.HttpClientError","Error.InvalidUrlError","Error.addFailureRedactedNames","Effect.failCause","Scope.addFinalizer","Effect.sync","Effect.uninterruptibleMask","Effect.matchCauseEffect","Effect.succeed","Cause.hasInterrupts","References.TracerEnabled","Tracer.DisablePropagation","Effect.useSpan","Headers.CurrentRedactedNames","tracing.addUrlAttributes","tracing.redactedNames","tracing.addHeaderAttributes","HttpClientRequest.setHeaders","TraceContext.toHeaders","Effect.withParentSpan","Exit.fail","Error.StatusCodeError","References.TracerTimingEnabled","Schedule.isSchedule","Schedule.forever","Effect.repeat","Effect.retry","Predicate.or","retryAfterDelay","Headers.parseRetryAfter","Result.isSuccess","Headers.retryAfterDelay","Duration.max","Duration.millis","Effect.tap","Effect.tapError","Context.Reference","effect","Layer.effect","Effect.contextWith","Effect.map","Effect.updateContext","Context.merge","Error.addResponseRedactedNames","HttpClientResponse.TypeId","HttpIncomingMessage.TypeId","Effect.suspend","Effect.onInterrupt","Stream.suspend","Stream.ensuring","Inspectable.NodeInspectSymbol","Cause.isTimeoutError","Error.isHttpClientError","Predicate.hasProperty","Schedule.fromStep","Schedule.toStep","Context.Service","Data.TaggedError","Effect.fnUntraced","Effect.context","Context.get","Scope.Scope","Fiber.runIn","Scope.forkUnsafe","Semaphore.make","Latch.makeUnsafe","Scope.addFinalizer","Effect.withFiber","Effect.runForkWith","Effect.void","Effect.catchDefect","Effect.interrupt","Rpc.ServerClient","Effect.asVoid","Exit.interrupt","Effect.andThen","Context.getOrUndefinedUnsafe","Exit.die","Effect.ensuring","RpcSchema.isStreamSchema","Tracer.externalSpan","Effect.die","isWrapper","Rpc.isWrapper","Effect.suspend","Exit.void","Effect.flatMap","Effect.exit","Effect.failCause","Scope.makeUnsafe","Effect.onExit","Deferred.isDeferred","Scope.closeUnsafe","Cause.hasDies","Cause.hasInterrupts","Cause.squash","Fiber.getCurrent","Rpc.TracingEnabled","Context.getOrUndefined","Tracer.ParentSpan","Effect.withSpan","RpcTracing.spanName","RpcTracing.spanAttributes","Context.add","onExit","Deferred.await","Effect.onError","Cause.hasInterruptsOnly","Effect.isEffect","Effect.whileLoop","Queue.takeAll","Pull.catchDone","Effect.scoped","Stream.runForEachArray","RpcSchema.getStreamSchemas","Rpc.ParseOptions","Schema.decodeUnknownEffect","Schema.encodeUnknownEffect","Schema.NonEmptyArray","Option.isSome","Schema.Any","Rpc.exitSchema","Schema.encodeSync","Schema.Defect","Schema.Exit","Schema.Never","Context.merge","Context.getUnsafe","make","Scope.make","Scope.provide","Effect.ignoreCause","Effect.forkIn","Effect.forkChild","Queue.take","exitSchema","Schema.Void","Exit.isExit","Exit.isSuccess","Effect.catch","Effect.provideContext","Effect.provideService","Transferable.Collector","Cause.die","SchemaIssue.defaultFormatter","Effect.catchCause","Effect.annotateLogs","Effect.logDebug","Headers.fromInput","Transferable.makeCollectorUnsafe","Effect.matchEffect","Effect.tapCause","Effect.logFatal","Scope.close","layer","Layer.effectDiscard","Effect.forkScoped","Context.Service","Effect.gen","SocketServer.SocketServer","Layer.effect","RpcSerialization.RpcSerialization","Queue.make","scope","Effect.scope","Scope.addFinalizerExit","Queue.offer","Effect.orDie","Predicate.isTagged","Socket.CloseEvent","Effect.catchReason","Effect.succeed","Effect.sync","Effect.succeedNone","Effect.succeed","NetAddress.unixPathAddress","Effect.fromResult","NetAddress.inetAddressFromIpString","Effect.mapError","SocketServer.SocketServerError","SocketServer.SocketServerOpenError","make","layer","Function.flow","Layer.effect","SocketServer.SocketServer","Effect.fnUntraced","Deferred.makeUnsafe","Effect.addFinalizer","Effect.callback","Effect.void","Deferred.doneUnsafe","Exit.fail","Effect.raceFirst","Deferred.await","Scope.make","Context.omit","Scope.Scope","Effect.context","Fiber.runIn","NodeSocket.fromDuplex","Effect.acquireRelease","Effect.suspend","Effect.fail","Socket.SocketError","Socket.SocketOpenError","Socket.SocketCloseError","Effect.sync","Effect.flatMap","Effect.ignoreCause","Effect.runForkWith","Context.add","NodeSocket.NetSocket","Scope.close","Exit.void","runMain","Runtime.makeRunMain","Context.Service","Schema.encodeEffect","Schema.fromJsonString","Schema.Json","ChildProcess.make","Effect.fnUntraced","FileSystem.FileSystem","Path.Path","runtimeManifest","runtimeLock","ChildProcessSpawner.ChildProcessSpawner","Effect.filterOrFail","Hash.string","Predicate.hasProperty","Effect.tryPromise","Exit.match","Duration.zero","Duration.infinity","importModule","Effect.fnUntraced","Path.Path","Effect.mapError","Effect.all","Schema.decodeUnknownEffect","Effect.try","Predicate.isNotUndefined","Cache.makeWith","Effect.withSpan","Cache.get","Effect.flatMap","Effect.asVoid","Layer.effect","NodeRuntime.runMain","Context.Reference","Context.Service","HttpClient.make","Effect.fail","HttpClientError.HttpClientError","HttpClientError.TransportError","Context.getOrUndefined","Headers.merge","Headers.fromInput","Headers.remove","Effect.sync","Effect.map","Effect.tryPromise","HttpClientResponse.fromWeb","Effect.ensuring","Stream.ensuring","Effect.onError","Effect.callback","Effect.interrupt","Effect.flatMap","Stream.toReadableStreamEffect","Stream.interruptWhen","HttpClientError.EncodeError","Stream.mkArrayBuffer","Effect.mapError","layer","HttpClient.layerMergedContext","Effect.succeed","Config.Array","Schema.String","Config.map","Config.Record","Schema.StringFromUriComponent","Config.orElse","Config.withDefault","Config.URL","Headers.parseRetryAfter","Result.isFailure","Effect.succeed","Duration.seconds","Effect.map","Headers.retryAfterDelay","Schedule.passthrough","Schedule.addDelay","HttpClientError.isHttpClientError","Context.Service","Layer.sync","Effect.suspend","Effect.void","Effect.forEach","Effect.flatMap","Scope.Scope","Scope.addFinalizer","Effect.sync","make","Effect.fnUntraced","Effect.context","Context.get","Duration.max","Duration.fromInputUnsafe","Duration.zero","Count.normalizeNonEmpty","Count.normalize","HttpClient.HttpClient","HttpClient.tap","Effect.ignore","HttpClient.tapError","HttpClient.filterStatusOk","HttpClient.transformResponse","Effect.provideService","HttpClient.TracerPropagationEnabled","HttpClient.retryTransient","Version.getCurrentVersion","Headers.fromInput","Headers.set","HttpClientRequest.post","MutableList.make","Effect.callback","Latch.make","HttpClientRequest.setBody","HttpClientRequest.compressBody","Effect.andThen","Effect.withTracerEnabled","Effect.catchCause","MutableList.clear","Effect.logWarning","Effect.annotateLogs","Effect.withFiber","MutableList.takeN","Effect.exit","Effect.ensuring","Effect.runForkWith","Duration.isFinite","Effect.gen","Effect.race","Effect.as","Effect.sleep","Effect.interruptible","Effect.timeoutOption","MutableList.append","make","Version.getCurrentVersion","Effect.fnUntraced","Config.Record","Schema.StringFromUriComponent","Config.withDefault","Config.schema","Schema.UndefinedOr","Schema.String","Config.String","Effect.orDie","Context.Service","Base64.encode","HttpBody.text","Layer.succeed","make","Effect.fnUntraced","OtlpResource.fromConfig","Version.getCurrentVersion","Exporter.make","Duration.seconds","Effect.void","Logger.make","layer","Logger.layer","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Option.firstSomeOf","Option.map","Duration.millis","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Cause.prettyErrors","Arr.ensure","OtlpResource.entriesToAttributes","OtlpResource.unknownToAttributeValue","Option.isSome","make","Effect.fnUntraced","OtlpResource.fromConfig","OtlpResource.serviceNameUnsafe","Effect.context","Metric.snapshotUnsafe","OtlpResource.entriesToAttributes","Effect.sync","Effect.void","Exporter.make","Duration.seconds","layer","Layer.effectDiscard","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Config.map","Duration.millis","Option.firstSomeOf","Option.map","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Effect.fnUntraced","OtlpResource.fromConfig","Version.getCurrentVersion","Exporter.make","Duration.seconds","Effect.void","Option.isSome","Tracer.make","Layer.effect","Tracer.Tracer","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Config.map","Duration.millis","Option.isNone","Config.schema","Schema.isBetween","Option.firstSomeOf","Option.map","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Hex.random","Cause.hasInterruptsOnly","Cause.prettyErrors","Layer.mergeAll","OtlpLogger.layerFromConfig","OtlpMetrics.layerFromConfig","OtlpTracer.layerFromConfig","Schema.Struct","Schema.String","Schema.Finite","Schema.Array","Schema.Struct","Schema.String","Schema.decodeUnknownOption","Schema.fromJsonString","Schema.encodeEffect","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.option","Option.flatMap","Option.isSome","Option.isNone","Option.none","Option.map","Effect.forEach","Effect.map","Arr.getSomes","Random.nextInt","Effect.ignore","Schema.TaggedError","Effect.tryPromise","Effect.flatMap","Layer.build","Effect.provideContext","Effect.scoped","Exit.match","Effect.runSyncExit","Config.NonEmptyString","Config.option","Option.none","Effect.suspend","Option.isNone","Effect.void","Arr.map","Option.liftPredicate","Predicate.isObject","Option.map","Rec.toEntries","Option.getOrElse","Arr.flatMap","Predicate.isString","Option.filter","Option.toArray","Arr.join","Cause.isFailReason","Str.isNonEmpty","Option.match","Cause.prettyErrors","Cause.fromReasons","Arr.map","Str.isEmpty","Cause.isDieReason","Cause.hasInterruptsOnly","Cause.squash","Runtime.getErrorReported","Arr.filter","Cause.isInterruptReason","Layer.mergeAll","nodeServices","FetchHttpClient.layer","Otlp.layerFromConfig","Layer.provide","OtlpSerialization.layerJson","Layer.provideMerge","nodeRuntimeRunMain","Layer.build","Effect.flatMap","Effect.provideContext","Effect.scoped","Effect.ensuring","Effect.tapCause","Effect.forEach","Console.error","Duration.millis","Effect.fnUntraced","Clock.currentTimeMillis","Ref.make","Effect.flatMap","Ref.set","Effect.andThen","Ref.update","Effect.acquireUseRelease","Effect.all","Ref.get","Effect.map","Duration.toMillis","Effect.repeat","Schedule.spaced","Effect.asVoid","Duration.millis","Schema.decodeUnknownOption","Schema.decodeTo","Schema.Int","Effect.flatMap","Effect.map","Effect.orElseSucceed","Option.none","Option.map","Option.getOrElse","Effect.fnUntraced","FileSystem.FileSystem","Option.exists","Effect.ignore","Effect.catchTag","Effect.retry","Schedule.spaced","Effect.timeoutOrElse","Effect.acquireRelease","Duration.seconds","Ref.get","Effect.map","Effect.fnUntraced","Semaphore.make","FiberSet.make","Semaphore.withPermits","Effect.andThen","FiberSet.run","Effect.ignore","Effect.asVoid","Effect.tap","RpcServer.layer","Layer.provide","RpcServer.layerProtocolSocketServer","NodeSocketServer.layer","RpcSerialization.layerNdjson","FileSystem.FileSystem","Option.isSome","Layer.buildWithScope","Effect.scoped","Path.Path","scope","Effect.scope","Schema.decodeUnknownEffect","Schema.fromJsonString","Predicate.hasProperty","Layer.isLayer","Layer.unwrap","Effect.tryPromise","Effect.filterOrFail","Effect.map","Option.match","Option.fromNullishOr","Effect.flatMap","Duration.millis","Effect.scoped"],"sources":["../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Iterable.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/internal/random.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/MutableHashMap.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Metric.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Random.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Cache.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Console.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/FiberSet.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Logger.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Ref.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Runtime.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/internal/version.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Version.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpMethod.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/compressionBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/httpBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/Url.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClientRequest.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpIncomingMessage.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/webResponse.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClientResponse.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpTraceContext.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/tracing.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClient.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/socket/SocketServer.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/rpc/RpcServer.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.2.0_effect@4.2.0/node_modules/@effect/platform-node-shared/dist/NodeSocketServer.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.2.0_effect@4.2.0/node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../src/entities/model-engine/model/engine.ts","../../src/features/load-transformers/model/runtime-lock.json","../../src/features/load-transformers/model/runtime-manifest.json","../../src/features/load-transformers/model/runtime.ts","../../src/features/load-transformers/model/transformers.ts","../../../../node_modules/.pnpm/@effect+platform-node@4.2.0_effect@4.2.0_redis@6.2.1_@opentelemetry+api@1.10.0_/node_modules/@effect/platform-node/dist/NodeRuntime.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/FetchHttpClient.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/internal/otlpEnv.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpExporter.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpResource.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpSerialization.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpLogger.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpMetrics.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpTracer.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/Otlp.js","../../src/shared/lib/usage-tally.ts","../../src/shared/lib/usage-spool.ts","../../src/shared/lib/usage-meter.ts","../../src/features/run-main/model/report.ts","../../src/features/run-main/model/run-main.ts","../../src/features/serve-models/model/activity.ts","../../src/features/serve-models/model/lock.ts","../../src/features/serve-models/model/serve.ts","../../src/app/model-server-process.ts"],"sourcesContent":["/**\n * Works with JavaScript values that implement `[Symbol.iterator]`.\n *\n * Iterables include arrays, strings, generators, sets, and custom lazy\n * sequences. The helpers in this module let code transform, search, group, and\n * fold iterable values while preserving the input as an iterable instead of\n * forcing an array first.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as O from \"./Option.js\";\nimport { isBoolean } from \"./Predicate.js\";\nimport * as R from \"./Result.js\";\nimport * as Tuple from \"./Tuple.js\";\n/**\n * Creates an iterable by applying a function to consecutive integers.\n *\n * **Details**\n *\n * The function is called with each index starting from `0`. If a length is\n * provided, it is rounded down and normalized to at least `1`, with `NaN`\n * treated as `1`. If no length is specified, the iterable is infinite.\n *\n * **Example** (Generating values by index)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Generate first 5 even numbers\n * const evens = Iterable.makeBy((n) => n * 2, { length: 5 })\n * Array.from(evens) // => [0, 2, 4, 6, 8]\n *\n * // Generate squares\n * const squares = Iterable.makeBy((n) => n * n, { length: 4 })\n * Array.from(squares) // => [0, 1, 4, 9]\n *\n * // Infinite sequence (be careful when consuming!)\n * const naturals = Iterable.makeBy((n) => n)\n * const first10 = Iterable.take(naturals, 10)\n * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy = (f, options) => {\n const max = options?.length !== undefined ? Count.normalizeNonEmpty(options.length) : Infinity;\n return {\n [Symbol.iterator]() {\n let i = 0;\n return {\n next() {\n if (i < max) {\n return {\n value: f(i++),\n done: false\n };\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns an iterable of integers starting at `start` and increasing by `1`.\n *\n * **Details**\n *\n * When `end` is provided and `start <= end`, both endpoints are included. When\n * `end` is omitted, the iterable is unbounded. When `start > end`, the\n * iterable contains only `start`.\n *\n * **Example** (Creating a range)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.range(1, 3)) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start, end) => {\n if (end === undefined) {\n return makeBy(i => start + i);\n }\n return makeBy(i => start + i, {\n length: start <= end ? end - start + 1 : 1\n });\n};\n/**\n * Returns a `Iterable` containing a value repeated the specified number of times.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to an integer greater than or equal to\n * `1`. `NaN` is treated as `1`.\n *\n * **Example** (Repeating a value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.replicate(\"a\", 3)) // => [\"a\", \"a\", \"a\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate = /*#__PURE__*/dual(2, (a, n) => makeBy(() => a, {\n length: n\n}));\n/**\n * Repeats an iterable `n` times, yielding the full contents of `self` for each\n * repetition.\n *\n * **When to use**\n *\n * Use to repeat an iterable's contents a specific number of times.\n *\n * **Details**\n *\n * The result is lazy. `n` is rounded down and normalized to at least `1`, with\n * `NaN` treated as `1`. Each repetition obtains a new iterator from `self`.\n *\n * @see {@link forever} for repeating without an upper bound\n * @see {@link replicate} for repeating a single value\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, n) => flatten(makeBy(() => self, {\n length: n\n})));\n/**\n * Repeats an iterable without an upper bound.\n *\n * **When to use**\n *\n * Use to cycle a reusable iterable without an upper bound when a downstream\n * consumer controls how many values are taken.\n *\n * **Gotchas**\n *\n * The returned iterable is lazy and should usually be bounded with `take` or\n * another terminating consumer before materializing it.\n *\n * @see {@link repeat} for repeating an iterable a specific number of times\n * @see {@link take} for bounding the unbounded result before materializing it\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const forever = self => repeat(self, Infinity);\n/**\n * Takes a record and returns an Iterable of tuples containing its keys and values.\n *\n * **Example** (Converting a record to entries)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * Array.from(Iterable.fromRecord(x)) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @stability stable\n * @category converting\n * @since 2.0.0\n */\nexport const fromRecord = self => ({\n *[Symbol.iterator]() {\n for (const key in self) {\n if (Object.hasOwn(self, key)) {\n yield [key, self[key]];\n }\n }\n }\n});\n/**\n * Prepends an element to the front of an `Iterable`, creating a new `Iterable`.\n *\n * **Example** (Prepending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 3, 4]\n * const withOne = Iterable.prepend(numbers, 1)\n * Array.from(withOne) // => [1, 2, 3, 4]\n *\n * // Works with any iterable\n * const letters = \"abc\"\n * const withZ = Iterable.prepend(letters, \"z\")\n * Array.from(withZ) // => [\"z\", \"a\", \"b\", \"c\"]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, head) => prependAll(self, [head]));\n/**\n * Prepends the specified prefix iterable to the beginning of the specified iterable.\n *\n * **Example** (Prepending another iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.prependAll([1, 2], [\"a\", \"b\"])) // => [\"a\", \"b\", 1, 2]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const prependAll = /*#__PURE__*/dual(2, (self, that) => appendAll(that, self));\n/**\n * Appends an element to the end of an `Iterable`, creating a new `Iterable`.\n *\n * **When to use**\n *\n * Use to add one element after all elements of an iterable while keeping the\n * result as a lazy `Iterable`.\n *\n * **Details**\n *\n * The result yields every element from `self` first, then yields `last` after\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, the appended element is never\n * reached.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link prepend} for adding one element before the existing elements\n * @see {@link appendAll} for appending all elements from another iterable\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const append = /*#__PURE__*/dual(2, (self, last) => appendAll(self, [last]));\n/**\n * Concatenates two iterables, combining their elements.\n *\n * **When to use**\n *\n * Use to lazily concatenate two iterables while preserving order, yielding all\n * elements from `self` before `that`.\n *\n * **Details**\n *\n * The result is lazy. The iterator for `that` is not created or read until\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, `that` is never reached.\n *\n * **Example** (Concatenating iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6]\n *\n * // Works with different iterable types\n * const numbers = [1, 2]\n * const letters = \"abc\"\n * const mixed = Iterable.appendAll(numbers, letters)\n * Array.from(mixed) // => [1, 2, \"a\", \"b\", \"c\"]\n *\n * // Lazy evaluation - only consumes what's needed\n * const infinite = Iterable.range(1)\n * const finite = [0, -1, -2]\n * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2]\n * ```\n *\n * @see {@link append} for appending one value instead of another iterable\n * @see {@link prependAll} for yielding another iterable before `self`\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, that) => ({\n [Symbol.iterator]() {\n const iterA = self[Symbol.iterator]();\n let doneA = false;\n let iterB;\n return {\n next() {\n if (!doneA) {\n const r = iterA.next();\n if (r.done) {\n doneA = true;\n iterB = that[Symbol.iterator]();\n return iterB.next();\n }\n return r;\n }\n return iterB.next();\n }\n };\n }\n}));\n/**\n * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result.\n *\n * **Example** (Tracking running results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Running sum of numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n)\n * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15]\n *\n * // Build strings progressively\n * const letters = [\"a\", \"b\", \"c\"]\n * const progressive = Iterable.scan(letters, \"\", (acc, letter) => acc + letter)\n * Array.from(progressive) // => [\"\", \"a\", \"ab\", \"abc\"]\n *\n * // Track maximum values seen so far\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * const runningMax = Iterable.scan(values, -Infinity, Math.max)\n * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9]\n * ```\n *\n * @stability stable\n * @category folding\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, b, f) => ({\n [Symbol.iterator]() {\n let acc = b;\n let iterator;\n function next() {\n if (iterator === undefined) {\n iterator = self[Symbol.iterator]();\n return {\n done: false,\n value: acc\n };\n }\n const result = iterator.next();\n if (result.done) {\n return result;\n }\n acc = f(acc, result.value);\n return {\n done: false,\n value: acc\n };\n }\n return {\n next\n };\n }\n}));\n/**\n * Checks whether an `Iterable` is empty.\n *\n * **Example** (Checking for emptiness)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.isEmpty([]) // => true\n * Iterable.isEmpty([1, 2, 3]) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 2.0.0\n */\nexport const isEmpty = self => {\n const iterator = self[Symbol.iterator]();\n return iterator.next().done === true;\n};\n/**\n * Returns the number of elements in a `Iterable`.\n *\n * **Example** (Counting iterable elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.size(numbers) // => 5\n *\n * const empty = Iterable.empty<number>()\n * Iterable.size(empty) // => 0\n *\n * // Works with any iterable\n * const letters = \"hello\"\n * Iterable.size(letters) // => 5\n *\n * // Note: This consumes the entire iterable\n * const range = Iterable.range(1, 100)\n * Iterable.size(range) // => 100\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => {\n const iterator = self[Symbol.iterator]();\n let count = 0;\n while (!iterator.next().done) {\n count++;\n }\n return count;\n};\n/**\n * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty.\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.head(numbers) // => Option.some(1)\n *\n * const empty = Iterable.empty<number>()\n * Iterable.head(empty) // => Option.none()\n *\n * // Safe way to get first element\n * const firstEven = Iterable.head(\n * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0)\n * )\n * firstEven // => Option.some(4)\n *\n * // Use with Option methods\n * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2)\n * doubled // => Option.some(10)\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const head = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n return result.done ? O.none() : O.some(result.value);\n};\n/**\n * Gets the first element of an `Iterable` without returning an `Option`.\n *\n * **When to use**\n *\n * Use when the `Iterable` is known to be non-empty and direct access to the\n * first element is preferred over handling `Option.none`.\n *\n * **Gotchas**\n *\n * Throws if the `Iterable` is empty.\n *\n * **Example** (Getting the first element unsafely)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.headUnsafe(numbers) // => 1\n *\n * const letters = \"hello\"\n * Iterable.headUnsafe(letters) // => \"h\"\n *\n * // Iterable.headUnsafe(Iterable.empty<number>())\n * // throws Error: \"headUnsafe: empty iterable\"\n *\n * // Use only when you're certain the iterable is non-empty\n * const nonEmpty = Iterable.range(1, 10)\n * Iterable.headUnsafe(nonEmpty) // => 1\n * ```\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const headUnsafe = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) throw new Error(\"headUnsafe: empty iterable\");\n return result.value;\n};\n/**\n * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Taking from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const firstThree = Iterable.take(numbers, 3)\n * Array.from(firstThree) // => [1, 2, 3]\n *\n * // Taking more than available returns all elements\n * const firstTen = Iterable.take(numbers, 10)\n * Array.from(firstTen) // => [1, 2, 3, 4, 5]\n *\n * // Taking 0 or negative returns empty\n * const none = Iterable.take(numbers, 0)\n * Array.from(none) // => []\n *\n * // Useful with infinite iterables\n * const naturals = Iterable.range(1)\n * const firstFive = Iterable.take(naturals, 5)\n * Array.from(firstFive) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n let i = 0;\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n if (i < count) {\n i++;\n return iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n});\n/**\n * Takes the longest initial `Iterable` prefix for which all elements satisfy the\n * specified predicate.\n *\n * **Example** (Taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 4, 6, 8, 3, 10, 12]\n * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0)\n * Array.from(evenPrefix) // => [2, 4, 6, 8]\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3)\n * Array.from(firstThreeByIndex) // => [\"a\", \"b\", \"c\"]\n *\n * // Stops at first non-matching element\n * const mixed = [1, 3, 5, 4, 7, 9]\n * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1)\n * Array.from(oddPrefix) // => [1, 3, 5]\n *\n * // Type refinement\n * const values: Array<string | number> = [\"a\", \"b\", \"c\", 1, \"d\"]\n * const stringPrefix = Iterable.takeWhile(\n * values,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(stringPrefix) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n if (iterator !== undefined) {\n const result = iterator.next();\n if (!result.done && predicate(result.value, i++)) {\n return result;\n }\n iterator = undefined;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Drops a max number of elements from the start of an `Iterable`\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Dropping from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const withoutFirstTwo = Iterable.drop(numbers, 2)\n * Array.from(withoutFirstTwo) // => [3, 4, 5]\n *\n * // Dropping more than available returns empty\n * const withoutFirstTen = Iterable.drop(numbers, 10)\n * Array.from(withoutFirstTen) // => []\n *\n * // Dropping 0 or negative returns all elements\n * const all = Iterable.drop(numbers, 0)\n * Array.from(all) // => [1, 2, 3, 4, 5]\n *\n * // Combine with take for slicing\n * const slice = Iterable.take(Iterable.drop(numbers, 1), 3)\n * Array.from(slice) // => [2, 3, 4]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n while (i < count) {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n i++;\n }\n return iterator.next();\n }\n };\n }\n };\n});\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * **Example** (Finding the first match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8]\n * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0)\n * firstEven // => Option.some(4)\n *\n * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10)\n * firstGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\"]\n * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0)\n * atEvenIndex // => Option.some(\"a\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\"]\n * const firstString = Iterable.findFirst(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * firstString // => Option.some(\"hello\")\n *\n * // Transform during search\n * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => {\n * const sqrt = Math.sqrt(x)\n * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none()\n * })\n * findSquareRoot // => Option.some(1)\n * ```\n *\n * @stability stable\n * @category searching\n * @since 2.0.0\n */\nexport const findFirst = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n return O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n return o;\n }\n }\n i++;\n }\n return O.none();\n});\n/**\n * Finds the last element for which a predicate holds.\n *\n * **Example** (Finding the last match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8, 2]\n * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0)\n * lastEven // => Option.some(2)\n *\n * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10)\n * lastGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0)\n * lastAtEvenIndex // => Option.some(\"e\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\", 3]\n * const lastString = Iterable.findLast(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * lastString // => Option.some(\"world\")\n * ```\n *\n * @stability stable\n * @category searching\n * @since 2.0.0\n */\nexport const findLast = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n let last = O.none();\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n last = O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n last = o;\n }\n }\n i++;\n }\n return last;\n});\n/**\n * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs.\n *\n * **Example** (Zipping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\", \"c\"]\n * const zipped = Iterable.zip(numbers, letters)\n * Array.from(zipped) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Different lengths - shorter one determines result length\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const partial = Iterable.zip(short, long)\n * Array.from(partial) // => [[1, \"a\"], [2, \"b\"]]\n *\n * // Works with any iterables\n * const range = Iterable.range(1, 3)\n * const word = \"abc\"\n * const mixed = Iterable.zip(range, word)\n * Array.from(mixed) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Create indexed pairs\n * const values = [\"apple\", \"banana\", \"cherry\"]\n * const indices = Iterable.range(0, 2)\n * const indexed = Iterable.zip(indices, values)\n * Array.from(indexed) // => [[0, \"apple\"], [1, \"banana\"], [2, \"cherry\"]]\n * ```\n *\n * @stability stable\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, Tuple.make));\n/**\n * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one\n * input `Iterable` is short, excess elements of the longer `Iterable` are discarded.\n *\n * **Example** (Zipping with a combining function)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Add corresponding elements\n * const a = [1, 2, 3, 4]\n * const b = [10, 20, 30, 40]\n * const sums = Iterable.zipWith(a, b, (x, y) => x + y)\n * Array.from(sums) // => [11, 22, 33, 44]\n *\n * // Combine strings\n * const firstNames = [\"John\", \"Jane\", \"Bob\"]\n * const lastNames = [\"Doe\", \"Smith\", \"Johnson\"]\n * const fullNames = Iterable.zipWith(\n * firstNames,\n * lastNames,\n * (first, last) => `${first} ${last}`\n * )\n * Array.from(fullNames) // => [\"John Doe\", \"Jane Smith\", \"Bob Johnson\"]\n *\n * // Different lengths - stops at shorter\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const combined = Iterable.zipWith(\n * short,\n * long,\n * (num, letter) => `${num}${letter}`\n * )\n * Array.from(combined) // => [\"1a\", \"2b\"]\n *\n * // Complex transformations\n * const prices = [10.99, 25.50, 5.00]\n * const quantities = [2, 1, 3]\n * const totals = Iterable.zipWith(prices, quantities, (price, qty) => {\n * return Math.round(price * qty * 100) / 100 // round to 2 decimal places\n * })\n * Array.from(totals) // => [21.98, 25.5, 15]\n * ```\n *\n * @stability stable\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const selfIterator = self[Symbol.iterator]();\n const thatIterator = that[Symbol.iterator]();\n return {\n next() {\n const selfResult = selfIterator.next();\n const thatResult = thatIterator.next();\n if (selfResult.done || thatResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(selfResult.value, thatResult.value)\n };\n }\n };\n }\n}));\n/**\n * Places a separator between members of an `Iterable`.\n *\n * **When to use**\n *\n * Use to lazily insert a separator between adjacent values.\n *\n * **Details**\n *\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * **Example** (Interspersing separators)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Join numbers with separator\n * const numbers = [1, 2, 3, 4]\n * const withCommas = Iterable.intersperse(numbers, \",\")\n * Array.from(withCommas) // => [1, \",\", 2, \",\", 3, \",\", 4]\n *\n * // Join words with spaces\n * const words = [\"hello\", \"world\", \"from\", \"effect\"]\n * const sentence = Iterable.intersperse(words, \" \")\n * Array.from(sentence).join(\"\") // => \"hello world from effect\"\n *\n * // Empty iterable remains empty\n * const empty = Iterable.empty<string>()\n * const stillEmpty = Iterable.intersperse(empty, \"-\")\n * Array.from(stillEmpty) // => []\n *\n * // Single element has no separators added\n * const single = [42]\n * const noSeparator = Iterable.intersperse(single, \"|\")\n * Array.from(noSeparator) // => [42]\n *\n * // Build CSS-like strings\n * const styles = [\"color: red\", \"font-size: 14px\", \"margin: 10px\"]\n * const css = Iterable.intersperse(styles, \"; \")\n * Array.from(css).join(\"\") // => \"color: red; font-size: 14px; margin: 10px\"\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, middle) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let next = iterator.next();\n let emitted = false;\n return {\n next() {\n if (next.done) {\n return next;\n } else if (emitted) {\n emitted = false;\n return {\n done: false,\n value: middle\n };\n }\n emitted = true;\n const result = next;\n next = iterator.next();\n return result;\n }\n };\n }\n}));\n/**\n * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function.\n *\n * **Example** (Checking membership with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Custom equivalence for objects\n * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id\n * const containsById = Iterable.containsWith(byId)\n *\n * const users = [{ id: 1 }, { id: 2 }]\n * const hasUser1 = containsById(users, { id: 1 })\n * hasUser1 // => true\n *\n * // Case-insensitive string comparison\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive)\n *\n * const words = [\"Hello\", \"World\"]\n * const hasHello = containsCaseInsensitive(words, \"hello\")\n * hasHello // => true\n *\n * // Approximate number comparison\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const containsApprox = Iterable.containsWith(approxEqual)\n *\n * const values = [1.0, 2.0, 3.0]\n * const hasAlmostTwo = containsApprox(values, 2.05)\n * hasAlmostTwo // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const containsWith = isEquivalent => dual(2, (self, a) => {\n for (const i of self) {\n if (isEquivalent(a, i)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Checks whether an iterable contains a value using Effect's default `Equal`\n * equivalence.\n *\n * **Details**\n *\n * Can be called as `contains(self, value)` or curried as\n * `contains(value)(self)`.\n *\n * **Example** (Checking membership)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.contains(numbers, 3) // => true\n * Iterable.contains(numbers, 6) // => false\n *\n * const letters = \"hello\"\n * Iterable.contains(letters, \"l\") // => true\n * Iterable.contains(letters, \"x\") // => false\n *\n * // Works with any iterable\n * const range = Iterable.range(1, 100)\n * Iterable.contains(range, 50) // => true\n * Iterable.contains(range, 150) // => false\n *\n * // Curried version\n * const containsThree = Iterable.contains(3)\n * containsThree([1, 2, 3]) // => true\n * containsThree([4, 5, 6]) // => false\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const contains = /*#__PURE__*/containsWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of\n * the `Iterable`.\n * `n` is rounded down and normalized to at least `1`; `NaN` and non-positive\n * values therefore produce singleton pieces.\n *\n * **Example** (Chunking an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * const chunks = Iterable.chunksOf(numbers, 3)\n * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n *\n * // Last chunk can be shorter\n * const uneven = [1, 2, 3, 4, 5, 6, 7]\n * const chunks2 = Iterable.chunksOf(uneven, 3)\n * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]]\n *\n * // Chunk size larger than iterable\n * const small = [1, 2]\n * const chunks3 = Iterable.chunksOf(small, 5)\n * Array.from(chunks3) // => [[1, 2]]\n *\n * // Process data in batches\n * const data = Iterable.range(1, 100)\n * const batches = Iterable.chunksOf(data, 10)\n * const batchSums = Iterable.map(\n * batches,\n * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n)\n * )\n * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255]\n * ```\n *\n * @stability stable\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf = /*#__PURE__*/dual(2, (self, n) => {\n const safeN = Count.normalizeNonEmpty(n);\n return {\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n return {\n next() {\n if (iterator === undefined) {\n return {\n done: true,\n value: undefined\n };\n }\n const chunk = [];\n for (let i = 0; i < safeN; i++) {\n const result = iterator.next();\n if (result.done) {\n iterator = undefined;\n return chunk.length === 0 ? {\n done: true,\n value: undefined\n } : {\n done: false,\n value: chunk\n };\n }\n chunk.push(result.value);\n }\n return {\n done: false,\n value: chunk\n };\n }\n };\n }\n };\n});\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function.\n *\n * **Example** (Grouping consecutive elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group consecutive equal numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.groupWith(numbers, (a, b) => a === b)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * // Case-insensitive grouping of strings\n * const words = [\"Apple\", \"APPLE\", \"banana\", \"Banana\", \"cherry\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const groupedWords = Iterable.groupWith(words, caseInsensitive)\n * Array.from(groupedWords) // => [[\"Apple\", \"APPLE\"], [\"banana\", \"Banana\"], [\"cherry\"]]\n *\n * // Group by approximate equality\n * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2\n * const groupedFloats = Iterable.groupWith(floats, approxEqual)\n * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]]\n *\n * // Only groups consecutive elements\n * const scattered = [1, 2, 1, 2, 1]\n * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b)\n * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]]\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let nextResult;\n return {\n next() {\n let result;\n if (nextResult !== undefined) {\n if (nextResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n result = nextResult;\n nextResult = undefined;\n } else {\n result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n }\n const chunk = [result.value];\n while (true) {\n const next = iterator.next();\n if (next.done || !isEquivalent(result.value, next.value)) {\n nextResult = next;\n return {\n done: false,\n value: chunk\n };\n }\n chunk.push(next.value);\n }\n }\n };\n }\n}));\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s.\n *\n * **Example** (Grouping consecutive elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.group(numbers)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * const letters = \"aabbccaa\"\n * const groupedLetters = Iterable.group(letters)\n * Array.from(groupedLetters) // => [[\"a\", \"a\"], [\"b\", \"b\"], [\"c\", \"c\"], [\"a\", \"a\"]]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\", value: 1 },\n * { type: \"A\", value: 1 },\n * { type: \"B\", value: 2 },\n * { type: \"A\", value: 1 }\n * ]\n * const groupedObjects = Iterable.group(objects)\n * Array.from(groupedObjects).length // => 3\n * // Note: Only consecutive equal objects are grouped together\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const group = /*#__PURE__*/groupWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Groups all elements by the string or symbol key returned by `f`.\n *\n * **Details**\n *\n * Each property in the returned record contains a non-empty array of elements\n * that produced that key. Unlike `group`, matching elements do not need to be\n * consecutive.\n *\n * **Gotchas**\n *\n * When the key function returns a finite union of string literals or unique\n * symbols, the result preserves those keys as optional properties because the\n * input may not produce every key. Open `string` and `symbol` key types retain\n * their record index signatures.\n *\n * **Example** (Grouping by a key)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group by string length\n * const words = [\"a\", \"bb\", \"ccc\", \"dd\", \"eee\", \"f\"]\n * const byLength = Iterable.groupBy(words, (word) => word.length.toString())\n * byLength // => { \"1\": [\"a\", \"f\"], \"2\": [\"bb\", \"dd\"], \"3\": [\"ccc\", \"eee\"] }\n *\n * // Group by first letter\n * const names = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Anna\", \"Betty\"]\n * const byFirstLetter = Iterable.groupBy(names, (name) => name[0])\n * byFirstLetter // => { A: [\"Alice\", \"Anna\"], B: [\"Bob\", \"Betty\"], C: [\"Charlie\"], D: [\"David\"] }\n *\n * // Group by category\n * const items = [\n * { name: \"apple\", category: \"fruit\" },\n * { name: \"carrot\", category: \"vegetable\" },\n * { name: \"banana\", category: \"fruit\" },\n * { name: \"broccoli\", category: \"vegetable\" }\n * ]\n * const byCategory = Iterable.groupBy(items, (item) => item.category)\n * Object.keys(byCategory) // => [\"fruit\", \"vegetable\"]\n *\n * // Group numbers by even/odd\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? \"even\" : \"odd\")\n * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] }\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(2, (self, f) => {\n const out = {};\n for (const a of self) {\n const k = f(a);\n if (Object.hasOwn(out, k)) {\n out[k].push(a);\n } else {\n InternalRecord.assignProperty(out, k, [a]);\n }\n }\n return out;\n});\nconst constEmpty = {\n [Symbol.iterator]() {\n return constEmptyIterator;\n }\n};\nconst constEmptyIterator = {\n next() {\n return {\n done: true,\n value: undefined\n };\n }\n};\n/**\n * Creates an empty iterable that yields no elements.\n *\n * **When to use**\n *\n * Use when you need an empty iterable as a typed \"no data\" value or a base\n * case for iterable operations.\n *\n * **Example** (Creating an empty iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.empty<string>()) // => []\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => constEmpty;\n/**\n * Creates an iterable containing a single element.\n *\n * **When to use**\n *\n * Use to wrap a single value in an iterable context so it can be combined\n * with other iterable operations.\n *\n * **Example** (Wrapping a single value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const single = Iterable.of(42)\n * Array.from(single) // => [42]\n *\n * // Useful for creating homogeneous sequences\n * const sequences = [\n * Iterable.of(\"hello\"),\n * Iterable.range(1, 3),\n * Iterable.empty<string>()\n * ]\n *\n * // Can be used with flatMap for conditional inclusion\n * const numbers = [1, 2, 3, 4, 5]\n * const evensOnly = Iterable.flatMap(\n * numbers,\n * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty()\n * )\n * Array.from(evensOnly) // => [2, 4]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const of = a => [a];\n/**\n * Transforms each element of an iterable using a function.\n *\n * **Details**\n *\n * This is one of the most fundamental operations for working with iterables.\n * It applies a transformation function to each element, creating a new iterable\n * with the transformed values. The operation is lazy, so elements are only\n * transformed when the iterable is consumed.\n *\n * **Example** (Mapping elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Transform numbers to their squares\n * const numbers = [1, 2, 3, 4, 5]\n * const squares = Iterable.map(numbers, (x) => x * x)\n * Array.from(squares) // => [1, 4, 9, 16, 25]\n *\n * // Use index in transformation\n * const indexed = Iterable.map([\"a\", \"b\", \"c\"], (char, i) => `${i}: ${char}`)\n * Array.from(indexed) // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * Array.from(Iterable.map(\n * Iterable.map([1, 2, 3], (x) => x * 2),\n * (x) => x + 1\n * )) // => [3, 5, 7]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(result.value, i++)\n };\n }\n };\n }\n}));\n/**\n * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements.\n *\n * **Example** (Flat mapping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Expand each number to a range\n * const numbers = [1, 2, 3]\n * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n))\n * Array.from(expanded) // => [1, 1, 2, 1, 2, 3]\n *\n * // Split strings into characters\n * const words = [\"hi\", \"bye\"]\n * const chars = Iterable.flatMap(words, (word) => word)\n * Array.from(chars) // => [\"h\", \"i\", \"b\", \"y\", \"e\"]\n *\n * // Conditional expansion with empty iterables\n * const values = [1, 2, 3, 4, 5]\n * const evenMultiples = Iterable.flatMap(\n * values,\n * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : []\n * )\n * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12]\n *\n * // Use index in transformation\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.flatMap(\n * letters,\n * (letter, i) => Iterable.replicate(letter, i + 1)\n * )\n * Array.from(indexed) // => [\"a\", \"b\", \"b\", \"c\", \"c\", \"c\"]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => flatten(map(self, f)));\n/**\n * Flattens an Iterable of Iterables into a single Iterable\n *\n * **Example** (Flattening nested iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Flatten nested arrays\n * const nested = [[1, 2], [3, 4], [5, 6]]\n * const flat = Iterable.flatten(nested)\n * Array.from(flat) // => [1, 2, 3, 4, 5, 6]\n *\n * // Flatten different iterable types\n * const mixed: Array<Iterable<string>> = [\"ab\", \"cd\"]\n * const flatMixed = Iterable.flatten(mixed)\n * Array.from(flatMixed) // => [\"a\", \"b\", \"c\", \"d\"]\n *\n * // Flatten deeply nested (only one level)\n * const deepNested = [[[1, 2]], [[3, 4]]]\n * const oneLevelFlat = Iterable.flatten(deepNested)\n * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]]\n * // [[1, 2], [3, 4]] (still contains arrays)\n *\n * // Empty iterables are handled correctly\n * const withEmpty = [[1, 2], [], [3, 4], []]\n * const flatWithEmpty = Iterable.flatten(withEmpty)\n * Array.from(flatWithEmpty) // => [1, 2, 3, 4]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = self => ({\n [Symbol.iterator]() {\n const outerIterator = self[Symbol.iterator]();\n let innerIterator;\n function next() {\n while (true) {\n if (innerIterator === undefined) {\n const next = outerIterator.next();\n if (next.done) {\n return next;\n }\n innerIterator = next.value[Symbol.iterator]();\n }\n const result = innerIterator.next();\n if (!result.done) {\n return result;\n }\n innerIterator = undefined;\n }\n }\n return {\n next\n };\n }\n});\n/**\n * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values.\n *\n * **Details**\n *\n * This combines mapping and filtering in a single operation. The function is\n * applied to each element, and only elements that result in `Result.succeed`\n * are included in the result.\n *\n * **Example** (Filtering and transforming Result values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse strings to numbers, keeping only valid ones\n * const strings = [\"1\", \"2\", \"invalid\", \"4\", \"not-a-number\"]\n * const numbers = Iterable.filterMap(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 4]\n *\n * // Extract specific properties from objects\n * const users = [\n * { name: \"Alice\", age: 25, email: \"alice@example.com\" },\n * { name: \"Bob\", age: 17, email: undefined },\n * { name: \"Charlie\", age: 30, email: \"charlie@example.com\" },\n * { name: \"David\", age: 16, email: undefined }\n * ]\n * const adultEmails = Iterable.filterMap(\n * users,\n * (user) =>\n * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid\n * )\n * Array.from(adultEmails) // => [\"alice@example.com\", \"charlie@example.com\"]\n *\n * // Use index in transformation\n * const items = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const evenIndexItems = Iterable.filterMap(\n * items,\n * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid\n * )\n * Array.from(evenIndexItems) // => [\"0: a\", \"2: c\", \"4: e\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms all elements of the `Iterable` for as long as the specified function succeeds.\n *\n * **Example** (Filtering and transforming until failure)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse numbers until we hit an invalid one\n * const strings = [\"1\", \"2\", \"3\", \"invalid\", \"4\", \"5\"]\n * const numbers = Iterable.filterMapWhile(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 3]\n *\n * // Take elements while they meet a condition and transform them\n * const values = [2, 4, 6, 7, 8, 10]\n * const doubledEvens = Iterable.filterMapWhile(\n * values,\n * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid\n * )\n * Array.from(doubledEvens) // => [4, 8, 12]\n *\n * // Process with index until condition fails\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const indexedUntilC = Iterable.filterMapWhile(\n * letters,\n * (letter, i) => letter !== \"c\" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid\n * )\n * Array.from(indexedUntilC) // => [\"0: a\", \"1: b\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapWhile = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n if (iterator !== undefined) {\n const result = iterator.next();\n if (!result.done) {\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n }\n iterator = undefined;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Retrieves the `Some` values from an `Iterable` of `Option`s.\n *\n * **Example** (Extracting Some values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (O.isSome(result.value)) {\n return {\n done: false,\n value: result.value.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the failure values from an iterable of\n * `Result`s, skipping successful results.\n *\n * **Example** (Extracting failures)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getFailures([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [\"err\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 4.0.0\n */\nexport const getFailures = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isFailure(result.value)) {\n return {\n done: false,\n value: result.value.failure\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the success values from an iterable of\n * `Result`s, skipping failed results.\n *\n * **Example** (Extracting successes)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getSuccesses([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [1, 2]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 4.0.0\n */\nexport const getSuccesses = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isSuccess(result.value)) {\n return {\n done: false,\n value: result.value.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Filters an iterable to only include elements that match a predicate.\n *\n * **Details**\n *\n * This function creates a new iterable containing only the elements for which\n * the predicate function returns true. Like map, this operation is lazy and\n * elements are only tested when the iterable is consumed.\n *\n * **Example** (Filtering elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Filter even numbers\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evens = Iterable.filter(numbers, (x) => x % 2 === 0)\n * Array.from(evens) // => [2, 4, 6]\n *\n * // Filter with index\n * const items = [\"a\", \"b\", \"c\", \"d\"]\n * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1)\n * Array.from(oddPositions) // => [\"b\", \"d\"]\n *\n * // Type refinement\n * const mixed: Array<string | number> = [\"hello\", 42, \"world\", 100]\n * const onlyStrings = Iterable.filter(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(onlyStrings) // => [\"hello\", \"world\"]\n *\n * // Combine with map\n * const processed = Iterable.map(\n * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2),\n * (x) => x * 10\n * )\n * Array.from(processed) // => [30, 40, 50]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (predicate(result.value, i++)) {\n return {\n done: false,\n value: result.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results.\n *\n * **When to use**\n *\n * Use when working with APIs or functions that return nullable values,\n * providing a clean way to filter out null or undefined while transforming.\n *\n * **Example** (Flat mapping nullable results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Extract valid elements from nullable function results\n * const data = [\"1\", \"2\", \"invalid\", \"4\"]\n * const parsed = Iterable.flatMapNullishOr(data, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? null : num * 2\n * })\n * Array.from(parsed) // => [2, 4, 8]\n *\n * // Safe property access\n * const objects = [\n * { nested: { value: 10 } },\n * { nested: null },\n * { nested: { value: 20 } },\n * {}\n * ]\n * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value)\n * Array.from(values) // => [10, 20]\n *\n * // Working with Map.get (returns undefined for missing keys)\n * const map = new Map([\n * [\"a\", 1],\n * [\"b\", 2],\n * [\"c\", 3]\n * ])\n * const keys = [\"a\", \"x\", \"b\", \"y\", \"c\"]\n * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key))\n * Array.from(foundValues) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapNullishOr = /*#__PURE__*/dual(2, (self, f) => filterMap(self, a => {\n const b = f(a);\n return b == null ? R.failVoid : R.succeed(b);\n}));\n/**\n * Checks whether a predicate holds true for some `Iterable` element.\n *\n * **Example** (Checking whether some element matches)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 3, 5, 7, 8]\n * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0)\n * hasEven // => true\n *\n * const allOdd = [1, 3, 5, 7]\n * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0)\n * hasEvenInAllOdd // => false\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\"]\n * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2)\n * hasElementAtIndex2 // => true\n *\n * // Early termination - stops at first match\n * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1)\n * const hasEvenInInfiniteOdds = Iterable.some(\n * Iterable.take(infiniteOdds, 1000),\n * (x) => x % 2 === 0\n * )\n * hasEvenInInfiniteOdds // => false\n *\n * // Type guard usage\n * const mixed: Array<string | number> = [1, 2, \"hello\"]\n * const hasString = Iterable.some(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * hasString // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const some = /*#__PURE__*/dual(2, (self, predicate) => {\n let i = 0;\n for (const a of self) {\n if (predicate(a, i++)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Generates an iterable by repeatedly applying a function that produces the\n * next element and state.\n *\n * **Details**\n *\n * This is useful for creating iterables from a generating function that\n * maintains state. The function should return `Option.some([value, nextState])`\n * to continue or `Option.none()` to stop.\n *\n * **Example** (Unfolding state into values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * // Generate Fibonacci sequence\n * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]]))\n * const first10Fib = Iterable.take(fibonacci, 10)\n * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n *\n * // Generate powers of 2 up to a limit\n * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none())\n * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n *\n * // Generate countdown\n * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none())\n * Array.from(countdown) // => [5, 4, 3, 2, 1]\n *\n * // Generate collatz sequence\n * const collatz = Iterable.unfold(7, (n) => {\n * if (n === 1) return Option.none()\n * const next = n % 2 === 0 ? n / 2 : n * 3 + 1\n * return Option.some([n, next])\n * })\n * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (b, f) => ({\n [Symbol.iterator]() {\n let next = b;\n let done = false;\n return {\n next() {\n if (!done) {\n const ab = f(next);\n if (O.isSome(ab)) {\n const [a, b] = ab.value;\n next = b;\n return {\n done: false,\n value: a\n };\n }\n done = true;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n});\n/**\n * Iterates over the `Iterable`, applying `f` to each element.\n *\n * **Example** (Iterating with side effects)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Collect each visited element\n * const numbers = [1, 2, 3, 4, 5]\n * const visited: Array<number> = []\n * Iterable.forEach(numbers, (n) => visited.push(n))\n * visited // => [1, 2, 3, 4, 5]\n *\n * // Use index in the callback\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed: Array<string> = []\n * Iterable.forEach(letters, (letter, i) => {\n * indexed.push(`${i}: ${letter}`)\n * })\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * // Side effects with any iterable\n * const results: Array<number> = []\n * Iterable.forEach(Iterable.range(1, 5), (n) => {\n * results.push(n * n)\n * })\n * results // => [1, 4, 9, 16, 25]\n *\n * // Process in chunks\n * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2)\n * const processed: Array<Array<number>> = []\n * Iterable.forEach(data, (chunk) => {\n * processed.push(Array.from(chunk))\n * })\n * processed // => [[1, 2], [3, 4], [5, 6]]\n * ```\n *\n * @stability stable\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n f(a, i++);\n }\n});\n/**\n * Reduces an iterable to a single value by applying a function to each element and accumulating the result.\n *\n * **Details**\n *\n * This function applies a reducing function against an accumulator and each element\n * of the iterable (from left to right) to reduce it to a single value.\n *\n * **Example** (Reducing an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Sum all numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n)\n * sum // => 15\n *\n * // Find maximum value\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9\n *\n * // Build an object from key-value pairs\n * const pairs = [[\"a\", 1], [\"b\", 2], [\"c\", 3]] as const\n * const obj = Iterable.reduce(\n * pairs,\n * {} as Record<string, number>,\n * (acc, [key, value]) => {\n * acc[key] = value\n * return acc\n * }\n * )\n * obj // => { a: 1, b: 2, c: 3 }\n *\n * // Use index in the reducer\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.reduce(\n * letters,\n * [] as Array<string>,\n * (acc, letter, i) => {\n * acc.push(`${i}: ${letter}`)\n * return acc\n * }\n * )\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n * ```\n *\n * @stability stable\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = /*#__PURE__*/dual(3, (self, b, f) => {\n if (Array.isArray(self)) {\n return self.reduce(f, b);\n }\n let i = 0;\n let result = b;\n for (const n of self) {\n result = f(result, n, i++);\n }\n return result;\n});\n/**\n * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function.\n *\n * **Example** (Deduplicating adjacent elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicates with custom equality\n * const numbers = [1, 1, 2, 2, 3, 1, 1]\n * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b)\n * Array.from(dedupedNumbers) // => [1, 2, 3, 1]\n *\n * // Case-insensitive deduplication\n * const words = [\"Hello\", \"HELLO\", \"world\", \"World\", \"test\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive)\n * Array.from(dedupedWords) // => [\"Hello\", \"world\", \"test\"]\n *\n * // Deduplication by object property\n * const users = [\n * { id: 1, name: \"Alice\" },\n * { id: 1, name: \"Alice Updated\" }, // different name, same id\n * { id: 2, name: \"Bob\" },\n * { id: 2, name: \"Bob\" },\n * { id: 3, name: \"Charlie\" }\n * ]\n * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id\n * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId)\n * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3]\n *\n * // Approximate numeric equality\n * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual)\n * Array.from(dedupedFloats) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let first = true;\n let last;\n function next() {\n while (true) {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n if (first) {\n first = false;\n last = result.value;\n return result;\n }\n const current = result.value;\n if (!isEquivalent(last, current)) {\n last = current;\n return result;\n }\n }\n }\n return {\n next\n };\n }\n}));\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * **Example** (Deduplicating adjacent elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicate numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const deduped = Iterable.dedupeAdjacent(numbers)\n * Array.from(deduped) // => [1, 2, 3, 1]\n *\n * // Remove adjacent duplicate characters\n * const letters = \"aabbccaa\"\n * const dedupedLetters = Iterable.dedupeAdjacent(letters)\n * Array.from(dedupedLetters) // => [\"a\", \"b\", \"c\", \"a\"]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\" },\n * { type: \"A\" },\n * { type: \"B\" },\n * { type: \"B\" },\n * { type: \"A\" }\n * ]\n * const dedupedObjects = Iterable.dedupeAdjacent(objects)\n * Array.from(dedupedObjects, (object) => object.type) // => [\"A\", \"B\", \"A\"]\n *\n * // Clean up streaming data\n * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100]\n * const cleanedData = Iterable.dedupeAdjacent(sensorData)\n * Array.from(cleanedData) // => [100, 101, 102, 100]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacent = /*#__PURE__*/dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Zips this Iterable crosswise with the specified Iterable using the specified combiner.\n *\n * **Example** (Combining cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Create coordinate pairs\n * const xs = [1, 2]\n * const ys = [\"a\", \"b\", \"c\"]\n * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`)\n * Array.from(coordinates) // => [\"(1,a)\", \"(1,b)\", \"(1,c)\", \"(2,a)\", \"(2,b)\", \"(2,c)\"]\n *\n * // Generate all combinations of options\n * const sizes = [\"S\", \"M\", \"L\"]\n * const colors = [\"red\", \"blue\"]\n * const products = Iterable.cartesianWith(\n * sizes,\n * colors,\n * (size, color) => ({ size, color })\n * )\n * Array.from(products, ({ color, size }) => `${size}:${color}`) // => [\"S:red\", \"S:blue\", \"M:red\", \"M:blue\", \"L:red\", \"L:blue\"]\n *\n * // Mathematical operations on all pairs\n * const a = [1, 2, 3]\n * const b = [10, 20]\n * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y)\n * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60]\n *\n * // Create test data combinations\n * const userTypes = [\"admin\", \"user\"]\n * const features = [\"read\", \"write\", \"delete\"]\n * const testCases = Iterable.cartesianWith(\n * userTypes,\n * features,\n * (user, feature) => `${user}_can_${feature}`\n * )\n * Array.from(testCases) // => [\"admin_can_read\", \"admin_can_write\", \"admin_can_delete\", \"user_can_read\", \"user_can_write\", \"user_can_delete\"]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const cartesianWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const cache = [];\n let iterator;\n let done = false;\n const replay = {\n [Symbol.iterator]() {\n let index = 0;\n return {\n next() {\n if (index < cache.length) {\n return {\n done: false,\n value: cache[index++]\n };\n }\n if (done) {\n return {\n done: true,\n value: undefined\n };\n }\n iterator ??= that[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) {\n done = true;\n return {\n done: true,\n value: undefined\n };\n }\n cache.push(result.value);\n index++;\n return result;\n }\n };\n }\n };\n return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator]();\n }\n}));\n/**\n * Zips this Iterable crosswise with the specified Iterable.\n *\n * **Example** (Generating cartesian pairs)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // All pairs of numbers and letters\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\"]\n * const pairs = Iterable.cartesian(numbers, letters)\n * Array.from(pairs) // => [[1, \"a\"], [1, \"b\"], [2, \"a\"], [2, \"b\"], [3, \"a\"], [3, \"b\"]]\n *\n * // Generate coordinate grid\n * const x = [0, 1, 2]\n * const y = [0, 1]\n * const grid = Iterable.cartesian(x, y)\n * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]\n *\n * // All combinations for testing\n * const browsers = [\"chrome\", \"firefox\"]\n * const devices = [\"desktop\", \"mobile\", \"tablet\"]\n * const testMatrix = Iterable.cartesian(browsers, devices)\n * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => [\"chrome:desktop\", \"chrome:mobile\", \"chrome:tablet\", \"firefox:desktop\", \"firefox:mobile\", \"firefox:tablet\"]\n *\n * // Empty iterable results in empty cartesian product\n * const empty = Iterable.empty<number>()\n * const withEmpty = Iterable.cartesian([1, 2], empty)\n * Array.from(withEmpty) // => []\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const cartesian = /*#__PURE__*/dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b]));\n/**\n * Computes how many elements of the iterable pass the given predicate.\n *\n * **Example** (Counting matching elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2\n * ```\n *\n * @stability stable\n * @category folding\n * @since 3.16.0\n */\nexport const countBy = /*#__PURE__*/dual(2, (self, f) => {\n let count = 0;\n let i = 0;\n for (const a of self) {\n if (f(a, i)) {\n count++;\n }\n i++;\n }\n return count;\n});\n//# sourceMappingURL=Iterable.js.map","import * as Context from \"../Context.js\";\n/** @internal */\nexport const Random = /*#__PURE__*/Context.Reference(\"effect/Random\", {\n defaultValue: () => ({\n nextIntUnsafe() {\n return Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;\n },\n nextDoubleUnsafe() {\n return Math.random();\n }\n })\n});\n/** @internal */\nexport const nextBetween = (min, max, draw) => {\n const value = draw * (max - min) + min;\n if (value !== max || min >= max || !Number.isFinite(max)) {\n return value;\n }\n // Rounding can reach the excluded endpoint even for a draw below 1.\n // Return its immediate predecessor, which is at least min for finite min < max.\n if (max === 0) {\n return -Number.MIN_VALUE;\n }\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, max);\n const bits = view.getBigUint64(0);\n view.setBigUint64(0, max > 0 ? bits - BigInt(1) : bits + BigInt(1));\n return view.getFloat64(0);\n};\n//# sourceMappingURL=random.js.map","import * as Equal from \"./Equal.js\";\nimport { format } from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport * as Hash from \"./Hash.js\";\nimport { NodeInspectSymbol, toJson } from \"./Inspectable.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/MutableHashMap\";\n/**\n * Checks whether the specified value is a `MutableHashMap`, `false` otherwise.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before treating it as a mutable hash map.\n *\n * **Details**\n *\n * The check looks for the `MutableHashMap` runtime marker.\n *\n * **Gotchas**\n *\n * The check does not validate the key or value types carried by the map.\n *\n * @see {@link MutableHashMap} for the mutable hash map interface\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isMutableHashMap = value => hasProperty(value, TypeId);\nconst MutableHashMapProto = {\n [TypeId]: TypeId,\n [Symbol.iterator]() {\n return this.backing[Symbol.iterator]();\n },\n toString() {\n return `MutableHashMap(${format(Array.from(this))})`;\n },\n toJSON() {\n return {\n _id: \"MutableHashMap\",\n values: toJson(Array.from(this))\n };\n },\n [NodeInspectSymbol]() {\n return this.toJSON();\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Creates an empty MutableHashMap.\n *\n * **When to use**\n *\n * Use to create a fresh mutable map before adding entries over time.\n *\n * **Details**\n *\n * Each call returns a new empty map instance.\n *\n * **Example** (Creating an empty map)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n *\n * // Add some entries\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n *\n * MutableHashMap.size(map) // => 2\n * ```\n *\n * @see {@link make} for creating a map from explicit entries\n * @see {@link fromIterable} for creating a map from an iterable of entries\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => {\n const self = Object.create(MutableHashMapProto);\n self.backing = new Map();\n self.buckets = new Map();\n return self;\n};\n/**\n * Creates a MutableHashMap from a variable number of key-value pairs.\n *\n * **When to use**\n *\n * Use to create a mutable hash map from explicit entries known at the call site.\n *\n * **Example** (Creating a map from entries)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.size(map) // => 3\n * ```\n *\n * @see {@link empty} for creating an empty map\n * @see {@link fromIterable} for creating a map from an iterable of entries\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...entries) => fromIterable(entries);\n/**\n * Creates a MutableHashMap from an iterable collection of key-value pairs.\n *\n * **When to use**\n *\n * Use to create a mutable hash map from an existing iterable of entries.\n *\n * **Example** (Creating a map from an iterable)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const entries = [\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * ] as const\n *\n * const map = MutableHashMap.fromIterable(entries)\n *\n * MutableHashMap.get(map, \"banana\") // => Option.some(2)\n * MutableHashMap.size(map) // => 3\n *\n * // Works with any iterable\n * const fromMap = MutableHashMap.fromIterable(new Map([[\"x\", 10], [\"y\", 20]]))\n * MutableHashMap.get(fromMap, \"x\") // => Option.some(10)\n * ```\n *\n * @see {@link make} for creating a map from explicit entries\n * @see {@link empty} for creating an empty map\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = entries => {\n const self = empty();\n for (const [key, value] of entries) {\n set(self, key, value);\n }\n return self;\n};\n/**\n * Looks up a key in the `MutableHashMap` safely.\n *\n * **When to use**\n *\n * Use to safely read a `MutableHashMap` value for a key as an `Option`.\n *\n * **Details**\n *\n * Returns `Some(value)` when an equal key is present and `None` when the key is\n * absent.\n *\n * **Example** (Getting a value)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"key1\", 42], [\"key2\", 100])\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.get(map, \"key3\") // => Option.none()\n *\n * // Pipe-able version\n * MutableHashMap.get(\"key1\")(map) // => Option.some(42)\n * ```\n *\n * @see {@link has} for checking only whether a key is present\n * @see {@link set} for inserting or replacing a value by key\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => {\n if (self.backing.has(key)) {\n return Option.some(self.backing.get(key));\n } else if (isSimpleKey(key)) {\n return Option.none();\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return Option.none();\n }\n return getFromBucket(self, bucket, key);\n});\nconst isSimpleKey = u => typeof u !== \"object\" && typeof u !== \"function\";\n/**\n * Returns an iterable over the keys in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to iterate over the keys currently stored in a mutable hash map.\n *\n * **Example** (Reading keys)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * )\n *\n * Array.from(MutableHashMap.keys(map)) // => [\"apple\", \"banana\", \"cherry\"]\n * ```\n *\n * @see {@link values} for iterating over stored values\n * @see {@link has} for checking one key without iterating\n *\n * @stability stable\n * @category getters\n * @since 3.8.0\n */\nexport const keys = self => self.backing.keys();\n/**\n * Returns an iterable over the values in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to iterate over the values currently stored in a mutable hash map.\n *\n * **Example** (Reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * )\n *\n * const allValues = Array.from(MutableHashMap.values(map)) // => [1, 2, 3]\n *\n * // Useful for calculations\n * allValues.reduce((sum, value) => sum + value, 0) // => 6\n *\n * // Filter values\n * allValues.filter((value) => value > 1) // => [2, 3]\n * ```\n *\n * @see {@link keys} for iterating over stored keys\n *\n * @stability stable\n * @category getters\n * @since 3.8.0\n */\nexport const values = self => self.backing.values();\nconst getFromBucket = (self, bucket, key) => {\n for (let i = 0, len = bucket.length; i < len; i++) {\n if (Equal.equals(key, bucket[i])) {\n const refKey = bucket[i];\n return Option.some(self.backing.get(refKey));\n }\n }\n return Option.none();\n};\n/**\n * Checks whether the MutableHashMap contains the specified key.\n *\n * **When to use**\n *\n * Use to test whether a key is present in a `MutableHashMap` without reading\n * its value.\n *\n * **Example** (Checking for a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make([\"key1\", 42], [\"key2\", 100])\n *\n * MutableHashMap.has(map, \"key1\") // => true\n * MutableHashMap.has(map, \"key3\") // => false\n *\n * // Pipe-able version\n * MutableHashMap.has(\"key1\")(map) // => true\n * ```\n *\n * @see {@link get} for reading the value as an `Option`\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => Option.isSome(get(self, key)));\n/**\n * Sets a key-value pair in the MutableHashMap, mutating the map in place.\n * If the key already exists, its value is updated.\n *\n * **When to use**\n *\n * Use to insert a new `MutableHashMap` entry or replace an existing entry in\n * place.\n *\n * **Example** (Setting key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n *\n * // Add new entries\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.size(map) // => 2\n *\n * // Update existing entry\n * MutableHashMap.set(map, \"key1\", 999)\n * MutableHashMap.get(map, \"key1\") // => Option.some(999)\n *\n * // Pipe-able version\n * MutableHashMap.set(\"key3\", 300)(map)\n * MutableHashMap.size(map) // => 3\n * ```\n *\n * @see {@link modify} for updating an existing value with a function\n * @see {@link modifyAt} for setting or removing based on the current optional value\n * @see {@link remove} for deleting an entry by key\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => {\n if (self.backing.has(key) || isSimpleKey(key)) {\n self.backing.set(key, value);\n return self;\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n self.buckets.set(hash, [key]);\n self.backing.set(key, value);\n return self;\n }\n let refKey = getRefKey(bucket, key);\n if (refKey === undefined) {\n bucket.push(key);\n refKey = key;\n }\n self.backing.set(refKey, value);\n return self;\n});\nconst getRefKey = (bucket, key) => {\n for (let i = 0, len = bucket.length; i < len; i++) {\n if (Equal.equals(key, bucket[i])) {\n return bucket[i];\n }\n }\n};\n/**\n * Updates the value of the specified key within the MutableHashMap if it exists.\n * If the key doesn't exist, the map remains unchanged.\n *\n * **When to use**\n *\n * Use to transform an existing `MutableHashMap` value in place without\n * inserting missing keys.\n *\n * **Example** (Modifying existing values)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"count\", 5], [\"total\", 100])\n *\n * // Increment existing value\n * MutableHashMap.modify(map, \"count\", (n) => n + 1)\n * MutableHashMap.get(map, \"count\") // => Option.some(6)\n *\n * // Double existing value\n * MutableHashMap.modify(map, \"total\", (n) => n * 2)\n * MutableHashMap.get(map, \"total\") // => Option.some(200)\n *\n * // Try to modify non-existent key (no effect)\n * MutableHashMap.modify(map, \"missing\", (n) => n + 1)\n * MutableHashMap.has(map, \"missing\") // => false\n *\n * // Pipe-able version\n * MutableHashMap.modify(\"count\", (n: number) => n + 1)(map)\n * MutableHashMap.get(map, \"count\") // => Option.some(7)\n * ```\n *\n * @see {@link set} for inserting or replacing a value directly\n * @see {@link modifyAt} for handling both missing and existing keys\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(3, (self, key, f) => {\n const hasKey = self.backing.has(key);\n if (hasKey || isSimpleKey(key)) {\n if (hasKey) {\n self.backing.set(key, f(self.backing.get(key)));\n }\n return self;\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return self;\n }\n const refKey = getRefKey(bucket, key);\n if (refKey === undefined) {\n return self;\n }\n self.backing.set(refKey, f(self.backing.get(refKey)));\n return self;\n});\n/**\n * Updates or removes the specified key using a function from the current\n * optional value to the next optional value.\n *\n * **When to use**\n *\n * Use to decide whether to insert, update, or remove a key based on its current\n * optional value.\n *\n * **Example** (Updating or removing a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"count\", 5])\n *\n * // Update existing key\n * MutableHashMap.modifyAt(\n * map,\n * \"count\",\n * (option) => Option.map(option, (n) => n * 2)\n * )\n * MutableHashMap.get(map, \"count\") // => Option.some(10)\n *\n * // Add new key\n * MutableHashMap.modifyAt(\n * map,\n * \"new\",\n * (option) => Option.isNone(option) ? Option.some(42) : option\n * )\n * MutableHashMap.get(map, \"new\") // => Option.some(42)\n *\n * // Remove key by returning None\n * MutableHashMap.modifyAt(map, \"count\", () => Option.none())\n * MutableHashMap.get(map, \"count\") // => Option.none()\n *\n * // Conditional update\n * MutableHashMap.modifyAt(\n * map,\n * \"new\",\n * (option) => Option.filter(option, (n) => n > 50) // Remove if <= 50\n * )\n * MutableHashMap.get(map, \"new\") // => Option.none()\n * ```\n *\n * @see {@link modify} for updating only when the key already exists\n * @see {@link set} for inserting or replacing directly\n * @see {@link remove} for deleting directly\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modifyAt = /*#__PURE__*/dual(3, (self, key, f) => {\n const current = get(self, key);\n const result = f(current);\n if (Option.isNone(result)) {\n if (Option.isSome(current)) {\n remove(self, key);\n }\n return self;\n }\n set(self, key, result.value);\n return self;\n});\n/**\n * Removes the specified key from the MutableHashMap, mutating the map in place.\n * If the key doesn't exist, the map remains unchanged.\n *\n * **When to use**\n *\n * Use to delete one key from a mutable hash map in place.\n *\n * **Example** (Removing a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.size(map) // => 3\n *\n * // Remove existing key\n * MutableHashMap.remove(map, \"key2\")\n * MutableHashMap.size(map) // => 2\n * MutableHashMap.has(map, \"key2\") // => false\n *\n * // Remove non-existent key (no effect)\n * MutableHashMap.remove(map, \"nonexistent\")\n * MutableHashMap.size(map) // => 2\n *\n * // Pipe-able version\n * MutableHashMap.remove(\"key1\")(map)\n * MutableHashMap.size(map) // => 1\n * ```\n *\n * @see {@link clear} for removing all entries\n * @see {@link modifyAt} for conditionally removing based on the current value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key_) => {\n if (isSimpleKey(key_)) {\n self.backing.delete(key_);\n return self;\n }\n const hash = Hash.hash(key_);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return self;\n }\n for (let i = 0, len = bucket.length; i < len; i++) {\n const bkey = bucket[i];\n if (bkey === key_ || Equal.equals(key_, bkey)) {\n self.backing.delete(bkey);\n bucket.splice(i, 1);\n break;\n }\n }\n if (bucket.length === 0) {\n self.buckets.delete(hash);\n }\n return self;\n});\n/**\n * Removes all key-value pairs from the MutableHashMap, mutating the map in place.\n * The map becomes empty after this operation.\n *\n * **When to use**\n *\n * Use to empty a mutable hash map while keeping the same map instance.\n *\n * **Example** (Clearing all entries)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.size(map) // => 3\n *\n * // Clear all entries\n * MutableHashMap.clear(map)\n *\n * MutableHashMap.size(map) // => 0\n * MutableHashMap.has(map, \"key1\") // => false\n *\n * // Can still add new entries after clearing\n * MutableHashMap.set(map, \"new\", 999)\n * Array.from(map) // => [[\"new\", 999]]\n * ```\n *\n * @see {@link remove} for deleting one key\n * @see {@link empty} for creating a fresh empty map\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const clear = self => {\n self.backing.clear();\n self.buckets.clear();\n return self;\n};\n/**\n * Returns the number of key-value pairs in the MutableHashMap.\n *\n * **When to use**\n *\n * Use to read how many entries are currently stored in the mutable hash map.\n *\n * **Example** (Checking map size)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n * MutableHashMap.size(map) // => 0\n *\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n * MutableHashMap.size(map) // => 2\n *\n * MutableHashMap.remove(map, \"key1\")\n * MutableHashMap.size(map) // => 1\n *\n * MutableHashMap.clear(map)\n * MutableHashMap.size(map) // => 0\n * ```\n *\n * @see {@link isEmpty} for checking whether the map has no entries\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => self.backing.size;\n/**\n * Returns `true` when the `MutableHashMap` contains no key-value pairs.\n *\n * **When to use**\n *\n * Use to branch on whether a mutable map currently has any entries.\n *\n * @see {@link size} for reading the exact number of entries\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const isEmpty = self => self.backing.size === 0;\n/**\n * Runs a callback for each key-value pair in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to run a synchronous side-effecting callback for every key-value pair in\n * an existing mutable map.\n *\n * **Details**\n *\n * Iteration follows the backing map's order. The callback receives the value\n * first and the key second, matching `Map.prototype.forEach`.\n *\n * @see {@link keys} for iterating only keys\n * @see {@link values} for iterating only values\n *\n * @stability stable\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => {\n self.backing.forEach(f);\n});\n//# sourceMappingURL=MutableHashMap.js.map","/**\n * Records and reads measurements from Effect programs.\n *\n * A `Metric<Input, State>` accepts typed update values and stores an aggregated\n * state that can be read directly or included in a snapshot. Metrics are used\n * for counters, gauges, frequencies, histograms, summaries, and timers. This\n * module includes metric constructors, update and read helpers, attributes,\n * histogram boundaries, registry snapshots, text dumps, and controls for\n * enabling runtime metrics.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport { constUndefined, constVoid, dual, identity } from \"./Function.js\";\nimport { withFiberSucceed } from \"./internal/core.js\";\nimport * as InternalEffect from \"./internal/effect.js\";\nimport { FiberRuntimeMetricsKey as InternalFiberRuntimeMetricsKey } from \"./internal/fiberCachedKeys.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Order from \"./Order.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as _String from \"./String.js\";\n/**\n * Service key for the current metric attributes context.\n *\n * **Example** (Accessing the current metric attributes key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // The key is used internally by the Effect runtime to manage metric attributes\n * const key = Metric.CurrentMetricAttributesKey\n *\n * // Create metrics with base attributes\n * const requestCounter = Metric.counter(\"requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n *\n * // The CurrentMetricAttributes service provides default attributes\n * // that get applied to all metrics in the current context\n * const baseAttributes = { service: \"api\", version: \"1.0\" }\n *\n * // Use withAttributes to apply attributes to metrics\n * const taggedCounter1 = Metric.withAttributes(requestCounter, baseAttributes)\n * const program1 = Metric.update(taggedCounter1, 1)\n *\n * const taggedCounter2 = Metric.withAttributes(requestCounter, {\n * ...baseAttributes,\n * endpoint: \"/users\"\n * })\n * const program2 = Metric.update(taggedCounter2, 5)\n *\n * yield* program1\n * yield* program2\n *\n * return {\n * keyValue: key, // \"effect/Metric/CurrentMetricAttributes\"\n * keyType: typeof key, // \"string\"\n * isConstant: key === \"effect/Metric/CurrentMetricAttributes\" // true\n * }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const key = result // => { keyValue: \"effect/Metric/CurrentMetricAttributes\", keyType: \"string\", isConstant: true }\n * ```\n *\n * @stability stable\n * @category constants\n * @since 4.0.0\n */\nexport const CurrentMetricAttributesKey = \"effect/Metric/CurrentMetricAttributes\";\n/**\n * Context reference for metric attributes applied from the current Effect\n * context.\n *\n * **When to use**\n *\n * Use to provide default attributes that should be merged into metric updates\n * and reads in a scoped part of a program.\n *\n * **Details**\n *\n * The default value is an empty attribute set. Metric reads and updates merge\n * these contextual attributes with the metric's own attributes to select the\n * metric series being accessed.\n *\n * **Example** (Providing current metric attributes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Access current metric attributes\n * yield* Metric.CurrentMetricAttributes\n *\n * // Set new attributes context\n * const newAttributes = { service: \"api\", version: \"1.0\" }\n * const result = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const updatedAttributes = yield* Metric.CurrentMetricAttributes\n * return updatedAttributes\n * }),\n * Metric.CurrentMetricAttributes,\n * newAttributes\n * )\n *\n * return result\n * })\n *\n * const attributes = await Effect.runPromise(program)\n * const actual = attributes // => { service: \"api\", version: \"1.0\" }\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const CurrentMetricAttributes = /*#__PURE__*/Context.Reference(CurrentMetricAttributesKey, {\n defaultValue: () => ({})\n});\nconst MetricRegistryKey = \"effect/Metric/MetricRegistry\";\n/**\n * Context reference for the metric registry in the current context.\n *\n * **When to use**\n *\n * Use when you need a custom metric registry for an isolated program or test\n * instead of the default registry.\n *\n * **Details**\n *\n * By default, the reference creates an empty `Map` the first time it is\n * resolved. Metrics register their metadata and hooks lazily in this map when\n * they are read or updated.\n *\n * **Gotchas**\n *\n * Because `Context.Reference` caches default values, the default `Map` is\n * shared by contexts that do not provide an override. Provide `MetricRegistry`\n * with a fresh `Map` when isolation matters.\n *\n * @see {@link snapshot} for reading all registered metrics from the current `Effect` context\n * @see {@link snapshotUnsafe} for reading all registered metrics from an explicit `Context`\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const MetricRegistry = /*#__PURE__*/Context.Reference(MetricRegistryKey, {\n defaultValue: () => new Map()\n});\nconst TypeId = \"~effect/Metric\";\nclass Metric$ {\n [TypeId] = TypeId;\n // The last series resolved through this metric and its contextual attributes.\n #extraAttributes;\n #series;\n // Series resolved by this metric, keyed by serialized contextual attributes.\n #cache;\n id;\n description;\n attributes;\n constructor(id, description, attributes) {\n this.id = id;\n this.description = description;\n this.attributes = attributes;\n }\n valueUnsafe(context) {\n return this.run(\"get\", undefined, context, this);\n }\n modifyUnsafe(input, context) {\n return this.run(\"modify\", input, context, this);\n }\n updateUnsafe(input, context) {\n return this.run(\"update\", input, context, this);\n }\n // Runs an operation through the wrapper chain. `slot` is the metric the\n // caller holds: it keeps its own last series, so sibling wrappers do not\n // evict each other.\n run(op, input, context, slot) {\n const hooks = this.hook(context, slot);\n return op === \"get\" ? hooks.get(context) : hooks[op](input, context);\n }\n hook(context, slot) {\n const series = this.series(context, slot);\n // The registry owns the series, so it is looked up on every update.\n const registry = Context.get(context, MetricRegistry);\n let metadata = registry.get(series.key);\n if (Predicate.isUndefined(metadata)) {\n metadata = this.metadata(series, this.createHooks());\n registry.set(series.key, metadata);\n }\n return metadata.hooks;\n }\n removeUnsafe(context) {\n Context.get(context, MetricRegistry).delete(this.series(context).key);\n }\n registerUnsafe(context, hooks) {\n const series = this.series(context);\n const key = series.key;\n // Keep the registry from registration time, so removal does not depend on\n // the context it is called from.\n const registry = Context.get(context, MetricRegistry);\n const metadata = this.metadata(series, {\n get: hooks.get,\n update: constVoid,\n modify: constVoid\n });\n registry.set(key, metadata);\n return {\n remove() {\n if (registry.get(key) === metadata) {\n registry.delete(key);\n }\n }\n };\n }\n // Series key and metadata share one merged attribute set.\n series(context, slot = this) {\n const extraAttributes = Context.get(context, CurrentMetricAttributes);\n if (extraAttributes !== slot.#extraAttributes) {\n slot.#extraAttributes = extraAttributes;\n // Finds a known set under a new object, such as a wrapper built per\n // update. The attributes are read once, so key and series agree; a\n // different key order only costs a miss.\n const extra = {\n ...extraAttributes\n };\n const seen = JSON.stringify(extra);\n const cache = this.#cache ??= new Map();\n let series = cache.get(seen);\n if (series === undefined) {\n const merged = mergeAttributes(this.attributes, extra);\n series = {\n key: makeKey(this, merged),\n attributes: seen === \"{}\" ? this.attributes : merged\n };\n // Bounds the cache for attribute values that never repeat.\n if (cache.size >= 1024) cache.clear();\n cache.set(seen, series);\n }\n slot.#series = series;\n }\n return slot.#series;\n }\n metadata(series, hooks) {\n return {\n id: this.id,\n type: this.type,\n description: this.description,\n attributes: series.attributes,\n hooks\n };\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\nconst bigint0 = /*#__PURE__*/BigInt(0);\nclass CounterMetric extends Metric$ {\n type = \"Counter\";\n #bigint;\n #incremental;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#bigint = options?.bigint ?? false;\n this.#incremental = options?.incremental ?? false;\n }\n createHooks() {\n let count = this.#bigint ? bigint0 : 0;\n const canUpdate = this.#incremental ? this.#bigint ? value => value >= bigint0 : value => value >= 0 : _value => true;\n const update = value => {\n if (canUpdate(value)) {\n count = count + value;\n }\n };\n return makeHooks(() => ({\n count,\n incremental: this.#incremental\n }), update);\n }\n}\nclass GaugeMetric extends Metric$ {\n type = \"Gauge\";\n #bigint;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#bigint = options?.bigint ?? false;\n }\n createHooks() {\n let value = this.#bigint ? BigInt(0) : 0;\n const update = input => {\n value = input;\n };\n const modify = input => {\n value = value + input;\n };\n return makeHooks(() => ({\n value\n }), update, modify);\n }\n}\nclass FrequencyMetric extends Metric$ {\n type = \"Frequency\";\n #preregisteredWords;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#preregisteredWords = options?.preregisteredWords;\n }\n createHooks() {\n const occurrences = new Map();\n if (Predicate.isNotUndefined(this.#preregisteredWords)) {\n for (const word of this.#preregisteredWords) {\n occurrences.set(word, 0);\n }\n }\n const update = word => {\n const count = occurrences.get(word) ?? 0;\n occurrences.set(word, count + 1);\n };\n return makeHooks(() => ({\n occurrences: new Map(occurrences)\n }), update);\n }\n}\nclass HistogramMetric extends Metric$ {\n type = \"Histogram\";\n #boundaries;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#boundaries = options.boundaries;\n }\n createHooks() {\n const bounds = this.#boundaries;\n const size = bounds.length;\n const values = new Uint32Array(size + 1);\n const boundaries = new Float64Array(size);\n let count = 0;\n let sum = 0;\n let min = Number.MAX_VALUE;\n let max = -Number.MAX_VALUE;\n Arr.map(Arr.sort(bounds, Order.Number), (n, i) => {\n boundaries[i] = n;\n });\n // Insert the value into the right bucket with a binary search\n const update = value => {\n let from = 0;\n let to = size;\n while (from !== to) {\n const mid = Math.floor(from + (to - from) / 2);\n const boundary = boundaries[mid];\n if (value <= boundary) {\n to = mid;\n } else {\n from = mid;\n }\n // The special case when to / from have a distance of one\n if (to === from + 1) {\n if (value <= boundaries[from]) {\n to = from;\n } else {\n from = to;\n }\n }\n }\n values[from] = values[from] + 1;\n count = count + 1;\n sum = sum + value;\n if (value < min) {\n min = value;\n }\n if (value > max) {\n max = value;\n }\n };\n const getBuckets = () => {\n const builder = Arr.allocate(size);\n let cumulated = 0;\n for (let i = 0; i < size; i++) {\n const boundary = boundaries[i];\n const value = values[i];\n cumulated = cumulated + value;\n builder[i] = [boundary, cumulated];\n }\n return builder;\n };\n return makeHooks(() => ({\n buckets: getBuckets(),\n count,\n min,\n max,\n sum\n }), update);\n }\n}\nclass SummaryMetric extends Metric$ {\n type = \"Summary\";\n #maxAge;\n #maxSize;\n #quantiles;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#maxAge = Math.max(Duration.toMillis(Duration.fromInputUnsafe(options.maxAge)), 0);\n this.#maxSize = options.maxSize;\n this.#quantiles = options.quantiles;\n }\n createHooks() {\n const sortedQuantiles = Arr.sort(this.#quantiles, Order.Number);\n const observations = Arr.allocate(this.#maxSize);\n for (const quantile of this.#quantiles) {\n if (!(quantile >= 0 && quantile <= 1)) {\n throw new Error(`Quantile must be between 0 and 1, found: ${quantile}`);\n }\n }\n let head = 0;\n let count = 0;\n let sum = 0;\n let min = Number.MAX_VALUE;\n let max = -Number.MAX_VALUE;\n const snapshot = now => {\n const builder = [];\n let i = 0;\n while (i < this.#maxSize) {\n const observation = observations[i];\n if (Predicate.isNotUndefined(observation)) {\n const [timestamp, value] = observation;\n const age = now - timestamp;\n if (age >= 0 && age <= this.#maxAge) {\n builder.push(value);\n }\n }\n i = i + 1;\n }\n const samples = Arr.sort(builder, Order.Number);\n const sampleSize = samples.length;\n if (sampleSize === 0) {\n return sortedQuantiles.map(q => [q, undefined]);\n }\n // Compute the value of the quantile in terms of rank:\n // For a given quantile `q`, return the maximum value `v` such that at\n // most `q * n` values are less than or equal to `v`.\n return sortedQuantiles.map(q => {\n if (q <= 0) return [q, samples[0]];\n if (q >= 1) return [q, samples[sampleSize - 1]];\n const index = Math.ceil(q * sampleSize) - 1;\n return [q, samples[index]];\n });\n };\n const observe = (value, timestamp) => {\n if (this.#maxSize > 0) {\n const target = head % this.#maxSize;\n observations[target] = [timestamp, value];\n head = head + 1;\n }\n count = count + 1;\n sum = sum + value;\n if (value < min) {\n min = value;\n }\n if (value > max) {\n max = value;\n }\n };\n const get = context => {\n const clock = Context.get(context, InternalEffect.ClockRef);\n const quantiles = snapshot(clock.currentTimeMillisUnsafe());\n return {\n quantiles,\n count,\n min,\n max,\n sum\n };\n };\n const update = ([value, timestamp]) => observe(value, timestamp);\n return makeHooks(get, update);\n }\n}\n// Every operation maps the context first and the input second, so wrappers\n// such as `withAttributes` address the same series for update, remove and\n// register.\nclass MetricTransform extends Metric$ {\n type;\n metric;\n mapInput;\n mapContext;\n constructor(metric, mapInput, mapContext) {\n super(metric.id, metric.description, metric.attributes);\n this.metric = metric;\n this.mapInput = mapInput;\n this.mapContext = mapContext;\n this.type = metric.type;\n }\n createHooks() {\n return this.metric.createHooks();\n }\n run(op, input, context, slot) {\n const mapped = this.mapContext(context);\n if (op !== \"get\") input = this.mapInput(input, mapped);\n const metric = this.metric;\n // A metric from another copy of this module only has the public methods.\n return metric instanceof Metric$ ? metric.run(op, input, mapped, slot) : op === \"get\" ? metric.valueUnsafe(mapped) : op === \"update\" ? metric.updateUnsafe(input, mapped) : metric.modifyUnsafe(input, mapped);\n }\n removeUnsafe(context) {\n removeUnsafe(this.metric, this.mapContext(context));\n }\n registerUnsafe(context, hooks) {\n return registerUnsafe(this.metric, this.mapContext(context), {\n get: hooks.get,\n update: constVoid,\n modify: constVoid\n });\n }\n}\n/**\n * Returns `true` if the specified value is a `Metric`, otherwise returns `false`.\n *\n * **When to use**\n *\n * Use when you need runtime type checking and ensuring that a value\n * conforms to the Metric interface before performing metric operations.\n *\n * **Example** (Checking metric values)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.isMetric(Metric.counter(\"requests\")) // => true\n * Metric.isMetric({ name: \"requests\" }) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isMetric = u => Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n/**\n * Represents a Counter metric that tracks cumulative numerical values over\n * time. Counters can be incremented and decremented and provide a running total\n * of changes.\n *\n * **Details**\n *\n * The optional `description` describes the counter, and `attributes` attach\n * dimensions to it. Set `bigint` to create a counter that accepts `bigint`\n * inputs. Set `incremental` to `true` to create a counter that can only ever be\n * incremented.\n *\n * **Example** (Creating counter metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a basic counter for tracking requests\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total number of HTTP requests processed\"\n * })\n *\n * // Create an incremental-only counter for events\n * const eventCounter = Metric.counter(\"events_processed\", {\n * description: \"Events processed (increment only)\",\n * incremental: true\n * })\n *\n * // Create a bigint counter for large values\n * const bytesCounter = Metric.counter(\"bytes_transferred\", {\n * description: \"Total bytes transferred\",\n * bigint: true,\n * attributes: { service: \"file-transfer\" }\n * })\n *\n * // Update counters with values\n * yield* Metric.update(requestCounter, 1) // Increment by 1\n * yield* Metric.update(requestCounter, 5) // Increment by 5 (total: 6)\n * yield* Metric.update(eventCounter, 1) // Increment by 1\n * yield* Metric.update(bytesCounter, 1024n) // Add 1024 bytes\n *\n * // Get current counter values\n * const requestValue = yield* Metric.value(requestCounter)\n * const eventValue = yield* Metric.value(eventCounter)\n * const bytesValue = yield* Metric.value(bytesCounter)\n *\n * return { requestValue, eventValue, bytesValue }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const counts = [result.requestValue.count, result.eventValue.count, result.bytesValue.count] // => [6, 1, 1024n]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const counter = (name, options) => new CounterMetric(name, options);\n/**\n * Represents a `Gauge` metric that tracks and reports a single numerical value\n * at a specific moment.\n *\n * **When to use**\n *\n * Use when you need a metric for instantaneous values, such as memory usage or\n * CPU load.\n *\n * **Details**\n *\n * The optional `description` describes the gauge, and `attributes` attach\n * dimensions to it. Set `bigint` to create a gauge that accepts `bigint`\n * inputs.\n *\n * **Example** (Creating gauge metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a gauge for tracking memory usage\n * const memoryGauge = Metric.gauge(\"memory_usage_mb\", {\n * description: \"Current memory usage in megabytes\"\n * })\n *\n * // Create a gauge for CPU utilization\n * const cpuGauge = Metric.gauge(\"cpu_utilization\", {\n * description: \"Current CPU utilization percentage\",\n * attributes: { host: \"server-01\" }\n * })\n *\n * // Create a bigint gauge for large values\n * const diskSpaceGauge = Metric.gauge(\"disk_free_bytes\", {\n * description: \"Free disk space in bytes\",\n * bigint: true\n * })\n *\n * // Set gauge values (replaces current value)\n * yield* Metric.update(memoryGauge, 512) // Set to 512 MB\n * yield* Metric.update(cpuGauge, 85.5) // Set to 85.5%\n * yield* Metric.update(diskSpaceGauge, 1024000000n) // Set to ~1GB\n *\n * // Modify gauge values (adds to current value)\n * yield* Metric.modify(memoryGauge, 128) // Increase by 128 MB (total: 640)\n * yield* Metric.modify(cpuGauge, -10.5) // Decrease by 10.5% (total: 75%)\n *\n * // Update with new absolute values\n * yield* Metric.update(memoryGauge, 800) // Set to 800 MB (replaces 640)\n *\n * // Get current gauge values\n * const memoryValue = yield* Metric.value(memoryGauge)\n * const cpuValue = yield* Metric.value(cpuGauge)\n * const diskValue = yield* Metric.value(diskSpaceGauge)\n *\n * return { memoryValue, cpuValue, diskValue }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.memoryValue.value, result.cpuValue.value, result.diskValue.value] // => [800, 75, 1024000000n]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const gauge = (name, options) => new GaugeMetric(name, options);\n/**\n * Creates a `Frequency` metric which can be used to count the number of\n * occurrences of a string.\n *\n * **When to use**\n *\n * Use when you need a metric for counting how often a specific event or\n * incident occurs.\n *\n * **Details**\n *\n * The optional `description` describes the frequency, and `attributes` attach\n * dimensions to it. Use `preregisteredWords` to initialize occurrence counts\n * for known string values before updates arrive.\n *\n * **Example** (Creating frequency metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a frequency metric for HTTP status codes\n * const statusFrequency = Metric.frequency(\"http_status_codes\", {\n * description: \"Frequency of HTTP response status codes\",\n * preregisteredWords: [\"200\", \"404\", \"500\"] // Pre-register common codes\n * })\n *\n * // Create a frequency metric for user actions\n * const userActionFrequency = Metric.frequency(\"user_actions\", {\n * description: \"Frequency of user actions performed\",\n * attributes: { application: \"web-app\" }\n * })\n *\n * // Create a frequency metric for error types\n * const errorTypeFrequency = Metric.frequency(\"error_types\", {\n * description: \"Frequency of different error types\"\n * })\n *\n * // Record different occurrences\n * yield* Metric.update(statusFrequency, \"200\") // Success response\n * yield* Metric.update(statusFrequency, \"200\") // Another success\n * yield* Metric.update(statusFrequency, \"404\") // Not found error\n * yield* Metric.update(statusFrequency, \"500\") // Server error\n * yield* Metric.update(statusFrequency, \"200\") // Another success\n *\n * yield* Metric.update(userActionFrequency, \"login\")\n * yield* Metric.update(userActionFrequency, \"view_dashboard\")\n * yield* Metric.update(userActionFrequency, \"login\")\n * yield* Metric.update(userActionFrequency, \"logout\")\n *\n * yield* Metric.update(errorTypeFrequency, \"ValidationError\")\n * yield* Metric.update(errorTypeFrequency, \"NetworkError\")\n * yield* Metric.update(errorTypeFrequency, \"ValidationError\")\n *\n * // Get frequency counts\n * const statusCounts = yield* Metric.value(statusFrequency)\n * const actionCounts = yield* Metric.value(userActionFrequency)\n * const errorCounts = yield* Metric.value(errorTypeFrequency)\n *\n * // statusCounts.occurrences will be:\n * // Map { \"200\" => 3, \"404\" => 1, \"500\" => 1 }\n * // actionCounts.occurrences will be:\n * // Map { \"login\" => 2, \"view_dashboard\" => 1, \"logout\" => 1 }\n * // errorCounts.occurrences will be:\n * // Map { \"ValidationError\" => 2, \"NetworkError\" => 1 }\n *\n * return { statusCounts, actionCounts, errorCounts }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const counts = [\n * result.statusCounts.occurrences.get(\"200\"),\n * result.actionCounts.occurrences.get(\"login\"),\n * result.errorCounts.occurrences.get(\"ValidationError\")\n * ]\n * counts // => [3, 2, 2]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const frequency = (name, options) => new FrequencyMetric(name, options);\n/**\n * Represents a `Histogram` metric that records observations into buckets.\n *\n * **When to use**\n *\n * Use when you need a metric for measuring the distribution of values within a\n * range.\n *\n * **Details**\n *\n * The optional `description` describes the histogram, and `attributes` attach\n * dimensions to it. The required `boundaries` option defines the histogram\n * bucket boundaries.\n *\n * **Example** (Creating histogram metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a histogram for API response times\n * const responseTimeHistogram = Metric.histogram(\"api_response_time\", {\n * description: \"Distribution of API response times in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 50, count: 10 })\n * // Creates buckets: 0-50ms, 50-100ms, 100-150ms, ..., 350-400ms, 400ms+\n * })\n *\n * // Create a histogram for request payload sizes\n * const payloadSizeHistogram = Metric.histogram(\"payload_size\", {\n * description: \"Distribution of request payload sizes in KB\",\n * boundaries: Metric.exponentialBoundaries({ start: 1, factor: 2, count: 8 }),\n * // Creates exponential buckets: 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, 64KB, 128KB+\n * attributes: { service: \"api-gateway\" }\n * })\n *\n * // Create a histogram with custom boundaries\n * const customHistogram = Metric.histogram(\"custom_metric\", {\n * description: \"Custom distribution metric\",\n * boundaries: [0.1, 0.5, 1, 2.5, 5, 10, 25, 50, 100]\n * })\n *\n * // Record various response times\n * yield* Metric.update(responseTimeHistogram, 25) // Goes in 0-50ms bucket\n * yield* Metric.update(responseTimeHistogram, 75) // Goes in 50-100ms bucket\n * yield* Metric.update(responseTimeHistogram, 125) // Goes in 100-150ms bucket\n * yield* Metric.update(responseTimeHistogram, 200) // Goes in 150-200ms bucket\n * yield* Metric.update(responseTimeHistogram, 75) // Another 50-100ms\n *\n * // Record payload sizes\n * yield* Metric.update(payloadSizeHistogram, 3) // Goes in 2-4KB bucket\n * yield* Metric.update(payloadSizeHistogram, 15) // Goes in 8-16KB bucket\n * yield* Metric.update(payloadSizeHistogram, 0.5) // Goes in 0-1KB bucket\n *\n * // Get histogram state with distribution data\n * const responseTimeState = yield* Metric.value(responseTimeHistogram)\n * const payloadSizeState = yield* Metric.value(payloadSizeHistogram)\n *\n * // responseTimeState will contain:\n * // - buckets: [[50, 1], [100, 3], [150, 4], [200, 5], ...]\n * // - count: 5, min: 25, max: 200, sum: 500\n * // - Useful for calculating percentiles, averages, etc.\n *\n * return { responseTimeState, payloadSizeState }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.responseTimeState.count, result.responseTimeState.sum, result.payloadSizeState.count]\n * values // => [5, 500, 3]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const histogram = (name, options) => new HistogramMetric(name, options);\n/**\n * Creates a `Summary` metric that records observations and calculates quantiles\n * which takes a value as input and uses the current time.\n *\n * **When to use**\n *\n * Use when you need a metric that records statistical information about a set\n * of values, including quantiles.\n *\n * **Details**\n *\n * The optional `description` describes the summary, and `attributes` attach\n * dimensions to it. `maxAge` controls how long observations are retained,\n * `maxSize` controls how many observations are kept, and `quantiles` lists the\n * quantiles to calculate, such as `[0.5, 0.9]`.\n *\n * **Example** (Creating summary metrics)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a summary for API response times\n * const responseTimeSummary = Metric.summary(\"api_response_time\", {\n * description: \"API response time quantiles over 5-minute windows\",\n * maxAge: Duration.minutes(5), // Keep observations for 5 minutes\n * maxSize: 1000, // Maximum 1000 observations in memory\n * quantiles: [0.5, 0.9, 0.95, 0.99] // 50th, 90th, 95th, 99th percentiles\n * })\n *\n * // Create a summary for request payload sizes\n * const payloadSizeSummary = Metric.summary(\"request_payload_size\", {\n * description: \"Request payload size distribution over 2-minute windows\",\n * maxAge: Duration.minutes(2), // Shorter window for recent trends\n * maxSize: 500, // Smaller buffer for memory efficiency\n * quantiles: [0.5, 0.75, 0.9], // Median, 75th, 90th percentiles\n * attributes: { service: \"upload-service\" }\n * })\n *\n * // Record deterministic response times\n * const responseTimes = [82, 96, 104, 118, 135, 170, 210, 240]\n * for (const responseTime of responseTimes) {\n * yield* Metric.update(responseTimeSummary, responseTime)\n * }\n *\n * // Record some payload sizes\n * yield* Metric.update(payloadSizeSummary, 1.2) // 1.2KB\n * yield* Metric.update(payloadSizeSummary, 5.8) // 5.8KB\n * yield* Metric.update(payloadSizeSummary, 15.6) // 15.6KB\n * yield* Metric.update(payloadSizeSummary, 3.4) // 3.4KB\n *\n * // Get summary statistics with quantiles\n * const responseStats = yield* Metric.value(responseTimeSummary)\n * const payloadStats = yield* Metric.value(payloadSizeSummary)\n *\n * // Both summaries include quantile information for their configured windows.\n *\n * return { responseStats, payloadStats }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const response = result.responseStats\n * const payload = result.payloadStats\n * const responseValues = [response.count, response.min, response.max, response.sum] // => [8, 82, 240, 1155]\n * const payloadValues = [payload.count, payload.min, payload.max, payload.sum] // => [4, 1.2, 15.6, 26]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const summary = (name, options) => mapInput(summaryWithTimestamp(name, options), (input, context) => [input, Context.get(context, InternalEffect.ClockRef).currentTimeMillisUnsafe()]);\n/**\n * Creates a `Summary` metric that records observations with explicit\n * timestamps and calculates quantiles.\n *\n * **When to use**\n *\n * Use when you need a metric that records statistical information about a set\n * of values together with timestamps.\n *\n * **Details**\n *\n * Inputs to this metric are `[value, timestamp]` pairs; the current clock is\n * used when reading quantiles against the configured `maxAge`.\n *\n * The optional `description` describes the summary, and `attributes` attach\n * dimensions to it. `maxAge` controls how long observations are retained,\n * `maxSize` controls how many observations are kept, and `quantiles` lists the\n * quantiles to calculate, such as `[0.5, 0.9]`.\n *\n * **Example** (Creating summaries with explicit timestamps)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * const responseTimesSummary = Metric.summaryWithTimestamp(\n * \"response_times_summary\",\n * {\n * description: \"Measures the distribution of response times\",\n * maxAge: \"60 seconds\", // Retain observations for 60 seconds.\n * maxSize: 1000, // Keep a maximum of 1000 observations.\n * quantiles: [0.5, 0.9, 0.99] // Calculate 50th, 90th, and 99th quantiles.\n * }\n * )\n * const metadata = [responseTimesSummary.id, responseTimesSummary.type] // => [\"response_times_summary\", \"Summary\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const summaryWithTimestamp = (name, options) => new SummaryMetric(name, options);\n/**\n * Creates a timer metric, based on a `Histogram`, which keeps track of\n * durations in milliseconds.\n *\n * **Details**\n *\n * The unit of time will automatically be added to the metric as a tag (i.e.\n * `\"time_unit: milliseconds\"`).\n *\n * If `options.boundaries` is not provided, the boundaries will be computed\n * using `Metric.exponentialBoundaries({ start: 0.5, factor: 2, count: 35 })`.\n *\n * **Example** (Recording durations with a timer)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Metric } from \"effect\"\n *\n * // Create a timer metric to track API request durations\n * const apiRequestTimer = Metric.timer(\"api_request_duration\", {\n * description: \"Duration of API requests\",\n * attributes: { service: \"user-api\" }\n * })\n *\n * // Record a measured API operation duration\n * const apiOperation = Effect.gen(function*() {\n * const duration = Duration.millis(120)\n * yield* Metric.update(apiRequestTimer, duration)\n *\n * const state = yield* Metric.value(apiRequestTimer)\n * return {\n * count: state.count,\n * min: state.min,\n * max: state.max,\n * sum: state.sum\n * }\n * })\n *\n * await Effect.runPromise(\n * Effect.provideService(apiOperation, Metric.MetricRegistry, new Map())\n * ) // => { count: 1, min: 120, max: 120, sum: 120 }\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const timer = (name, options) => {\n const boundaries = Predicate.isNotUndefined(options?.boundaries) ? options.boundaries : exponentialBoundaries({\n start: 0.5,\n factor: 2,\n count: 35\n });\n const attributes = mergeAttributes(options?.attributes, {\n time_unit: \"milliseconds\"\n });\n const metric = new HistogramMetric(name, {\n ...options,\n boundaries,\n attributes\n });\n return mapInput(metric, Duration.toMillis);\n};\n/**\n * Retrieves the current state of the specified `Metric`.\n *\n * **Details**\n *\n * The returned state depends on the metric type. Counters return\n * `CounterState<number | bigint>` with `count` and `incremental`, gauges return\n * `GaugeState<number | bigint>` with `value`, frequencies return\n * `FrequencyState` with `occurrences`, histograms return `HistogramState` with\n * buckets, count, min, max, and sum, and summaries return `SummaryState` with\n * quantiles, count, min, max, and sum.\n *\n * **Example** (Reading metric state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"modify_requests\")\n * const responseTime = Metric.histogram(\"response_time\", {\n * boundaries: [100, 500, 1000, 2000]\n * })\n *\n * const program = Effect.gen(function*() {\n * // Update metrics\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 750)\n *\n * // Get current values\n * const counterState = yield* Metric.value(requestCounter)\n * const histogramState = yield* Metric.value(responseTime)\n * return {\n * requestCount: counterState.count,\n * count: histogramState.count,\n * min: histogramState.min,\n * max: histogramState.max,\n * average: histogramState.sum / histogramState.count\n * }\n * })\n *\n * await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * ) // => { requestCount: 1, count: 1, min: 750, max: 750, average: 750 }\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const value = self => withFiberSucceed(fiber => self.valueUnsafe(fiber.context));\n/**\n * Modifies the metric with the specified input.\n *\n * **Details**\n *\n * The behavior of `modify` depends on the metric type. Counters add the input\n * value to the current count, gauges add the input value to the current gauge\n * value, frequencies increment the occurrence count for the input string,\n * histograms record the input value in the appropriate bucket, and summaries\n * record the input observation.\n *\n * **Example** (Modifying metric values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const temperatureGauge = Metric.gauge(\"temperature\")\n * const requestCounter = Metric.counter(\"requests\")\n *\n * const program = Effect.gen(function*() {\n * // Set initial temperature\n * yield* Metric.update(temperatureGauge, 20)\n *\n * // Modify by adding/subtracting values\n * yield* Metric.modify(temperatureGauge, 5) // Now 25\n * yield* Metric.modify(temperatureGauge, -3) // Now 22\n *\n * // For counters, modify increments by the specified amount\n * yield* Metric.modify(requestCounter, 10) // Add 10 to counter\n * yield* Metric.modify(requestCounter, 5) // Add 5 more (total: 15)\n *\n * const temp = yield* Metric.value(temperatureGauge)\n * const requests = yield* Metric.value(requestCounter)\n * return [temp.value, requests.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [22, 15]\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 3.6.5\n */\nexport const modify = /*#__PURE__*/dual(2, (self, input) => withFiberSucceed(fiber => self.modifyUnsafe(input, fiber.context)));\n/**\n * Updates the metric with the specified input.\n *\n * **Details**\n *\n * The behavior of `update` depends on the metric type. Counters add the input\n * value to the current count, gauges replace the current value with the input\n * value, frequencies increment the occurrence count for the input string,\n * histograms record the input value in the appropriate bucket, and summaries\n * record the input value as a new observation.\n *\n * **Example** (Updating metric values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const cpuUsage = Metric.gauge(\"cpu_usage_percent\")\n * const httpStatus = Metric.frequency(\"http_status_codes\")\n * const responseTime = Metric.histogram(\"response_time_ms\", {\n * boundaries: [100, 500, 1000, 2000]\n * })\n *\n * const program = Effect.gen(function*() {\n * // Update gauge to specific values\n * yield* Metric.update(cpuUsage, 45.2)\n * yield* Metric.update(cpuUsage, 67.8) // Replaces previous value\n *\n * // Track HTTP status code occurrences\n * yield* Metric.update(httpStatus, \"200\")\n * yield* Metric.update(httpStatus, \"404\")\n * yield* Metric.update(httpStatus, \"200\") // Increments 200 count\n *\n * // Record response times\n * yield* Metric.update(responseTime, 250)\n * yield* Metric.update(responseTime, 750)\n * yield* Metric.update(responseTime, 1500)\n *\n * // Check current states\n * const cpu = yield* Metric.value(cpuUsage)\n * const statuses = yield* Metric.value(httpStatus)\n * const times = yield* Metric.value(responseTime)\n * return [cpu.value, statuses.occurrences.get(\"200\"), times.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [67.8, 2, 3]\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, input) => withFiberSucceed(fiber => self.updateUnsafe(input, fiber.context)));\n/**\n * Removes the series of a metric for the current attributes from the metric\n * registry.\n *\n * **When to use**\n *\n * Use when a series describes something that has gone away, such as a\n * connection or an entity, so the registry and exporters stop tracking it.\n *\n * **Details**\n *\n * The series is identified the same way `update` identifies it: by the metric\n * and its attributes merged with `CurrentMetricAttributes`. Other series of the\n * same metric are left alone. A later update creates the series again from its\n * initial state. Removing a series that does not exist does nothing.\n *\n * **Example** (Removing a series)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const connections = Metric.gauge(\"connections\")\n *\n * const program = Effect.gen(function*() {\n * yield* Metric.update(connections, 3).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"a\" })\n * )\n * yield* Metric.update(connections, 5).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"b\" })\n * )\n * yield* Metric.remove(connections).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"a\" })\n * )\n * const snapshots = yield* Metric.snapshot\n * return snapshots.map((snapshot) => snapshot.attributes)\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [{ pool: \"b\" }]\n * ```\n *\n * @see {@link removeUnsafe} for removing a series with an explicit `Context`\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const remove = self => withFiberSucceed(fiber => removeUnsafe(self, fiber.context));\n/**\n * Removes the series of a metric for the attributes in the provided `Context`\n * from the metric registry in that `Context`.\n *\n * **When to use**\n *\n * Use when a low-level integration already holds a `Context`. Use `remove`\n * in application code.\n *\n * @see {@link remove} for the `Effect` version\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const removeUnsafe = (self, context) => self.removeUnsafe(context);\n/**\n * Registers a series backed by caller-supplied hooks, for gauges whose value is\n * read when metrics are snapshotted rather than pushed with updates.\n *\n * **When to use**\n *\n * Use when the value already lives in some data structure, such as a queue\n * size, and updating a metric on every change would cost more than reading the\n * value at export time.\n *\n * **Details**\n *\n * The series is identified as in `remove`, using the attributes and registry\n * from `context`, and replaces any series with the same identity. `hooks.get`\n * is called each time the series is read, for example by `snapshot` or an\n * exporter. The returned {@link Registration} removes it again.\n * `update` and `modify` on this series do nothing; the supplied mutation hooks\n * are ignored.\n *\n * **Gotchas**\n *\n * The registry keeps `hooks.get` reachable until the series is removed, along\n * with anything it closes over. Call `remove` once the source goes away.\n *\n * **Example** (Reporting a queue size on snapshot)\n *\n * ```ts import.meta.vitest\n * import { Context, Metric } from \"effect\"\n *\n * const context = Context.make(Metric.MetricRegistry, new Map())\n * const queueSize = Metric.gauge(\"queue_size\")\n * const queue: Array<string> = [\"a\", \"b\"]\n *\n * const registration = Metric.registerUnsafe(queueSize, context, {\n * get: () => ({ value: queue.length }),\n * update: () => {},\n * modify: () => {}\n * })\n * queue.push(\"c\")\n * const sizes = Metric.snapshotUnsafe(context).map((snapshot) => snapshot.state)\n * registration.remove()\n *\n * sizes // => [{ value: 3 }]\n * Metric.snapshotUnsafe(context).length // => 0\n * ```\n *\n * @see {@link remove} for removing a series updated with `update`\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const registerUnsafe = (self, context, hooks) => self.registerUnsafe(context, hooks);\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of the specified new type, which must be transformable to the input type of\n * this metric.\n *\n * **Example** (Mapping metric inputs)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const durationHistogram = Metric.histogram(\"request_duration_ms\", {\n * description: \"Request duration in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 100, count: 10 })\n * })\n *\n * // Accept duration strings while recording numeric milliseconds\n * const durationStringHistogram = Metric.mapInput(\n * durationHistogram,\n * (input: string) => Number(input)\n * )\n *\n * const program = Effect.gen(function*() {\n * yield* Metric.update(durationStringHistogram, \"250\")\n * return yield* Metric.value(durationStringHistogram)\n * })\n *\n * const value = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [value.count, value.sum] // => [1, 250]\n * ```\n *\n * @stability stable\n * @category annotations\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => new MetricTransform(self, f, identity));\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of any type, and translates them to updates with the specified constant\n * update value.\n *\n * **Example** (Ignoring inputs with a constant value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * // Create a counter that normally expects a number increment\n * const requestCounter = Metric.counter(\"total_requests\", {\n * description: \"Total number of requests processed\"\n * })\n *\n * // Create a version that always increments by 1, regardless of input\n * const simpleRequestCounter = Metric.withConstantInput(requestCounter, 1)\n *\n * const program = Effect.gen(function*() {\n * // These all increment the counter by 1, ignoring the input value\n * yield* Metric.update(simpleRequestCounter, \"any string\")\n * yield* Metric.update(simpleRequestCounter, { complex: \"object\" })\n * yield* Metric.update(simpleRequestCounter, 999) // Still increments by 1\n *\n * const value = yield* Metric.value(simpleRequestCounter)\n * return value // Counter state will show count: 3\n * })\n *\n * const value = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const count = value.count // => 3\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const withConstantInput = /*#__PURE__*/dual(2, (self, input) => mapInput(self, () => input));\n/**\n * Returns a new metric that applies the specified attributes to all operations.\n *\n * **Details**\n *\n * Attributes are key-value pairs that provide additional context for metrics,\n * enabling filtering, grouping, and more detailed analysis. Each combination\n * of attribute values creates a separate metric series.\n *\n * **Example** (Applying metric attributes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n *\n * // Create tagged versions of the metric\n * const getRequests = Metric.withAttributes(requestCounter, {\n * method: \"GET\",\n * endpoint: \"/api/users\"\n * })\n *\n * const postRequests = Metric.withAttributes(requestCounter, {\n * method: \"POST\",\n * endpoint: \"/api/users\"\n * })\n *\n * const program = Effect.gen(function*() {\n * // These will be tracked as separate metric series\n * yield* Metric.update(getRequests, 1) // http_requests_total{method=\"GET\", endpoint=\"/api/users\"}\n * yield* Metric.update(postRequests, 1) // http_requests_total{method=\"POST\", endpoint=\"/api/users\"}\n * yield* Metric.update(getRequests, 1) // Increments the GET counter\n *\n * // You can also chain attributes\n * const taggedMetric = requestCounter.pipe(\n * Metric.withAttributes({ service: \"user-api\" }),\n * Metric.withAttributes({ version: \"v1\" })\n * )\n *\n * yield* Metric.update(taggedMetric, 1) // http_requests_total{service=\"user-api\", version=\"v1\"}\n * })\n *\n * const result = Effect.gen(function*() {\n * yield* program\n * const get = yield* Metric.value(getRequests)\n * const post = yield* Metric.value(postRequests)\n * return [get.count, post.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(result, Metric.MetricRegistry, new Map())) // => [2, 1]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 4.0.0\n */\nexport const withAttributes = /*#__PURE__*/dual(2, (self, attributes) => {\n return new MetricTransform(self, identity, addAttributesToContext(attributes));\n});\n// Metric Snapshots\n/**\n * Captures a snapshot of all registered metrics in the current context.\n *\n * **Details**\n *\n * Returns an array of metric snapshots, each containing the metric's metadata\n * (name, description, type) and current state (values, counts, etc.).\n *\n * **Example** (Capturing metric snapshots)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create and update some metrics\n * const requestCounter = Metric.counter(\"http_requests\", {\n * description: \"Total HTTP requests\"\n * })\n * const responseTime = Metric.histogram(\"response_time_ms\", {\n * description: \"Response time in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 100, count: 5 })\n * })\n *\n * // Update the metrics with some values\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 150)\n * yield* Metric.update(responseTime, 75)\n *\n * // Take a snapshot of all metrics\n * const snapshots = yield* Metric.snapshot\n *\n * return snapshots\n * })\n *\n * const snapshots = await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * )\n * const ids = snapshots.map((snapshot) => snapshot.id).sort() // => [\"http_requests\", \"response_time_ms\"]\n * ```\n *\n * @stability stable\n * @category snapshotting\n * @since 2.0.0\n */\nexport const snapshot = /*#__PURE__*/withFiberSucceed(fiber => snapshotUnsafe(fiber.context));\n/**\n * Returns a human-readable string representation of all currently registered\n * metrics in a tabular format.\n *\n * **Details**\n *\n * This debugging utility captures a snapshot of all metrics and formats them\n * in an easy-to-read table showing names, descriptions, types, attributes,\n * and current state values.\n *\n * **Example** (Dumping metrics as text)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create and update some metrics for demonstration\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n * const responseTime = Metric.gauge(\"response_time_ms\", {\n * description: \"Current response time in milliseconds\"\n * })\n * const statusFreq = Metric.frequency(\"http_status_codes\", {\n * description: \"Frequency of HTTP status codes\"\n * })\n *\n * // Update metrics with some values\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 125)\n * yield* Metric.update(statusFreq, \"200\")\n * yield* Metric.update(statusFreq, \"404\")\n * yield* Metric.update(statusFreq, \"200\")\n *\n * // Get formatted dump of all metrics\n * const metricsReport = yield* Metric.dump\n * return metricsReport\n * })\n *\n * const report = await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * )\n * const included = [\n * report.includes(\"http_requests_total\"),\n * report.includes(\"response_time_ms\"),\n * report.includes(\"http_status_codes\")\n * ]\n * included // => [true, true, true]\n * ```\n *\n * @stability stable\n * @category formatting\n * @since 4.0.0\n */\nexport const dump = /*#__PURE__*/withFiberSucceed(fiber => {\n const metrics = snapshotUnsafe(fiber.context);\n if (metrics.length > 0) {\n const maxNameLength = metrics.reduce((max, metric) => {\n const length = metric.id.length;\n return length > max ? length : max;\n }, 0) + 2;\n const maxDescriptionLength = metrics.reduce((max, metric) => {\n const length = Predicate.isNotUndefined(metric.description) ? metric.description.length : 0;\n return length > max ? length : max;\n }, 0) + 2;\n const maxTypeLength = metrics.reduce((max, metric) => {\n const length = metric.type.length;\n return length > max ? length : max;\n }, 0) + 2;\n const maxAttributesLength = metrics.reduce((max, metric) => {\n const length = Predicate.isNotUndefined(metric.attributes) ? attributesToString(metric.attributes).length : 0;\n return length > max ? length : max;\n }, 0) + 2;\n const grouped = Object.entries(Arr.groupBy(metrics, metric => metric.id));\n const sorted = Arr.sortWith(grouped, entry => entry[0], _String.Order);\n const rendered = sorted.map(([, group]) => group.map(metric => renderName(metric, maxNameLength) + renderDescription(metric, maxDescriptionLength) + renderType(metric, maxTypeLength) + renderAttributes(metric, maxAttributesLength) + renderState(metric)).join(\"\\n\")).join(\"\\n\");\n return rendered;\n }\n return \"\";\n});\n/**\n * Captures a snapshot of all registered metrics synchronously using the provided\n * service context.\n *\n * **When to use**\n *\n * Use to read metric snapshots from an explicit `Context` in low-level\n * integrations, exporters, or debugging tools that already have the context.\n *\n * **Details**\n *\n * This is the \"unsafe\" version that bypasses Effect's safety guarantees and requires\n * manual handling of the services context. Use the safe `snapshot` function for normal\n * application code.\n *\n * **Example** (Capturing snapshots from a context)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"http_requests\")\n * const program = Effect.gen(function*() {\n * yield* Metric.update(requestCounter, 1)\n * const context = yield* Effect.context()\n * return Metric.snapshotUnsafe(context).map((snapshot) => snapshot.id)\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [\"http_requests\"]\n * ```\n *\n * @stability stable\n * @category snapshotting\n * @since 4.0.0\n */\nexport const snapshotUnsafe = context => {\n const registry = Context.get(context, MetricRegistry);\n return Array.from(registry.values()).map(({\n hooks,\n ...meta\n }) => ({\n ...meta,\n state: hooks.get(context)\n }));\n};\nconst renderName = (metric, padTo) => `name=${metric.id.padEnd(padTo, \" \")}`;\nconst renderDescription = (metric, padTo) => `description=${(metric.description ?? \"\").padEnd(padTo, \" \")}`;\nconst renderType = (metric, padTo) => `type=${metric.type.padEnd(padTo, \" \")}`;\nconst renderAttributes = (metric, padTo) => {\n const attrs = attributesToString(metric.attributes ?? {});\n const padding = \" \".repeat(Math.max(0, padTo - attrs.length));\n return `${attrs}${padding}`;\n};\nconst renderState = metric => {\n const prefix = \"state=\";\n switch (metric.type) {\n case \"Counter\":\n {\n const state = metric.state;\n return `${prefix}[count: [${state.count}]]`;\n }\n case \"Frequency\":\n {\n const state = metric.state;\n return `${prefix}[occurrences: ${renderKeyValues(state.occurrences)}]`;\n }\n case \"Gauge\":\n {\n const state = metric.state;\n return `${prefix}[value: [${state.value}]]`;\n }\n case \"Histogram\":\n {\n const state = metric.state;\n const buckets = `buckets: [${renderKeyValues(state.buckets)}]`;\n const count = `count: [${state.count}]`;\n const min = `min: [${state.min}]`;\n const max = `max: [${state.max}]`;\n const sum = `sum: [${state.sum}]`;\n return `${prefix}[${buckets}, ${count}, ${min}, ${max}, ${sum}]`;\n }\n case \"Summary\":\n {\n const state = metric.state;\n const printableQuantiles = state.quantiles.map(([key, value]) => [key, value ?? 0]);\n const quantiles = `quantiles: [${renderKeyValues(printableQuantiles)}]`;\n const count = `count: [${state.count}]`;\n const min = `min: [${state.min}]`;\n const max = `max: [${state.max}]`;\n const sum = `sum: [${state.sum}]`;\n return `${prefix}[${quantiles}, ${count}, ${min}, ${max}, ${sum}]`;\n }\n }\n};\nconst renderKeyValues = keyValues => Array.from(keyValues).map(([key, value]) => `(${key} -> ${value})`).join(\", \");\nconst attributesToString = attributes => {\n const attrs = Object.entries(attributes);\n const sorted = Arr.sortWith(attrs, attr => attr[0], _String.Order);\n return `attributes=[${sorted.map(([key, value]) => `${key}: ${value}`).join(\", \")}]`;\n};\n// Metric Boundaries\n/**\n * Creates histogram bucket boundaries from an iterable set of values.\n *\n * **Details**\n *\n * Processes any iterable of numbers by removing duplicates, filtering out\n * non-positive values, and automatically appending positive infinity as the\n * final boundary.\n *\n * **Example** (Creating boundaries from values)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.boundariesFromIterable([-5, 0, 10, 10, 25, 50]) // => [10, 25, 50, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const boundariesFromIterable = iterable => Arr.append(Arr.filter(new Set(iterable), n => n > 0), Number.POSITIVE_INFINITY);\n/**\n * Creates histogram bucket boundaries from a linear sequence and appends\n * positive infinity.\n *\n * **Details**\n *\n * Generates `count - 1` candidate boundaries using `start + index * width` for\n * each zero-based index, then applies the same normalization as\n * `boundariesFromIterable`: non-positive values are removed, duplicates are\n * collapsed, and `Infinity` is appended.\n *\n * **Example** (Creating linear boundaries)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.linearBoundaries({ start: 10, width: 20, count: 5 }) // => [10, 30, 50, 70, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const linearBoundaries = options => boundariesFromIterable(Arr.makeBy(options.count - 1, n => options.start + n * options.width));\n/**\n * Creates histogram bucket boundaries with exponentially increasing values.\n *\n * **Details**\n *\n * Creates boundaries that grow exponentially, useful for metrics that span\n * multiple orders of magnitude. Each boundary is calculated as start * factor^i.\n *\n * **Example** (Creating exponential boundaries)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.exponentialBoundaries({ start: 1, factor: 2, count: 5 }) // => [1, 2, 4, 8, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const exponentialBoundaries = options => boundariesFromIterable(Arr.makeBy(options.count - 1, i => options.start * Math.pow(options.factor, i)));\n// Fiber Runtime Metrics\nconst fibersActive = /*#__PURE__*/gauge(\"child_fibers_active\", {\n description: \"The current count of active child fibers\"\n});\nconst fibersStarted = /*#__PURE__*/counter(\"child_fibers_started\", {\n description: \"The total number of child fibers that have been started\",\n incremental: true\n});\nconst fiberSuccesses = /*#__PURE__*/counter(\"child_fiber_successes\", {\n description: \"The total number of child fibers that have succeeded\",\n incremental: true\n});\nconst fiberFailures = /*#__PURE__*/counter(\"child_fiber_failures\", {\n description: \"The total number of child fibers that have failed\",\n incremental: true\n});\n/**\n * Service key for the fiber runtime metrics service.\n *\n * **Example** (Accessing the fiber runtime metrics key)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.FiberRuntimeMetricsKey // => \"effect/Metric/FiberRuntimeMetrics\"\n * ```\n *\n * @stability stable\n * @category constants\n * @since 4.0.0\n */\nexport const FiberRuntimeMetricsKey = InternalFiberRuntimeMetricsKey;\n/**\n * Context reference for the optional service that records fiber runtime\n * metrics.\n *\n * **When to use**\n *\n * Use to provide or inspect the service that receives fiber start and end\n * notifications for automatic runtime metrics.\n *\n * **Details**\n *\n * When provided, the runtime can notify the service about child-fiber start and\n * end events. When the reference is `undefined`, automatic fiber runtime metric\n * collection is disabled.\n *\n * **Example** (Accessing the fiber runtime metrics service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const metricsService = yield* Metric.FiberRuntimeMetrics\n * return metricsService === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * const result = await Effect.runPromise(\n * Effect.provideService(program, Metric.FiberRuntimeMetrics, Metric.FiberRuntimeMetricsImpl)\n * )\n * const isDefault = result // => true\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const FiberRuntimeMetrics = /*#__PURE__*/Context.Reference(InternalFiberRuntimeMetricsKey, {\n defaultValue: constUndefined\n});\n/**\n * Default implementation of the fiber runtime metrics service.\n *\n * **Example** (Accessing the default fiber metrics implementation)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * [\n * typeof Metric.FiberRuntimeMetricsImpl.recordFiberStart,\n * typeof Metric.FiberRuntimeMetricsImpl.recordFiberEnd\n * ] // => [\"function\", \"function\"]\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const FiberRuntimeMetricsImpl = {\n recordFiberStart(context) {\n fibersStarted.updateUnsafe(1, context);\n fibersActive.modifyUnsafe(1, context);\n },\n recordFiberEnd(context, exit) {\n fibersActive.modifyUnsafe(-1, context);\n if (InternalEffect.exitIsSuccess(exit)) {\n fiberSuccesses.updateUnsafe(1, context);\n } else {\n fiberFailures.updateUnsafe(1, context);\n }\n }\n};\n/**\n * Layer that enables automatic collection of fiber runtime metrics across\n * an entire Effect application.\n *\n * **When to use**\n *\n * Use when you need runtime metrics collection for all Effects in the\n * application context rather than wrapping individual Effects.\n *\n * **Example** (Enabling runtime metrics with a layer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * await Effect.runPromise(Effect.provide(program, Metric.enableRuntimeMetricsLayer)) // => true\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const enableRuntimeMetricsLayer = /*#__PURE__*/Layer.succeed(FiberRuntimeMetrics)(FiberRuntimeMetricsImpl);\n/**\n * Layer that disables automatic collection of fiber runtime metrics.\n *\n * **Example** (Disabling runtime metrics with a layer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Disable runtime metrics collection\n * const disabledLayer = Metric.disableRuntimeMetricsLayer\n *\n * return yield* Effect.gen(function*() {\n * // Check that metrics service is disabled\n * const metricsService = yield* Metric.FiberRuntimeMetrics\n *\n * // Run some Effects - no metrics will be collected\n * yield* Effect.forkChild(Effect.sleep(\"50 millis\"))\n * yield* Effect.forkChild(Effect.sleep(\"100 millis\"))\n * yield* Effect.sleep(\"200 millis\")\n *\n * // Create test metrics to show they still work\n * const testCounter = Metric.counter(\"test_counter\")\n * yield* Metric.update(testCounter, 1)\n * const counterValue = yield* Metric.value(testCounter)\n *\n * return { counterValue, metricsEnabled: metricsService !== undefined }\n * }).pipe(Effect.provide(disabledLayer))\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.counterValue.count, result.metricsEnabled] // => [1, false]\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const disableRuntimeMetricsLayer = /*#__PURE__*/Layer.succeed(FiberRuntimeMetrics)(undefined);\n/**\n * Enables automatic collection of fiber runtime metrics for the provided Effect.\n *\n * **Details**\n *\n * When enabled, automatically tracks fiber lifecycle metrics including active fibers,\n * started fibers, successful completions, and failures. These metrics provide valuable\n * insights into the concurrency patterns and health of your Effect application.\n *\n * **Example** (Enabling runtime metrics for an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * await Effect.runPromise(Metric.enableRuntimeMetrics(program)) // => true\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const enableRuntimeMetrics = /*#__PURE__*/InternalEffect.provideService(FiberRuntimeMetrics, FiberRuntimeMetricsImpl);\n/**\n * Disables automatic collection of fiber runtime metrics for the provided Effect.\n *\n * **When to use**\n *\n * Use when you need to disable runtime metrics for a specific effect while\n * keeping them enabled elsewhere.\n *\n * **Example** (Disabling runtime metrics for an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === undefined\n * })\n *\n * await Effect.runPromise(Metric.disableRuntimeMetrics(program)) // => true\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const disableRuntimeMetrics = /*#__PURE__*/InternalEffect.provideService(FiberRuntimeMetrics, undefined);\n// Utilities\nfunction makeKey(metric, attributes) {\n // Tuple encoding keeps ids, descriptions and attributes unambiguous.\n const entries = Object.entries(attributes).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);\n return JSON.stringify([metric.type, metric.id, metric.description, entries]);\n}\nfunction makeHooks(get, update, modify) {\n return {\n get,\n update,\n modify: modify ?? update\n };\n}\nfunction mergeAttributes(self, other) {\n return {\n ...attributesToRecord(self),\n ...attributesToRecord(other)\n };\n}\nfunction attributesToRecord(attributes) {\n if (Predicate.isNotUndefined(attributes) && Array.isArray(attributes)) {\n return attributes.reduce((acc, [key, value]) => {\n InternalRecord.assignProperty(acc, key, value);\n return acc;\n }, {});\n }\n return attributes;\n}\nfunction addAttributesToContext(attributes) {\n // Merge once per contextual attribute set, so the wrapped metric can reuse its cached series key.\n let current;\n let merged = {};\n return context => {\n const extraAttributes = Context.get(context, CurrentMetricAttributes);\n if (extraAttributes !== current) {\n current = extraAttributes;\n merged = mergeAttributes(extraAttributes, attributes);\n }\n return Context.add(context, CurrentMetricAttributes, merged);\n };\n}\n//# sourceMappingURL=Metric.js.map","import * as Cause from \"./Cause.js\";\nimport * as SecureRandom from \"./crypto/SecureRandom.js\";\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport * as random from \"./internal/random.js\";\nimport * as Predicate from \"./Predicate.js\";\n/**\n * Represents a service for generating pseudo-random numbers.\n *\n * **When to use**\n *\n * Use to access or provide the random-number generator service used by Effect\n * programs.\n *\n * **Gotchas**\n *\n * The default implementation is based on `Math.random` and is not\n * cryptographically secure. Replace the service with a cryptographically secure\n * implementation before using these generators for security-sensitive values.\n *\n * **Example** (Accessing the random service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const float = yield* Random.next\n * const integer = yield* Random.nextInt\n * const inRange = yield* Random.nextIntBetween(1, 100)\n * return [float, integer, inRange] as const\n * })\n *\n * await Effect.runPromise(program.pipe(Random.withSeed(\"example\"))) // => [0.1633802591287037, 3434461687501127, 1]\n * ```\n *\n * @stability stable\n * @category services\n * @since 2.0.0\n */\nexport const Random = random.Random;\nconst randomWith = f => Effect.withFiber(fiber => Effect.succeed(f(fiber.getRef(Random))));\n/**\n * Generates a random number between 0 (inclusive) and 1 (exclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random floating-point number in the standard\n * `[0, 1)` range.\n *\n * **Example** (Generating a random number)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.next.pipe(Random.withSeed(\"example\"))) // => 0.1633802591287037\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const next = /*#__PURE__*/randomWith(r => r.nextDoubleUnsafe());\n/**\n * Generates a random boolean value.\n *\n * **When to use**\n *\n * Use to make a pseudo-random true-or-false choice.\n *\n * **Example** (Generating a random boolean)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextBoolean.pipe(Random.withSeed(\"example\"))) // => false\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextBoolean = /*#__PURE__*/randomWith(r => r.nextDoubleUnsafe() > 0.5);\n/**\n * Generates a random integer between `Number.MIN_SAFE_INTEGER` (inclusive)\n * and `Number.MAX_SAFE_INTEGER` (inclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random safe integer across the full safe-integer\n * range.\n *\n * **Example** (Generating a random integer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextInt.pipe(Random.withSeed(\"example\"))) // => -6064002158214091\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextInt = /*#__PURE__*/randomWith(r => r.nextIntUnsafe());\n/**\n * Generates a random number between `min` (inclusive) and `max` (exclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random floating-point number within a numeric range.\n *\n * **Example** (Generating a bounded random number)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextBetween(0, 1).pipe(Random.withSeed(\"example\"))) // => 0.1633802591287037\n * ```\n *\n * @stability stable\n * @category generators\n * @since 4.0.0\n */\nexport const nextBetween = (min, max) => randomWith(r => random.nextBetween(min, max, r.nextDoubleUnsafe()));\n/**\n * Generates a random integer between `min` and `max`.\n *\n * **When to use**\n *\n * Use to generate a pseudo-random integer within a rounded numeric range.\n *\n * **Details**\n *\n * The lower bound is rounded up with `Math.ceil` and the upper bound is\n * rounded down with `Math.floor`. By default the range is inclusive; set\n * `options.halfOpen: true` to exclude the upper bound.\n *\n * **Example** (Generating a bounded random integer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const diceRoll1 = yield* Random.nextIntBetween(1, 6)\n * const diceRoll2 = yield* Random.nextIntBetween(1, 6, {\n * halfOpen: true\n * })\n * const diceRoll3 = yield* Random.nextIntBetween(0, 10)\n * return [diceRoll1, diceRoll2, diceRoll3]\n * })\n *\n * await Effect.runPromise(program.pipe(Random.withSeed(\"example\"))) // => [1, 4, 0]\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextIntBetween = (min, max, options) => {\n const extra = options?.halfOpen === true ? 0 : 1;\n return randomWith(r => {\n const minInt = Math.ceil(min);\n const maxInt = Math.floor(max);\n return Math.floor(r.nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt;\n });\n};\n/**\n * Uses the pseudo-random number generator to shuffle the specified iterable.\n *\n * **When to use**\n *\n * Use to randomly reorder an iterable using the active `Random` service.\n *\n * **Example** (Shuffling values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.shuffle([1, 2, 3, 4, 5]).pipe(Random.withSeed(\"example\"))) // => [4, 2, 5, 3, 1]\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const shuffle = elements => randomWith(r => {\n const buffer = Array.from(elements);\n for (let i = buffer.length - 1; i >= 1; i = i - 1) {\n const index = Math.min(i, Math.floor(r.nextDoubleUnsafe() * (i + 1)));\n const value = buffer[i];\n buffer[i] = buffer[index];\n buffer[index] = value;\n }\n return buffer;\n});\n/**\n * Gets a random element from an iterable.\n *\n * **When to use**\n *\n * Use to select one value uniformly from a collection using the active `Random`\n * service.\n *\n * **Details**\n *\n * If the input type is known to be non-empty, the returned effect cannot fail.\n * Otherwise, empty iterables fail with `Cause.NoSuchElementError`.\n *\n * **Example** (Choosing a random value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.choice([\"red\", \"green\", \"blue\"] as const).pipe(Random.withSeed(\"example\"))) // => \"red\"\n * ```\n *\n * @stability stable\n * @category generators\n * @since 3.6.0\n */\nexport const choice = elements => {\n const buffer = Array.from(elements);\n return buffer.length === 0 ? Effect.fail(new Cause.NoSuchElementError(\"Cannot select a random element from an empty array\")) : randomWith(r => buffer[Math.min(buffer.length - 1, Math.floor(r.nextDoubleUnsafe() * buffer.length))]);\n};\n/**\n * Seeds the pseudo-random number generator with the specified value.\n *\n * **When to use**\n *\n * Use to run an effect with a deterministic pseudo-random sequence.\n *\n * **Details**\n *\n * Using the same seed produces the same random sequence, which is useful for\n * tests and reproducible simulations.\n *\n * **Gotchas**\n *\n * Use an unpredictable seed when uniqueness or unpredictability matters.\n *\n * **Example** (Seeding random generation)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const value1 = yield* Random.next\n * const value2 = yield* Random.next\n * return [value1, value2]\n * })\n *\n * await Effect.runPromise(Effect.all([\n * program.pipe(Random.withSeed(\"my-seed\")),\n * program.pipe(Random.withSeed(\"my-seed\"))\n * ])) // => [[0.018368576514773527, 0.4010840628128671], [0.018368576514773527, 0.4010840628128671]]\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const withSeed = /*#__PURE__*/dual(2, (self, seed) => Effect.suspend(() => Effect.provideService(self, Random, ISAAC_CSPRNG(seed))));\n/*///////////////////////////////////////////////////////////////////////////////////////////////////\nThis is a derivative work copyright (c) 2025 Effectful Technologies Inc, under MIT license.\nThis is a derivative work copyright (c) 2018, William P. \"Mac\" McMeans, under BSD license.\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n3. Neither the name of isaacCSPRNG nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nOriginal work copyright (c) 2012 Yves-Marie K. Rinquin, under MIT license.\nhttps://github.com/rubycon/isaac.js\n///////////////////////////////////////////////////////////////////////////////////////////////////*/\nfunction ISAAC_CSPRNG(userSeed) {\n // Internal State\n const memory = new Array(256);\n const result = new Array(256);\n let accumulator = 0;\n let lastResult = 0;\n let generation = 0;\n let counter = 0;\n // Initial Seed\n const internalSeed = Predicate.isUndefined(userSeed) ? getInitialSeed() : userSeed;\n seed(internalSeed);\n function getInitialSeed() {\n const view = new DataView(SecureRandom.randomBytesUnsafe(8).buffer);\n return view.getUint32(0) + view.getUint32(4);\n }\n function reset() {\n accumulator = 0;\n lastResult = 0;\n counter = 0;\n for (let i = 0; i < 256; ++i) {\n memory[i] = 0;\n result[i] = 0;\n }\n generation = 0;\n }\n function seed(userSeed) {\n // The golden ratio ( 2654435769 )\n // See https://stackoverflow.com/questions/4948780/magic-number-in-boosthash-combine\n const magicNumber = 0x9e3779b9;\n let a = magicNumber;\n let b = magicNumber;\n let c = magicNumber;\n let d = magicNumber;\n let e = magicNumber;\n let f = magicNumber;\n let g = magicNumber;\n let h = magicNumber;\n let i = 0;\n let seed;\n if (Predicate.isString(userSeed)) {\n seed = toIntArray(userSeed);\n } else {\n seed = [userSeed];\n }\n reset();\n for (i = 0; i < seed.length; i++) {\n result[i & 0xff] += seed[i];\n }\n function mix() {\n a ^= b << 11;\n d = add32(d, a);\n b = add32(b, c);\n b ^= c >>> 2;\n e = add32(e, b);\n c = add32(c, d);\n c ^= d << 8;\n f = add32(f, c);\n d = add32(d, e);\n d ^= e >>> 16;\n g = add32(g, d);\n e = add32(e, f);\n e ^= f << 10;\n h = add32(h, e);\n f = add32(f, g);\n f ^= g >>> 4;\n a = add32(a, f);\n g = add32(g, h);\n g ^= h << 8;\n b = add32(b, g);\n h = add32(h, a);\n h ^= a >>> 9;\n c = add32(c, h);\n a = add32(a, b);\n }\n // Scramble the seed\n for (i = 0; i < 4; i++) {\n mix();\n }\n for (i = 0; i < 256; i += 8) {\n // Use all the information in the seed\n a = add32(a, result[i]);\n b = add32(b, result[i + 1]);\n c = add32(c, result[i + 2]);\n d = add32(d, result[i + 3]);\n e = add32(e, result[i + 4]);\n f = add32(f, result[i + 5]);\n g = add32(g, result[i + 6]);\n h = add32(h, result[i + 7]);\n mix();\n // Fill in the memory with messy stuff\n memory[i] = a;\n memory[i + 1] = b;\n memory[i + 2] = c;\n memory[i + 3] = d;\n memory[i + 4] = e;\n memory[i + 5] = f;\n memory[i + 6] = g;\n memory[i + 7] = h;\n }\n // Second pass to make sure seed affects memory\n for (i = 0; i < 256; i += 8) {\n a = add32(a, memory[i]);\n b = add32(b, memory[i + 1]);\n c = add32(c, memory[i + 2]);\n d = add32(d, memory[i + 3]);\n e = add32(e, memory[i + 4]);\n f = add32(f, memory[i + 5]);\n g = add32(g, memory[i + 6]);\n h = add32(h, memory[i + 7]);\n mix();\n // Fill in the memory with messy stuff (again)\n memory[i] = a;\n memory[i + 1] = b;\n memory[i + 2] = c;\n memory[i + 3] = d;\n memory[i + 4] = e;\n memory[i + 5] = f;\n memory[i + 6] = g;\n memory[i + 7] = h;\n }\n pnrg();\n generation = 256;\n }\n function pnrg(n) {\n let i = 0;\n let x = 0;\n let y = 0;\n n = Predicate.isUndefined(n) ? 1 : Math.abs(Math.floor(n));\n while (n--) {\n counter = add32(counter, 1);\n lastResult = add32(lastResult, counter);\n for (i = 0; i < 256; i++) {\n switch (i & 3) {\n case 0:\n {\n accumulator ^= accumulator << 13;\n break;\n }\n case 1:\n {\n accumulator ^= accumulator >>> 6;\n break;\n }\n case 2:\n {\n accumulator ^= accumulator << 2;\n break;\n }\n case 3:\n {\n accumulator ^= accumulator >>> 16;\n break;\n }\n }\n accumulator = add32(memory[i + 128 & 0xff], accumulator);\n x = memory[i];\n memory[i] = add32(memory[x >>> 2 & 0xff], add32(accumulator, lastResult));\n y = memory[i];\n result[i] = add32(memory[y >>> 10 & 0xff], x);\n lastResult = result[i];\n }\n }\n }\n /**\n * Returns a signed, random integer in the range [-2^31, 2^31).\n */\n function nextInt32() {\n if (!generation--) {\n pnrg();\n generation = 255;\n }\n return result[generation];\n }\n function nextIntUnsafe() {\n return Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;\n }\n /**\n * Returns a 53-bit fraction in the range [0, 1).\n */\n function nextDoubleUnsafe() {\n const hi = nextInt32() >>> 0 & 0x1FFFFF; // take top 21 bits\n const lo = nextInt32() >>> 0; // full 32 bits\n // 53-bit integer\n const combined = hi * 4294967296 + lo;\n return combined / 0x20000000000000; // [0, 1)\n }\n return {\n nextIntUnsafe,\n nextDoubleUnsafe\n };\n}\n/**\n * 32-bit addition with overflow handling (JavaScript numbers are 53-bit).\n *\n * Example: add32(0xFFFFFFFF, 0x00000001) = 0x00000000 (wraps around)\n */\nfunction add32(x, y) {\n // Add lower 16 bits separately to handle carry\n // Example: x=0x12345678, y=0xABCDEF01\n // lsb = (0x5678 + 0xEF01) = 0x14579\n const lsb = (x & 0xffff) + (y & 0xffff);\n // Add upper 16 bits + carry from lower addition\n // msb = (0x1234 + 0xABCD + (0x14579 >>> 16)) = (0x1234 + 0xABCD + 0x1) = 0xBE02\n const msb = (x >>> 16) + (y >>> 16) + (lsb >>> 16);\n // Combine: upper 16 bits | lower 16 bits (masked to prevent double carry)\n // return (0xBE02 << 16) | (0x14579 & 0xffff) = 0xBE024579\n return msb << 16 | lsb & 0xffff;\n}\nconst seedEncoder = /*#__PURE__*/new TextEncoder();\n/**\n * Convert a string to UTF-8 encoded 32-bit integers (little-endian).\n */\nfunction toIntArray(seed) {\n const bytes = seedEncoder.encode(seed);\n const result = [];\n for (let index = 0; index < bytes.length; index += 4) {\n result.push((bytes[index] ?? 0) << 0 | (bytes[index + 1] ?? 0) << 8 | (bytes[index + 2] ?? 0) << 16 | (bytes[index + 3] ?? 0) << 24);\n }\n return result;\n}\n//# sourceMappingURL=Random.js.map","/**\n * Caches values loaded by an Effect lookup function.\n *\n * A cache stores successful and failed lookup results, shares an in-progress\n * lookup when multiple callers request the same missing key, and limits entries\n * by capacity and optional time-to-live rules. This module includes helpers for\n * reading, setting, refreshing, invalidating, and inspecting cache contents.\n *\n * @stability stable\n * @since 4.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as MutableHashMap from \"./MutableHashMap.js\";\nimport * as Option from \"./Option.js\";\nimport * as Result from \"./Result.js\";\nconst TypeId = \"~effect/Cache\";\n/**\n * Creates a cache with dynamic time-to-live based on the result and key.\n *\n * **When to use**\n *\n * Use when you need different cache entry lifetimes based on the lookup result\n * or key characteristics.\n *\n * **Details**\n *\n * The timeToLive function receives both the exit result and the key, allowing\n * for flexible TTL policies based on success/failure state and key characteristics.\n *\n * **Example** (Configuring dynamic time to live)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Exit } from \"effect\"\n *\n * // Cache with TTL based on computed value\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.makeWith(\n * (id: number) => Effect.succeed({ id, active: id % 2 === 0 }),\n * {\n * capacity: 1000,\n * timeToLive(exit) {\n * if (Exit.isSuccess(exit)) {\n * const user = exit.value\n * return user.active ? \"1 hour\" : \"5 minutes\"\n * }\n * return \"30 seconds\"\n * }\n * }\n * )\n *\n * return cache.capacity\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 1000\n * ```\n *\n * @see {@link make} for a simpler cache constructor with a fixed time-to-live for all entries\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeWith = (lookup, options) => effect.contextWith(context => {\n const self = Object.create(Proto);\n self.lookup = key => effect.updateContext(lookup(key), input => Context.merge(context, input));\n self.map = MutableHashMap.make();\n self.capacity = options.capacity;\n self.timeToLive = options.timeToLive ? (exit, key) => Duration.fromInputUnsafe(options.timeToLive(exit, key)) : defaultTimeToLive;\n return effect.succeed(self);\n});\n/**\n * Creates a cache with a fixed time-to-live for all entries.\n *\n * **Details**\n *\n * This is the basic cache constructor where all entries share the same TTL.\n * The lookup function will be called when a key is not found or has expired.\n *\n * **Example** (Creating a basic cache)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Basic cache with string keys\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make<string, number>({\n * capacity: 100,\n * lookup: (key) => Effect.succeed(key.length)\n * })\n *\n * const result1 = yield* Cache.get(cache, \"hello\")\n * const result2 = yield* Cache.get(cache, \"world\")\n * return { result1, result2 }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { result1: 5, result2: 5 }\n * ```\n *\n * **Example** (Creating a cache with TTL)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const users = new Map([\n * [123, { name: \"Ada\", email: \"ada@example.com\" }],\n * [456, { name: \"Grace\", email: \"grace@example.com\" }]\n * ])\n *\n * const cache = yield* Cache.make<\n * number,\n * { name: string; email: string },\n * string\n * >({\n * capacity: 500,\n * lookup: (userId) =>\n * Effect.suspend(() => {\n * const user = users.get(userId)\n * return user === undefined\n * ? Effect.fail(`User ${userId} not found`)\n * : Effect.succeed(user)\n * }),\n * timeToLive: \"15 minutes\"\n * })\n *\n * const user1 = yield* Cache.get(cache, 123)\n * const user2 = yield* Cache.get(cache, 123)\n * return [user1, user2, user1 === user2] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [{ name: \"Ada\", email: \"ada@example.com\" }, { name: \"Ada\", email: \"ada@example.com\" }, true]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = options => makeWith(options.lookup, {\n ...options,\n timeToLive: options.timeToLive !== undefined ? () => options.timeToLive : defaultTimeToLive\n});\nconst Proto = {\n ...PipeInspectableProto,\n [TypeId]: TypeId,\n toJSON() {\n return {\n _id: \"Cache\",\n capacity: this.capacity,\n map: this.map\n };\n }\n};\nconst defaultTimeToLive = (_, _key) => Duration.infinity;\n/**\n * Retrieves the value for a key, invoking the lookup function on a cache miss\n * or expired entry.\n *\n * **Details**\n *\n * Concurrent `get` calls for the same missing key share the same pending\n * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and\n * will fail again until the entry expires, is invalidated, or is refreshed.\n *\n * **Example** (Getting cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Cache miss - triggers lookup function\n * const result1 = yield* Cache.get(cache, \"hello\")\n *\n * // Cache hit - returns cached value without lookup\n * const result2 = yield* Cache.get(cache, \"hello\")\n *\n * return { result1, result2 }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { result1: 5, result2: 5 }\n * ```\n *\n * **Example** (Handling lookup failures)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Exit } from \"effect\"\n *\n * // Error handling when lookup fails\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make<string, number, string>({\n * capacity: 10,\n * lookup: (key: string) =>\n * key === \"error\"\n * ? Effect.fail(\"Lookup failed\")\n * : Effect.succeed(key.length)\n * })\n *\n * // Successful lookup\n * const success = yield* Cache.get(cache, \"hello\")\n *\n * // Failed lookup - returns error\n * const failure = yield* Effect.exit(Cache.get(cache, \"error\"))\n * return [success, failure] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [5, Exit.fail(\"Lookup failed\")]\n * ```\n *\n * **Example** (Sharing concurrent lookups)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Concurrent access - multiple gets of same key only invoke lookup once\n * const program = Effect.gen(function*() {\n * let lookupCount = 0\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) =>\n * Effect.sync(() => {\n * lookupCount++\n * return key.length\n * })\n * })\n *\n * // Multiple concurrent gets\n * const results = yield* Effect.all([\n * Cache.get(cache, \"hello\"),\n * Cache.get(cache, \"hello\"),\n * Cache.get(cache, \"hello\")\n * ], { concurrency: \"unbounded\" })\n *\n * return { results, lookupCount }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { results: [5, 5, 5], lookupCount: 1 }\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const oentry = MutableHashMap.get(self.map, key);\n if (Option.isSome(oentry)) {\n MutableHashMap.remove(self.map, key);\n if (!hasExpired(oentry.value, fiber)) {\n // Move the entry to the end of the map to keep it fresh\n MutableHashMap.set(self.map, key, oentry.value);\n return oentry.value.await(fiber);\n }\n }\n const clock = fiber.getRef(effect.ClockRef);\n const entry = new EntryImpl(fiber, self.lookup(key));\n entry.onInterrupt = () => removeEntry(self, key, entry);\n let skipCache = false;\n entry.fiber.addObserver(exit => {\n // Release the key once the lookup can no longer be interrupted.\n entry.onInterrupt = undefined;\n if (effect.exitHasInterrupts(exit)) {\n removeEntry(self, key, entry);\n return;\n }\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n skipCache = true;\n removeEntry(self, key, entry);\n } else if (Duration.isFinite(ttl)) {\n entry.expiresAt = clock.currentTimeMillisUnsafe() + Duration.toMillis(ttl);\n }\n });\n const exit = entry.fiber.pollUnsafe();\n if (!skipCache && (exit === undefined || !effect.exitHasInterrupts(exit))) {\n MutableHashMap.set(self.map, key, entry);\n }\n if (Number.isFinite(self.capacity)) {\n checkCapacity(self);\n }\n return entry.await(fiber);\n}));\nclass EntryImpl {\n expiresAt;\n awaiters;\n fiber;\n onInterrupt;\n constructor(parent, valueEffect) {\n this.fiber = effect.forkUnsafe(parent, valueEffect, true, true);\n this.awaiters = 0;\n this.expiresAt = undefined;\n }\n await(fiber) {\n if (fiber === undefined) return core.withFiber(fiber => this.await(fiber));\n const exit = this.fiber.pollUnsafe();\n if (exit) return exit;\n this.awaiters++;\n // Register cleanup in the same evaluation as the increment, before interruption\n // can prevent the returned join effect from starting.\n effect.onExitUnsafe(fiber, () => {\n this.awaiters--;\n if (this.awaiters > 0 || this.fiber.pollUnsafe()) return effect.void;\n // Detach before interrupting so new lookups do not join the abandoned fiber\n // while its finalizers run.\n this.onInterrupt?.();\n return effect.fiberInterrupt(this.fiber);\n });\n return effect.fiberJoin(this.fiber);\n }\n}\nconst removeEntry = (self, key, entry) => {\n const current = MutableHashMap.get(self.map, key);\n if (Option.isSome(current) && current.value === entry) {\n MutableHashMap.remove(self.map, key);\n }\n};\nconst hasExpired = (entry, fiber) => {\n if (entry.expiresAt === undefined) {\n return false;\n }\n return fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt;\n};\nconst checkCapacity = self => {\n let diff = MutableHashMap.size(self.map) - self.capacity;\n if (diff <= 0) return;\n // MutableHashMap has insertion order, so we can remove the oldest entries\n for (const [key] of self.map) {\n MutableHashMap.remove(self.map, key);\n diff--;\n if (diff === 0) return;\n }\n};\n/**\n * Reads an existing cache entry without invoking the lookup function.\n *\n * **Details**\n *\n * Returns `Option.none()` when the key is missing or expired, and `Option.some`\n * when a cached lookup has succeeded. If the entry is still pending, waits for\n * it to complete. If the cached or pending lookup fails, this effect fails with\n * the same error.\n *\n * **Example** (Reading cached values without lookup)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Option } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // No value in cache yet - returns None without lookup\n * const empty = yield* Cache.getOption(cache, \"hello\")\n *\n * // Populate cache using get\n * yield* Cache.get(cache, \"hello\")\n *\n * // Now getOption returns the cached value\n * const cached = yield* Cache.getOption(cache, \"hello\")\n * return [empty, cached] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Option.none(), Option.some(5)]\n * ```\n *\n * **Example** (Skipping expired entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Option } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // Expired entries return None\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Add value to cache\n * yield* Cache.get(cache, \"hello\")\n *\n * // Value exists before expiration\n * const beforeExpiry = yield* Cache.getOption(cache, \"hello\")\n *\n * // Simulate time passing\n * yield* TestClock.adjust(\"2 hours\")\n *\n * // Value expired - returns None\n * const afterExpiry = yield* Cache.getOption(cache, \"hello\")\n * return [beforeExpiry, afterExpiry] as const\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [Option.some(5), Option.none()]\n * ```\n *\n * **Example** (Waiting for pending lookups)\n *\n * ```ts import.meta.vitest\n * import { Cache, Deferred, Effect, Fiber, Option } from \"effect\"\n *\n * // Waits for ongoing computation to complete\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<void>()\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (_key: string) => Deferred.await(deferred).pipe(Effect.as(42))\n * })\n *\n * // Start lookup in background\n * const getFiber = yield* Effect.forkChild(Cache.get(cache, \"key\"))\n *\n * // getOption waits for ongoing computation\n * const optionFiber = yield* Effect.forkChild(Cache.getOption(cache, \"key\"))\n *\n * // Complete the computation\n * yield* Deferred.succeed(deferred, void 0)\n *\n * const result = yield* Fiber.join(optionFiber)\n * const value = yield* Fiber.join(getFiber)\n * return [result, value] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Option.some(42), 42]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const getOption = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const entry = getImpl(self, key, fiber);\n return entry ? effect.asSome(entry.await(fiber)) : effect.succeedNone;\n}));\nconst getImpl = (self, key, fiber, isRead = true) => {\n const oentry = MutableHashMap.get(self.map, key);\n if (Option.isNone(oentry)) {\n return undefined;\n } else if (hasExpired(oentry.value, fiber)) {\n MutableHashMap.remove(self.map, key);\n return undefined;\n } else if (isRead) {\n MutableHashMap.remove(self.map, key);\n MutableHashMap.set(self.map, key, oentry.value);\n }\n return oentry.value;\n};\n/**\n * Retrieves the value associated with the specified key from the cache, only if\n * it contains a resolved successful value.\n *\n * **Details**\n *\n * This checks only an existing non-expired entry. It returns `Option.some` when\n * the entry has already resolved successfully, and `Option.none` for missing,\n * expired, failed, or still-pending entries.\n *\n * @see {@link get} for triggering or awaiting the cache lookup\n * @see {@link getOption} for reading an existing entry as an optional effect\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const getSuccess = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const exit = getImpl(self, key, fiber)?.fiber.pollUnsafe();\n if (exit && effect.exitIsSuccess(exit)) {\n return effect.succeedSome(exit.value);\n }\n return effect.succeedNone;\n}));\n/**\n * Sets the value associated with the specified key in the cache. This will\n * overwrite any existing value for that key, skipping the lookup function.\n *\n * **Example** (Setting values directly)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Set a value directly without invoking lookup\n * yield* Cache.set(cache, \"hello\", 42)\n * return yield* Cache.get(cache, \"hello\")\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 42\n * ```\n *\n * **Example** (Overwriting cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Overwriting existing cached values\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // First get populates via lookup\n * const original = yield* Cache.get(cache, \"test\") // 4\n *\n * // Set overwrites the cached value\n * yield* Cache.set(cache, \"test\", 999)\n * const updated = yield* Cache.get(cache, \"test\") // 999\n *\n * return { original, updated }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { original: 4, updated: 999 }\n * ```\n *\n * **Example** (Applying TTL to set values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // TTL behavior with set operations\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Set value with TTL applied\n * yield* Cache.set(cache, \"temporary\", 123)\n * const beforeExpiry = yield* Cache.has(cache, \"temporary\")\n *\n * // Advance time past TTL\n * yield* TestClock.adjust(\"2 hours\")\n * const afterExpiry = yield* Cache.has(cache, \"temporary\")\n * return [beforeExpiry, afterExpiry]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, false]\n * ```\n *\n * **Example** (Enforcing capacity when setting values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Capacity enforcement with set operations\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 2,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Fill cache to capacity\n * yield* Cache.set(cache, \"a\", 1)\n * yield* Cache.set(cache, \"b\", 2)\n * const sizeBeforeEviction = yield* Cache.size(cache)\n *\n * // Adding another entry evicts oldest\n * yield* Cache.set(cache, \"c\", 3)\n * const sizeAfterEviction = yield* Cache.size(cache)\n * const hasOldest = yield* Cache.has(cache, \"a\")\n * const hasNewest = yield* Cache.has(cache, \"c\")\n * return [sizeBeforeEviction, sizeAfterEviction, hasOldest, hasNewest]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [2, 2, false, true]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => core.withFiber(fiber => {\n const exit = core.exitSucceed(value);\n const entry = new EntryImpl(fiber, exit);\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n MutableHashMap.remove(self.map, key);\n return effect.void;\n }\n entry.expiresAt = Duration.isFinite(ttl) ? fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() + Duration.toMillis(ttl) : undefined;\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n return effect.void;\n}));\n/**\n * Checks whether the cache contains an entry for the specified key.\n *\n * **Details**\n *\n * This checks for an existing non-expired entry without invoking the cache\n * lookup function. Expired entries are treated as absent.\n *\n * **Example** (Checking for cached keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Check non-existent key\n * const missing = yield* Cache.has(cache, \"missing\")\n *\n * // Add entry and check existence\n * yield* Cache.get(cache, \"hello\")\n * const present = yield* Cache.has(cache, \"hello\")\n * return [missing, present]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [false, true]\n * ```\n *\n * **Example** (Checking TTL expiration)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // TTL expiration behavior\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Add entry with TTL\n * yield* Cache.get(cache, \"expires\")\n * const initial = yield* Cache.has(cache, \"expires\")\n *\n * // Still valid before expiration\n * yield* TestClock.adjust(\"30 minutes\")\n * const beforeExpiry = yield* Cache.has(cache, \"expires\")\n *\n * // Expired after TTL\n * yield* TestClock.adjust(\"31 minutes\")\n * const afterExpiry = yield* Cache.has(cache, \"expires\")\n * return [initial, beforeExpiry, afterExpiry]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, true, false]\n * ```\n *\n * **Example** (Checking multiple keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Checking multiple keys efficiently\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Populate some entries\n * yield* Cache.set(cache, \"apple\", 5)\n * yield* Cache.set(cache, \"banana\", 6)\n *\n * // Check multiple keys\n * const keys = [\"apple\", \"banana\", \"cherry\", \"date\"]\n * const results: Array<string> = []\n * for (const key of keys) {\n * const exists = yield* Cache.has(cache, key)\n * results.push(`${key}: ${exists}`)\n * }\n * return results\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"apple: true\", \"banana: true\", \"cherry: false\", \"date: false\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const oentry = getImpl(self, key, fiber, false);\n return effect.succeed(oentry !== undefined);\n}));\n/**\n * Invalidates the entry associated with the specified key in the cache.\n *\n * **Example** (Invalidating cached entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add a value to the cache\n * yield* Cache.get(cache, \"hello\")\n * const beforeInvalidation = yield* Cache.has(cache, \"hello\")\n *\n * // Invalidate the entry\n * yield* Cache.invalidate(cache, \"hello\")\n * const afterInvalidation = yield* Cache.has(cache, \"hello\")\n *\n * // Invalidating non-existent keys doesn't error\n * yield* Cache.invalidate(cache, \"nonexistent\")\n *\n * // Get after invalidation will invoke lookup again\n * let lookupCount = 0\n * const cache2 = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) =>\n * Effect.sync(() => {\n * lookupCount++\n * return key.length\n * })\n * })\n *\n * yield* Cache.get(cache2, \"test\") // lookupCount = 1\n * yield* Cache.invalidate(cache2, \"test\")\n * yield* Cache.get(cache2, \"test\") // lookupCount = 2 (lookup called again)\n * return { beforeInvalidation, afterInvalidation, lookupCount }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { beforeInvalidation: true, afterInvalidation: false, lookupCount: 2 }\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidate = /*#__PURE__*/dual(2, (self, key) => effect.sync(() => {\n MutableHashMap.remove(self.map, key);\n}));\n/**\n * Invalidates the entry associated with the specified key in the cache when the\n * predicate returns true for the cached value.\n *\n * **Example** (Invalidating entries conditionally)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add values to the cache\n * yield* Cache.get(cache, \"hello\") // value = 5\n * yield* Cache.get(cache, \"hi\") // value = 2\n *\n * // Invalidate when value equals 5\n * const invalidated1 = yield* Cache.invalidateWhen(\n * cache,\n * \"hello\",\n * (value) => value === 5\n * )\n * const hasHello = yield* Cache.has(cache, \"hello\")\n *\n * // Don't invalidate when predicate doesn't match\n * const invalidated2 = yield* Cache.invalidateWhen(\n * cache,\n * \"hi\",\n * (value) => value === 5\n * )\n * const hasHi = yield* Cache.has(cache, \"hi\")\n *\n * // Returns false for non-existent keys\n * const invalidated3 = yield* Cache.invalidateWhen(\n * cache,\n * \"nonexistent\",\n * () => true\n * )\n *\n * // Returns false for failed cached values\n * const cacheWithErrors = yield* Cache.make<string, number, string>({\n * capacity: 10,\n * lookup: (key: string) =>\n * key === \"fail\" ? Effect.fail(\"error\") : Effect.succeed(key.length)\n * })\n *\n * yield* Effect.exit(Cache.get(cacheWithErrors, \"fail\"))\n * const invalidated4 = yield* Cache.invalidateWhen(\n * cacheWithErrors,\n * \"fail\",\n * () => true\n * )\n * return [invalidated1, hasHello, invalidated2, hasHi, invalidated3, invalidated4]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [true, false, false, true, false, false]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidateWhen = /*#__PURE__*/dual(3, (self, key, f) => core.withFiber(fiber => {\n const oentry = getImpl(self, key, fiber, false);\n if (oentry === undefined) {\n return effect.succeed(false);\n }\n return oentry.await(fiber).pipe(effect.map(value => {\n if (f(value)) {\n const current = MutableHashMap.get(self.map, key);\n if (Option.isNone(current) || current.value !== oentry) {\n return false;\n }\n MutableHashMap.remove(self.map, key);\n return true;\n }\n return false;\n }), effect.catchCause(() => effect.succeed(false)));\n}));\n/**\n * Forces a refresh of the value associated with the specified key in the cache.\n *\n * **Details**\n *\n * It will always invoke the lookup function to construct a new value,\n * overwriting any existing value for that key.\n *\n * **Example** (Refreshing cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Force refresh of existing cached values\n * const program = Effect.gen(function*() {\n * let counter = 0\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.sync(() => `${key}-${++counter}`)\n * })\n *\n * // Initial cache population\n * const value1 = yield* Cache.get(cache, \"user\")\n *\n * // Get from cache (no lookup)\n * const value2 = yield* Cache.get(cache, \"user\")\n *\n * // Force refresh - always calls lookup\n * const refreshed = yield* Cache.refresh(cache, \"user\")\n *\n * // Subsequent gets return refreshed value\n * const value3 = yield* Cache.get(cache, \"user\")\n * return [value1, value2, refreshed, value3, counter]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"user-1\", \"user-1\", \"user-2\", \"user-2\", 2]\n * ```\n *\n * **Example** (Resetting TTL on refresh)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // Refresh resets TTL (Time To Live)\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * yield* Cache.get(cache, \"test\")\n * yield* TestClock.adjust(\"45 minutes\")\n *\n * // Entry would normally expire in 15 minutes\n * const beforeRefresh = yield* Cache.has(cache, \"test\")\n *\n * // Refresh resets the TTL to full 1 hour\n * yield* Cache.refresh(cache, \"test\")\n * yield* TestClock.adjust(\"30 minutes\")\n *\n * // Still valid because TTL was reset\n * const afterRefresh = yield* Cache.has(cache, \"test\")\n * return [beforeRefresh, afterRefresh]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, true]\n * ```\n *\n * **Example** (Refreshing missing keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Refresh non-existent keys\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(`value-for-${key}`)\n * })\n *\n * // Refresh non-existent key creates new entry\n * const result = yield* Cache.refresh(cache, \"newKey\")\n *\n * // Verify it's now cached\n * const cached = yield* Cache.has(cache, \"newKey\")\n * return [result, cached]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"value-for-newKey\", true]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const refresh = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const clock = fiber.getRef(effect.ClockRef);\n const entry = new EntryImpl(fiber, self.lookup(key));\n entry.onInterrupt = () => removeEntry(self, key, entry);\n const existing = getImpl(self, key, fiber, false) !== undefined;\n if (!existing) {\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n }\n entry.fiber.addObserver(exit => {\n // Release the key once the lookup can no longer be interrupted.\n entry.onInterrupt = undefined;\n if (effect.exitHasInterrupts(exit)) {\n removeEntry(self, key, entry);\n return;\n }\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n if (existing) MutableHashMap.remove(self.map, key);else removeEntry(self, key, entry);\n return effect.void;\n }\n entry.expiresAt = Duration.isFinite(ttl) ? clock.currentTimeMillisUnsafe() + Duration.toMillis(ttl) : undefined;\n if (existing) {\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n }\n });\n return entry.await(fiber);\n}));\n/**\n * Invalidates all entries in the cache.\n *\n * **Example** (Invalidating all entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Clear all cached entries at once\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Populate cache with multiple entries\n * yield* Cache.get(cache, \"apple\")\n * yield* Cache.get(cache, \"banana\")\n * yield* Cache.get(cache, \"cherry\")\n *\n * const sizeBeforeInvalidation = yield* Cache.size(cache)\n * const hasAppleBeforeInvalidation = yield* Cache.has(cache, \"apple\")\n *\n * // Clear all entries\n * yield* Cache.invalidateAll(cache)\n *\n * // Verify cache is empty\n * const sizeAfterInvalidation = yield* Cache.size(cache)\n * const hasAppleAfterInvalidation = yield* Cache.has(cache, \"apple\")\n * const hasBananaAfterInvalidation = yield* Cache.has(cache, \"banana\")\n * const hasCherryAfterInvalidation = yield* Cache.has(cache, \"cherry\")\n * return [\n * sizeBeforeInvalidation,\n * hasAppleBeforeInvalidation,\n * sizeAfterInvalidation,\n * hasAppleAfterInvalidation,\n * hasBananaAfterInvalidation,\n * hasCherryAfterInvalidation\n * ]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [3, true, 0, false, false, false]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidateAll = self => effect.sync(() => {\n MutableHashMap.clear(self.map);\n});\n/**\n * Retrieves the approximate number of entries in the cache.\n *\n * **Details**\n *\n * Note that expired entries are counted until they are accessed and removed.\n * The size reflects the current number of entries stored, not the number\n * of valid entries.\n *\n * **Example** (Reading cache size)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Empty cache has size 0\n * const emptySize = yield* Cache.size(cache)\n *\n * // Add entries and check size\n * yield* Cache.get(cache, \"hello\")\n * yield* Cache.get(cache, \"world\")\n * const sizeAfterAdding = yield* Cache.size(cache)\n *\n * // Size decreases after invalidation\n * yield* Cache.invalidate(cache, \"hello\")\n * const sizeAfterInvalidation = yield* Cache.size(cache)\n * return [emptySize, sizeAfterAdding, sizeAfterInvalidation]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [0, 2, 1]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const size = self => effect.sync(() => MutableHashMap.size(self.map));\n/**\n * Retrieves all active keys from the cache, automatically filtering out expired entries.\n *\n * **Example** (Reading active keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Basic key enumeration\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add some entries to the cache\n * yield* Cache.get(cache, \"hello\")\n * yield* Cache.get(cache, \"world\")\n * yield* Cache.get(cache, \"cache\")\n *\n * // Retrieve all active keys\n * const keys = yield* Cache.keys(cache)\n * return Array.from(keys).sort()\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"cache\", \"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const keys = self => core.withFiber(fiber => {\n const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe();\n return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {\n if (entry.expiresAt === undefined || entry.expiresAt > now) {\n return Result.succeed(key);\n }\n MutableHashMap.remove(self.map, key);\n return Result.failVoid;\n }));\n});\n/**\n * Retrieves all successfully cached values from the cache, excluding failed\n * lookups and expired entries.\n *\n * **Example** (Reading all cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add some values to the cache\n * yield* Cache.get(cache, \"a\")\n * yield* Cache.get(cache, \"ab\")\n * yield* Cache.get(cache, \"abc\")\n *\n * // Retrieve all cached values\n * const values = yield* Cache.values(cache)\n * return Array.from(values).sort()\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const values = self => effect.map(entries(self), Iterable.map(([, value]) => value));\n/**\n * Retrieves all key-value pairs from the cache as an iterable. This function\n * only returns entries with successfully resolved values, filtering out any\n * failed lookups or expired entries.\n *\n * **Gotchas**\n *\n * Expired entries are removed from the cache while `entries` filters them out.\n *\n * @see {@link keys} for retrieving only cached keys\n * @see {@link values} for retrieving only cached values\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const entries = self => core.withFiber(fiber => {\n const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe();\n return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {\n if (entry.expiresAt === undefined || entry.expiresAt > now) {\n const exit = entry.fiber.pollUnsafe();\n return exit && exit._tag === \"Success\" ? Result.succeed([key, exit.value]) : Result.failVoid;\n }\n MutableHashMap.remove(self.map, key);\n return Result.failVoid;\n }));\n});\n//# sourceMappingURL=Cache.js.map","import { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\n/**\n * Context reference for the current console service in the Effect system, allowing access to the active console implementation from within the Effect context.\n *\n * **When to use**\n *\n * Use when you need an effect to run against a provided console implementation,\n * such as tests or alternate runtimes, rather than the default console.\n *\n * **Details**\n *\n * When no override is provided, the reference resolves to `globalThis.console`.\n *\n * **Example** (Accessing the current console)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n * Effect.sync(() => {\n * console.log(\"Hello from current console!\")\n * })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello from current console!\"]\n * ```\n *\n * @see {@link consoleWith} for using the current console service inside an effect\n *\n * @stability stable\n * @category services\n * @since 2.0.0\n */\nexport const Console = effect.ConsoleRef;\n/**\n * Creates an Effect that provides access to the current console service and lets you perform operations with it within an Effect context.\n *\n * **Example** (Accessing the current console service)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(...args),\n * error: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n * Effect.sync(() => {\n * console.log(\"Hello, world!\")\n * console.error(\"This is an error message\")\n * })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello, world!\", \"This is an error message\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const consoleWith = f => core.withFiber(fiber => f(fiber.getRef(Console)));\n/**\n * Writes the supplied assertion message to the console as an error when `condition` is false; when `condition` is true, no console output is produced.\n *\n * **Example** (Logging failed assertions)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const errors: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * assert: (condition: boolean, ...args: ReadonlyArray<unknown>) => {\n * if (!condition) errors.push(...args)\n * }\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.assert(2 + 2 === 4, \"Math is working correctly\")\n * yield* Console.assert(2 + 2 === 5, \"This will be logged as an error\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * errors // => [\"This will be logged as an error\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const assert = (condition, ...args) => consoleWith(console => effect.sync(() => {\n console.assert(condition, ...args);\n}));\n/**\n * Runs the current console service's clear operation.\n *\n * **When to use**\n *\n * Use to request that the active console implementation clear its visible\n * output.\n *\n * **Gotchas**\n *\n * The clearing behavior depends on the active console implementation and host\n * environment.\n *\n * **Example** (Clearing console output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (message: string) => operations.push(`log:${message}`),\n * clear: () => operations.push(\"clear\")\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.log(\"This will be cleared\")\n * yield* Console.clear\n * yield* Console.log(\"This appears after clearing\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"log:This will be cleared\", \"clear\", \"log:This appears after clearing\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const clear = /*#__PURE__*/consoleWith(console => effect.sync(() => {\n console.clear();\n}));\n/**\n * Logs and increments the counter associated with `label`, using the console's default counter when no label is provided.\n *\n * **Example** (Counting repeated calls)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * count: (label = \"default\") => {\n * const count = (counters.get(label) ?? 0) + 1\n * counters.set(label, count)\n * messages.push(`${label}: ${count}`)\n * }\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.count(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * yield* Console.count()\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"default: 1\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const count = label => consoleWith(console => effect.sync(() => {\n console.count(label);\n}));\n/**\n * Resets the counter associated with the specified label back to zero.\n *\n * **Example** (Resetting a counter)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * count: (label = \"default\") => {\n * const count = (counters.get(label) ?? 0) + 1\n * counters.set(label, count)\n * messages.push(`${label}: ${count}`)\n * },\n * countReset: (label = \"default\") => counters.set(label, 0)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.count(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * yield* Console.countReset(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"my-counter: 1\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const countReset = label => consoleWith(console => effect.sync(() => {\n console.countReset(label);\n}));\n/**\n * Writes a debug message through the current `Console` service.\n *\n * **Details**\n *\n * The arguments are passed to the service's `debug` method when the returned\n * Effect is executed. Any filtering behavior depends on the active console\n * implementation.\n *\n * **Example** (Writing debug messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * debug: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.debug(\"Debug info:\", { userId: 123, action: \"login\" })\n * yield* Console.debug(\"Processing step\", 1, \"of\", 5)\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [[\"Debug info:\", { userId: 123, action: \"login\" }], [\"Processing step\", 1, \"of\", 5]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const debug = (...args) => consoleWith(console => effect.sync(() => {\n console.debug(...args);\n}));\n/**\n * Displays an interactive list of the properties of the specified object, optionally using console-specific inspection options for debugging complex data structures.\n *\n * **Example** (Inspecting an object)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const inspected: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * dir: (item: unknown, options?: unknown) => inspected.push([item, options])\n * })\n * const program = Effect.gen(function*() {\n * const obj = { name: \"John\", age: 30, nested: { city: \"New York\" } }\n * yield* Console.dir(obj)\n * yield* Console.dir(obj, { depth: 2 })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, undefined],\n * [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, { depth: 2 }]\n * ]\n * inspected // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const dir = (item, options) => consoleWith(console => effect.sync(() => {\n console.dir(item, options);\n}));\n/**\n * Displays an interactive tree of descendant XML or HTML elements, which is particularly useful for inspecting DOM elements in browser environments.\n *\n * **Example** (Inspecting XML-like data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * dirxml: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.dirxml(\"<user id=\\\"1\\\">Ada</user>\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"<user id=\\\"1\\\">Ada</user>\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const dirxml = (...args) => consoleWith(console => effect.sync(() => {\n console.dirxml(...args);\n}));\n/**\n * Writes an error-level message to the console, typically displayed with error\n * styling by the active console implementation.\n *\n * **Example** (Writing error messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * error: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.error(\"Something went wrong!\")\n * yield* Console.error(\"Error details:\", {\n * code: 500,\n * message: \"Internal Server Error\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Something went wrong!\"],\n * [\"Error details:\", { code: 500, message: \"Internal Server Error\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const error = (...args) => consoleWith(console => effect.sync(() => {\n console.error(...args);\n}));\n/**\n * Creates a scoped console group, optionally collapsed and labeled, and closes it automatically when the Effect scope is finalized.\n *\n * **Example** (Grouping scoped output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * group: (label?: string) => operations.push(`group:${label}`),\n * groupEnd: () => operations.push(\"groupEnd\"),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.group({ label: \"User Processing\" })\n * yield* Console.log(\"Loading user data...\")\n * yield* Console.log(\"Validating user...\")\n * yield* Console.log(\"User processed successfully\")\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * \"group:User Processing\",\n * \"log:Loading user data...\",\n * \"log:Validating user...\",\n * \"log:User processed successfully\",\n * \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const group = options => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n if (options?.collapsed) {\n console.groupCollapsed(options.label);\n } else {\n console.group(options?.label);\n }\n}), () => effect.sync(() => {\n console.groupEnd();\n})));\n/**\n * Writes an informational message to the console, typically displayed with info\n * styling by the active console implementation.\n *\n * **Example** (Writing informational messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * info: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.info(\"Application started successfully\")\n * yield* Console.info(\"Server configuration:\", {\n * port: 3000,\n * env: \"development\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Application started successfully\"],\n * [\"Server configuration:\", { port: 3000, env: \"development\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const info = (...args) => consoleWith(console => effect.sync(() => {\n console.info(...args);\n}));\n/**\n * Logs a general-purpose message to the console.\n *\n * **Example** (Writing log messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.log(\"Hello, world!\")\n * yield* Console.log(\"User data:\", { name: \"John\", age: 30 })\n * yield* Console.log(\"Processing\", 42, \"items\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Hello, world!\"],\n * [\"User data:\", { name: \"John\", age: 30 }],\n * [\"Processing\", 42, \"items\"]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const log = (...args) => consoleWith(console => effect.sync(() => {\n console.log(...args);\n}));\n/**\n * Displays tabular data as a formatted table in the console, optionally limited to selected properties.\n *\n * **Example** (Displaying tabular data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const calls: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * table: (data: ReadonlyArray<unknown>, properties?: ReadonlyArray<string>) => {\n * calls.push({ rows: data.length, properties })\n * }\n * })\n *\n * const program = Effect.gen(function*() {\n * const users = [\n * { name: \"John\", age: 30, city: \"New York\" },\n * { name: \"Jane\", age: 25, city: \"London\" },\n * { name: \"Bob\", age: 35, city: \"Paris\" }\n * ]\n * yield* Console.table(users)\n * yield* Console.table(users, [\"name\", \"age\"]) // Only show specific columns\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * calls // => [{ rows: 3, properties: undefined }, { rows: 3, properties: [\"name\", \"age\"] }]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const table = (tabularData, properties) => consoleWith(console => effect.sync(() => {\n console.table(tabularData, properties);\n}));\n/**\n * Starts a scoped timer for `label` and automatically ends it when the Effect scope is finalized.\n *\n * **Example** (Timing scoped work)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push(`start:${label}`),\n * timeEnd: (label?: string) => operations.push(`end:${label}`),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.time(\"operation-timer\")\n * yield* Console.log(\"Operation completed\")\n * // Timer ends automatically when scope closes\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:operation-timer\", \"log:Operation completed\", \"end:operation-timer\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const time = label => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n console.time(label);\n}), () => effect.sync(() => {\n console.timeEnd(label);\n})));\n/**\n * Logs the elapsed time for an existing timer without stopping it, allowing progress reports for long-running operations.\n *\n * **Example** (Logging timer progress)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push([\"start\", label]),\n * timeLog: (label?: string, ...args: ReadonlyArray<unknown>) => operations.push([\"log\", label, ...args]),\n * timeEnd: (label?: string) => operations.push([\"end\", label])\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.time(\"long-operation\")\n * yield* Console.timeLog(\"long-operation\", \"Halfway done\")\n * // Timer ends when scope closes\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [[\"start\", \"long-operation\"], [\"log\", \"long-operation\", \"Halfway done\"], [\"end\", \"long-operation\"]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const timeLog = (label, ...args) => consoleWith(console => effect.sync(() => {\n console.timeLog(label, ...args);\n}));\n/**\n * Writes the current stack trace to the console to show how the current point in\n * the code was reached.\n *\n * **Example** (Writing stack traces)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const traces: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * trace: (...args: ReadonlyArray<unknown>) => traces.push(args)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Console.trace(\"Debug trace point\")\n * yield* Console.trace(\"Function call:\", { functionName: \"processData\" })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * traces // => [[\"Debug trace point\"], [\"Function call:\", { functionName: \"processData\" }]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const trace = (...args) => consoleWith(console => effect.sync(() => {\n console.trace(...args);\n}));\n/**\n * Writes a warning-level message to the console, typically displayed with\n * warning styling by the active console implementation.\n *\n * **Example** (Writing warning messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * warn: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.warn(\"This feature is deprecated\")\n * yield* Console.warn(\"Performance warning:\", {\n * slowQuery: \"SELECT * FROM large_table\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"This feature is deprecated\"],\n * [\"Performance warning:\", { slowQuery: \"SELECT * FROM large_table\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const warn = (...args) => consoleWith(console => effect.sync(() => {\n console.warn(...args);\n}));\n/**\n * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes.\n *\n * **Example** (Wrapping an effect in a group)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * group: (label?: string) => operations.push(`group:${label}`),\n * groupEnd: () => operations.push(\"groupEnd\"),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.withGroup(\n * Effect.gen(function*() {\n * yield* Console.log(\"Step 1: Initialize\")\n * yield* Console.log(\"Step 2: Process\")\n * yield* Console.log(\"Step 3: Complete\")\n * }),\n * { label: \"Processing Steps\", collapsed: false }\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * \"group:Processing Steps\",\n * \"log:Step 1: Initialize\",\n * \"log:Step 2: Process\",\n * \"log:Step 3: Complete\",\n * \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const withGroup = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, options) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n if (options?.collapsed) {\n console.groupCollapsed(options.label);\n } else {\n console.group(options?.label);\n }\n}), () => self, () => effect.sync(() => {\n console.groupEnd();\n}))));\n/**\n * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes.\n *\n * **Example** (Timing an effect)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push(`start:${label}`),\n * timeEnd: (label?: string) => operations.push(`end:${label}`),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Console.withTime(\n * Effect.gen(function*() {\n * yield* Console.log(\"Operation completed\")\n * }),\n * \"my-operation\"\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:my-operation\", \"log:Operation completed\", \"end:my-operation\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const withTime = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, label) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n console.time(label);\n}), () => self, () => effect.sync(() => {\n console.timeEnd(label);\n}))));\n//# sourceMappingURL=Console.js.map","/**\n * Manages many fibers together inside one scope.\n *\n * A `FiberSet<A, E>` tracks running fibers, removes each fiber when it\n * completes, and interrupts all still-running fibers when the owning scope\n * closes. This module includes scoped runtime constructors plus helpers for\n * adding, clearing, running, counting, joining, and waiting for managed fibers.\n *\n * A fiber's success or failure does not interrupt the other fibers or close\n * the set. The set removes the completed fiber and keeps accepting new ones.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Cause from \"./Cause.js\";\nimport * as Deferred from \"./Deferred.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport * as Filter from \"./Filter.js\";\nimport { constVoid, dual } from \"./Function.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Predicate from \"./Predicate.js\";\nconst TypeId = \"~effect/FiberSet\";\n/**\n * Checks whether a value is a FiberSet.\n *\n * **Example** (Checking if a value is a FiberSet)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * return [FiberSet.isFiberSet(set), FiberSet.isFiberSet({})]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [true, false]\n * ```\n *\n * @stability stable\n * @category guards\n * @since 2.0.0\n */\nexport const isFiberSet = u => Predicate.hasProperty(u, TypeId);\nconst Proto = {\n [TypeId]: TypeId,\n [Symbol.iterator]() {\n if (this.state._tag === \"Closed\") {\n return Iterable.empty();\n }\n return this.state.backing[Symbol.iterator]();\n },\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"FiberSet\",\n state: this.state\n };\n }\n};\nconst makeUnsafe = (backing, deferred) => {\n const self = Object.create(Proto);\n self.state = {\n _tag: \"Open\",\n backing\n };\n self.deferred = deferred;\n return self;\n};\n/**\n * Creates a scoped `FiberSet` for storing fibers.\n *\n * **Details**\n *\n * When the associated Scope is closed, all fibers in the set will be\n * interrupted. You can add fibers to the set using `FiberSet.add` or\n * `FiberSet.run`, and the fibers will be automatically removed from the\n * FiberSet when they complete.\n *\n * **Example** (Creating a scoped FiberSet)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // run some effects and add the fibers to the set\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * yield* Effect.yieldNow\n * return yield* FiberSet.size(set)\n * }).pipe(\n * Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 2\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = () => Effect.acquireRelease(Effect.sync(() => makeUnsafe(new Set(), Deferred.makeUnsafe())), set => Effect.suspend(() => {\n const state = set.state;\n if (state._tag === \"Closed\") return Effect.void;\n set.state = {\n _tag: \"Closed\"\n };\n const fibers = state.backing;\n return Fiber.interruptAll(fibers).pipe(Deferred.into(set.deferred));\n}));\n/**\n * Creates a scoped run function that forks effects into a new `FiberSet`.\n *\n * **Details**\n *\n * Each call returns the forked fiber and adds it to the set. Managed fibers are\n * removed when they complete and are interrupted when the set's scope closes.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Creating a scoped runtime)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const runFork = yield* FiberSet.makeRuntime()\n *\n * // Fork effects using the runtime\n * const fiber1 = runFork(Effect.succeed(\"hello\"))\n * const fiber2 = runFork(Effect.succeed(\"world\"))\n *\n * return [yield* Fiber.join(fiber1), yield* Fiber.join(fiber2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeRuntime = () => Effect.flatMap(make(), self => runtime(self)());\n/**\n * Creates a scoped run function that forks effects into a new `FiberSet` and\n * returns a `Promise` for each effect result.\n *\n * **When to use**\n *\n * Use when many scoped fibers should be tracked as a set while exposing each\n * result through Promise-based APIs.\n *\n * **Details**\n *\n * Managed fibers are removed when they complete and are interrupted when the\n * set's scope closes. Each Promise resolves with the effect's success value or\n * rejects with the squashed failure cause.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Creating a promise runtime)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const runPromise = yield* FiberSet.makeRuntimePromise()\n *\n * // Run effects as promises\n * const promise1 = runPromise(Effect.succeed(\"hello\"))\n * const promise2 = runPromise(Effect.succeed(\"world\"))\n *\n * return [yield* Effect.promise(() => promise1), yield* Effect.promise(() => promise2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 3.13.0\n */\nexport const makeRuntimePromise = () => Effect.flatMap(make(), self => runtimePromise(self)());\nconst internalFiberId = -1;\nconst isInternalInterruption = /*#__PURE__*/Filter.toPredicate(/*#__PURE__*/Filter.compose(Cause.filterInterruptors, /*#__PURE__*/Filter.has(internalFiberId)));\n/**\n * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe\n * mutation.\n *\n * **When to use**\n *\n * Use when an already forked fiber must be registered immediately and\n * synchronous interruption on a closed set is acceptable.\n *\n * **Details**\n *\n * When the fiber completes, it is removed from the set. If the set is already\n * closed, the supplied fiber is interrupted immediately. Non-interruption\n * failures are recorded for `FiberSet.join`.\n *\n * **Example** (Adding a fiber unsafely)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const fiber = yield* Effect.forkChild(Effect.never)\n *\n * // Unsafe add - doesn't return an Effect\n * FiberSet.addUnsafe(set, fiber)\n *\n * // The fiber is now managed by the set\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 1\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const addUnsafe = /*#__PURE__*/dual(args => isFiberSet(args[0]), (self, fiber, options) => {\n if (self.state._tag === \"Closed\") {\n fiber.interruptUnsafe(internalFiberId);\n return;\n } else if (self.state.backing.has(fiber)) {\n return;\n }\n self.state.backing.add(fiber);\n fiber.addObserver(exit => {\n if (self.state._tag === \"Closed\") {\n return;\n }\n self.state.backing.delete(fiber);\n if (Exit.isFailure(exit) && (options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !Cause.hasInterruptsOnly(exit.cause))) {\n Deferred.doneUnsafe(self.deferred, exit);\n }\n });\n});\n/**\n * Adds a fiber to the FiberSet. When the fiber completes, it will be removed.\n *\n * **Details**\n *\n * Set `propagateInterruption: true` to report external interruptions to\n * {@link join}.\n *\n * **Example** (Adding a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const fiber = yield* Effect.forkChild(Effect.never)\n *\n * // Add the fiber to the set\n * yield* FiberSet.add(set, fiber)\n *\n * // The fiber is now managed by the set\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 1\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const add = /*#__PURE__*/dual(args => isFiberSet(args[0]), (self, fiber, options) => Effect.sync(() => addUnsafe(self, fiber, options)));\n/**\n * Interrupts all fibers in the `FiberSet` and clears the set.\n *\n * **Example** (Clearing all fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // Add some fibers\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * const sizeBefore = yield* FiberSet.size(set)\n *\n * // Clear all fibers\n * yield* FiberSet.clear(set)\n *\n * return [sizeBefore, yield* FiberSet.size(set)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [2, 0]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const clear = self => Effect.suspend(() => {\n if (self.state._tag === \"Closed\") {\n return Effect.void;\n }\n return Fiber.interruptAllAs(self.state.backing, internalFiberId);\n});\nconst constInterruptedFiber = /*#__PURE__*/function () {\n let fiber = undefined;\n return () => {\n if (fiber === undefined) {\n fiber = Effect.runFork(Effect.interrupt);\n }\n return fiber;\n };\n}();\n/**\n * Forks an Effect and adds the fiber to the FiberSet. The fiber is removed\n * when it completes.\n *\n * **Details**\n *\n * The new fiber starts interruptible, even when the caller is uninterruptible.\n * By default, it runs synchronously until it suspends, yields, or completes\n * before `run` returns. Set `startImmediately: false` to defer startup as in\n * `Effect.forkChild`.\n *\n * The set owns the fiber, not the caller: it can outlive the caller's\n * completion or interruption. Forking and registration are interruption-safe,\n * so caller interruption cannot leave the fiber untracked. Closing the owning\n * scope from another fiber interrupts managed fibers and awaits their finalizers.\n *\n * Set `propagateInterruption: true` to report external interruptions to\n * {@link join}.\n *\n * **Gotchas**\n *\n * Uninterruptible work can delay scope closure.\n *\n * **Example** (Forking effects into a set)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // Fork and add to set\n * const fiber1 = yield* FiberSet.run(set, Effect.succeed(\"hello\"))\n * const fiber2 = yield* FiberSet.run(set, Effect.succeed(\"world\"))\n *\n * // Get results\n * return [yield* Fiber.join(fiber1), yield* Fiber.join(fiber2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const run = function () {\n const self = arguments[0];\n if (!Effect.isEffect(arguments[1])) {\n const options = arguments[1];\n return effect => runImpl(self, effect, options);\n }\n return runImpl(self, arguments[1], arguments[2]);\n};\nconst runImpl = (self, effect, options) => Effect.withFiber(parent => {\n if (self.state._tag === \"Closed\") {\n return Effect.sync(constInterruptedFiber);\n }\n const fiber = internalEffect.forkUnsafe(parent, effect, options?.startImmediately ?? true, true);\n addUnsafe(self, fiber, options);\n return Effect.succeed(fiber);\n});\n/**\n * Captures a `Runtime` and uses it to fork effects into the `FiberSet`.\n *\n * **Details**\n *\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Capturing a runtime)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Fiber, FiberSet } from \"effect\"\n *\n * class Users extends Context.Service<Users, {\n * readonly getAll: Effect.Effect<Array<unknown>>\n * }>()(\"Users\") {}\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const run = yield* FiberSet.runtime(set)<Users>()\n *\n * // run some effects and add the fibers to the set\n * const fiber = run(Effect.andThen(Users, (_) => _.getAll))\n * return (yield* Fiber.join(fiber)).length\n * }).pipe(\n * Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n *\n * const actual = await Effect.runPromise(Effect.provideService(program, Users, {\n * getAll: Effect.succeed([])\n * }))\n * actual // => 0\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const runtime = self => () => Effect.map(Effect.context(), services => {\n const runFork = Effect.runForkWith(services);\n return (effect, options) => {\n if (self.state._tag === \"Closed\") {\n return constInterruptedFiber();\n }\n const fiber = runFork(effect, options);\n addUnsafe(self, fiber, options);\n return fiber;\n };\n});\n/**\n * Captures a `Runtime` and returns a Promise-based runner that forks effects\n * into the `FiberSet`.\n *\n * **When to use**\n *\n * Use when you need to bridge effects to `Promise` values while still tracking\n * their fibers in a `FiberSet`.\n *\n * **Details**\n *\n * The returned run function returns a `Promise` for each effect result.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Running effects as promises)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const runPromise = yield* FiberSet.runtimePromise(set)()\n *\n * // Run effects as promises\n * const promise1 = runPromise(Effect.succeed(\"hello\"))\n * const promise2 = runPromise(Effect.succeed(\"world\"))\n *\n * return [yield* Effect.promise(() => promise1), yield* Effect.promise(() => promise2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @see {@link runtime} for a runner that returns the forked `Fiber`\n *\n * @stability stable\n * @category combinators\n * @since 3.13.0\n */\nexport const runtimePromise = self => () => Effect.map(runtime(self)(), runFork => (effect, options) => new Promise((resolve, reject) => runFork(effect, options).addObserver(exit => {\n if (Exit.isSuccess(exit)) {\n resolve(exit.value);\n } else {\n reject(Cause.squash(exit.cause));\n }\n})));\n/**\n * Gets the number of fibers currently in the FiberSet.\n *\n * **Example** (Checking the set size)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * const sizeBefore = yield* FiberSet.size(set)\n *\n * // Add some fibers\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * return [sizeBefore, yield* FiberSet.size(set)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [0, 2]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const size = self => Effect.sync(() => self.state._tag === \"Closed\" ? 0 : self.state.backing.size);\n/**\n * Waits for the `FiberSet` to fail or close.\n *\n * **Details**\n *\n * Fails with the first recorded fiber failure. A successful fiber is removed\n * without completing `join`; use {@link awaitEmpty} to wait for an empty set.\n *\n * By default, failures caused only by interruption are ignored. If the fiber\n * was registered with `propagateInterruption: true`, its interruption is\n * recorded unless the set itself interrupted it, as on scope closure or\n * `clear`.\n *\n * **Example** (Joining failing fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * yield* FiberSet.add(set, Effect.runFork(Effect.fail(\"error\")))\n *\n * // parent fiber will fail with \"error\"\n * yield* FiberSet.join(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.exit(Effect.scoped(program)))\n * actual // => Exit.fail(\"error\")\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const join = self => Deferred.await(self.deferred);\n/**\n * Waits until the fiber set is empty.\n *\n * **Example** (Waiting for an empty set)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * yield* FiberSet.run(set, Effect.yieldNow)\n * yield* FiberSet.run(set, Effect.yieldNow)\n *\n * // Wait for all fibers to complete\n * yield* FiberSet.awaitEmpty(set)\n *\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 0\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 3.13.0\n */\nexport const awaitEmpty = self => Effect.whileLoop({\n while: () => self.state._tag === \"Open\" && self.state.backing.size > 0,\n body: () => Fiber.await(Iterable.headUnsafe(self)),\n step: constVoid\n});\n//# sourceMappingURL=FiberSet.js.map","/**\n * Defines loggers and log-event data for Effect programs.\n *\n * A `Logger<Message, Output>` receives each log event as `Options` and turns it\n * into output such as a formatted string, structured object, console write,\n * file write, JSON line, or trace span event. This module also includes active\n * logger references, console routing helpers, built-in formatters, batching,\n * file logging, and layers for installing loggers.\n *\n * When a log effect (`Effect.log`, `Effect.logWithLevel`, or a level-specific\n * variant) invokes a logger, it does so synchronously in the logging fiber\n * before the log effect completes. A logger that defers work says so in its own\n * documentation, as `batched` and `toFile` do.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Array from \"./Array.js\";\nimport * as FileSystem from \"./FileSystem.js\";\nimport * as Formatter from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport { isEffect, withFiber } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"./References.js\";\nconst TypeId = \"~effect/Logger\";\n/**\n * Returns `true` if the specified value is a `Logger`, otherwise returns `false`.\n *\n * **Example** (Checking logger values)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * const myLogger = Logger.make(() => undefined)\n *\n * Logger.isLogger(myLogger) // => true\n * Logger.isLogger(\"not a logger\") // => false\n * Logger.isLogger({ log: () => {} }) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isLogger = u => Predicate.hasProperty(u, TypeId);\n/**\n * Context reference containing the active loggers for the current fiber.\n *\n * **Details**\n *\n * By default this set includes the default logger and the tracer logger.\n * Providing `Logger.layer` replaces or merges with this set depending on its\n * options.\n *\n * **Example** (Accessing current loggers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n * messages.push(options.message)\n * })\n * const program = Effect.gen(function*() {\n * const currentLoggers = yield* Effect.service(Logger.CurrentLoggers)\n * yield* Effect.log(\"Hello from custom logger\").pipe(\n * Effect.provide(Logger.layer([customLogger]))\n * )\n * return currentLoggers.has(Logger.defaultLogger)\n * })\n *\n * Effect.runSync(program) // => true\n * messages // => [[\"Hello from custom logger\"]]\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const CurrentLoggers = effect.CurrentLoggers;\n/**\n * Context reference that routes the built-in default logger and TTY pretty\n * console logger to stderr.\n *\n * **When to use**\n *\n * Use to route built-in logger output to stderr while keeping stdout reserved\n * for protocol messages or data output.\n *\n * **Details**\n *\n * The reference defaults to `false`. Providing `true` makes the affected\n * loggers call `console.error` instead of `console.log`.\n *\n * @see {@link defaultLogger} for the runtime logger affected by this reference\n * @see {@link consolePretty} for the TTY-mode pretty console logger affected by this reference\n * @see {@link withConsoleError} for routing a specific formatter logger to `console.error`\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const LogToStderr = effect.LogToStderr;\n/**\n * Transforms the output of a `Logger` using the provided function.\n *\n * **When to use**\n *\n * Use when an existing logger's output should be transformed without recreating the\n * logging logic.\n *\n * **Details**\n *\n * The returned logger calls `self` and then `f` inside the same `log` call.\n *\n * **Example** (Transforming logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<unknown> = []\n * const structuredLogger = Logger.make((options) => ({\n * message: options.message\n * }))\n *\n * // Transform to uppercase messages\n * const uppercaseLogger = Logger.map(\n * structuredLogger,\n * (output) => ({ ...output, message: String(output.message).toUpperCase() })\n * )\n *\n * const collector = Logger.make((options) => outputs.push(uppercaseLogger.log(options)))\n * const program = Effect.log(\"hello\").pipe(Effect.provide(Logger.layer([collector])))\n * Effect.runSync(program)\n * outputs // => [{ message: \"HELLO\" }]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => effect.loggerMake(options => f(self.log(options))));\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.log`.\n *\n * **When to use**\n *\n * Use when a logger's string or object output should be routed to `console.log` for\n * development or debugging.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call.\n *\n * **Example** (Writing logger output with console.log)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create a custom formatter\n * const customFormatter = Logger.make((options) =>\n * `${options.logLevel}: ${options.message}`\n * )\n *\n * const consoleLogger = Logger.withConsoleLog(customFormatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Hello World\").pipe(Effect.provide(Logger.layer([consoleLogger])))\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"Info: Hello World\"]\n * ```\n *\n * @stability stable\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleLog = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n return console.log(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.error`.\n *\n * **When to use**\n *\n * Use when logger output should be routed to `console.error`, such as error logs that\n * should appear on stderr instead of stdout.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call.\n *\n * **Example** (Writing logger output with console.error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create an error-specific formatter\n * const errorFormatter = Logger.make((options) =>\n * `ERROR: ${options.message}`\n * )\n *\n * const errorLogger = Logger.withConsoleError(errorFormatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logError(\"Database connection failed\").pipe(Effect.provide(Logger.layer([errorLogger])))\n * return yield* TestConsole.errorLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"ERROR: Database connection failed\"]\n * ```\n *\n * @stability stable\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleError = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n return console.error(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call. Will use the appropriate console\n * method (i.e. `console.log`, `console.error`, etc.) based upon the current\n * `LogLevel`.\n *\n * `Debug` uses `console.debug`, `Info` uses `console.info`, `Trace` uses\n * `console.trace`, `Warn` uses `console.warn`, `Error` and `Fatal` use\n * `console.error`, and all other levels use `console.log`.\n *\n * **Example** (Writing logs with level-based console methods)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Logger } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * info: (message: unknown) => messages.push([\"info\", message]),\n * warn: (message: unknown) => messages.push([\"warn\", message]),\n * error: (message: unknown) => messages.push([\"error\", message])\n * })\n * const formatter = Logger.make((options) =>\n * `[${options.logLevel}] ${options.message}`\n * )\n *\n * const leveledLogger = Logger.withLeveledConsole(formatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logInfo(\"Info message\") // -> console.info\n * yield* Effect.logWarning(\"Warning\") // -> console.warn\n * yield* Effect.logError(\"Error occurred\") // -> console.error\n * }).pipe(Effect.provide(Logger.layer([leveledLogger])))\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"info\", \"[Info] Info message\"],\n * [\"warn\", \"[Warn] Warning\"],\n * [\"error\", \"[Error] Error occurred\"]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category logging\n * @since 3.8.0\n */\nexport const withLeveledConsole = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n const output = self.log(options);\n switch (options.logLevel) {\n case \"Debug\":\n return console.debug(output);\n case \"Info\":\n return console.info(output);\n case \"Trace\":\n return console.trace(output);\n case \"Warn\":\n return console.warn(output);\n case \"Error\":\n case \"Fatal\":\n return console.error(output);\n default:\n return console.log(output);\n }\n});\n/**\n * Match strings that do not contain any whitespace characters, double quotes,\n * or equal signs.\n */\nconst textOnly = /^[^\\s\"=]*$/;\n/**\n * Escapes double quotes in a string.\n */\nconst escapeDoubleQuotes = s => `\"${s.replace(/\\\\([\\s\\S])|(\")/g, \"\\\\$1$2\")}\"`;\n/**\n * Formats the identifier of a `Fiber` by prefixing it with a hash tag.\n */\nconst formatFiberId = fiberId => `#${fiberId}`;\n/**\n * Used by both {@link formatSimple} and {@link formatLogFmt} to render a log\n * message.\n *\n * @internal\n */\nconst format = (quoteValue, space) => ({\n cause,\n date,\n fiber,\n logLevel,\n message\n}) => {\n const formatUnknown = value => typeof value === \"string\" ? value : Formatter.format(value, {\n space\n });\n const formatValue = value => value.match(textOnly) ? value : quoteValue(value);\n const format = (label, value) => `${effect.formatLabel(label)}=${formatValue(value)}`;\n const append = (label, value) => \" \" + format(label, value);\n let out = format(\"timestamp\", date.toISOString());\n out += append(\"level\", logLevel.toUpperCase());\n out += append(\"fiber\", formatFiberId(fiber.id));\n const messages = Array.ensure(message);\n for (let i = 0; i < messages.length; i++) {\n out += append(\"message\", formatUnknown(messages[i]));\n }\n if (cause.reasons.length > 0) {\n out += append(\"cause\", effect.causePretty(cause));\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const span of spans) {\n out += \" \" + effect.formatLogSpan(span, now);\n }\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [label, value] of Object.entries(annotations)) {\n out += append(label, formatUnknown(value));\n }\n return out;\n};\n/**\n * Creates a new `Logger` from a log function.\n *\n * **Details**\n *\n * The log function receives an options object containing the message, log level,\n * cause, fiber information, and timestamp, and should return the desired output.\n * `log` is called synchronously in the fiber that logs, before the log effect\n * completes.\n *\n * **Gotchas**\n *\n * If `log` throws, the log effect dies with the thrown value as a defect.\n *\n * **Example** (Creating loggers from functions)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<string> = []\n * const textLogger = Logger.make((options) =>\n * `${options.logLevel}: ${options.message}`\n * )\n * const collector = Logger.make((options) => outputs.push(textLogger.log(options)))\n *\n * const program = Effect.log(\"Hello World\").pipe(\n * Effect.provide(Logger.layer([collector]))\n * )\n * Effect.runSync(program)\n * outputs // => [\"Info: Hello World\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = effect.loggerMake;\n/**\n * The default logging implementation used by the Effect runtime.\n *\n * **Example** (Referencing the default logger)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.defaultLogger) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const defaultLogger = effect.defaultLogger;\n/**\n * A `Logger` which outputs logs as a string.\n *\n * **Details**\n *\n * For example, a simple log entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as simple strings)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Use the simple format logger\n * const stableSimple = Logger.map(Logger.formatSimple, (output) =>\n * output\n * .replace(/timestamp=\\S+ /, \"\")\n * .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Application started\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableSimple)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=INFO message=\\\"Application started\\\"\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatSimple = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(escapeDoubleQuotes));\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style.\n *\n * **Details**\n *\n * For example, a logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as logfmt)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableLogFmt = Logger.map(Logger.formatLogFmt, (output) =>\n * output\n * .replace(/timestamp=\\S+ /, \"\")\n * .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"User login\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableLogFmt)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=INFO message=\\\"User login\\\"\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatLogFmt = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(JSON.stringify, 0));\n/**\n * A `Logger` which outputs logs using a structured format.\n *\n * **Details**\n *\n * For example, a structured entry can contain `message: [ \"hello\" ]`,\n * `level: \"INFO\"`, `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Formatting logs as structured objects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableStructured = Logger.map(Logger.formatStructured, (output) => ({\n * message: output.message,\n * level: output.level\n * }))\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"User action\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableStructured)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [{ message: \"User action\", level: \"INFO\" }]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatStructured = /*#__PURE__*/effect.loggerMake(({\n cause,\n date,\n fiber,\n logLevel,\n message\n}) => {\n const annotationsObj = {};\n const spansObj = {};\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [key, value] of Object.entries(annotations)) {\n InternalRecord.assignProperty(annotationsObj, key, effect.structuredMessage(value));\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const [label, timestamp] of spans) {\n InternalRecord.assignProperty(spansObj, label, now - timestamp);\n }\n const messageArr = Array.ensure(message);\n return {\n message: messageArr.length === 1 ? effect.structuredMessage(messageArr[0]) : messageArr.map(effect.structuredMessage),\n level: logLevel.toUpperCase(),\n timestamp: date.toISOString(),\n cause: cause.reasons.length > 0 ? effect.causePretty(cause) : undefined,\n annotations: annotationsObj,\n spans: spansObj,\n fiberId: formatFiberId(fiber.id)\n };\n});\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line.\n *\n * **Details**\n *\n * For example, a JSON entry can render as `{\"message\":[\"hello\"],\"level\":\"INFO\",\n * \"timestamp\":\"2025-01-03T14:28:57.508Z\",\"annotations\":{\"key\":\"value\"},\n * \"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Formatting logs as JSON)\n *\n * ```ts import.meta.vitest\n * import { Effect, Formatter, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableJson = Logger.map(Logger.formatJson, (json) => {\n * const output = JSON.parse(json)\n * return Formatter.formatJson({ message: output.message, level: output.level })\n * })\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Server started\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableJson)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"{\\\"message\\\":\\\"Server started\\\",\\\"level\\\":\\\"INFO\\\"}\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatJson = /*#__PURE__*/map(formatStructured, Formatter.formatJson);\n/**\n * Creates a scoped logger that batches the output of another logger.\n *\n * **Details**\n *\n * The returned logger formats each event with `self` and buffers the output\n * during the log call. A background fiber passes pending entries to `flush`\n * once per window, skipping empty windows. When the scope closes, the\n * background fiber is interrupted and the scope finalizer flushes any remaining\n * entries.\n *\n * **Example** (Batching logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const flushed: Array<ReadonlyArray<string>> = []\n * const messageLogger = Logger.make((options) => String(options.message))\n * const batchedLogger = Logger.batched(messageLogger, {\n * window: \"1 hour\",\n * flush: (messages) =>\n * Effect.sync(() => {\n * flushed.push(messages)\n * })\n * })\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const logger = yield* batchedLogger\n * yield* Effect.log(\"Event 1\").pipe(Effect.provide(Logger.layer([logger])))\n * yield* Effect.log(\"Event 2\").pipe(Effect.provide(Logger.layer([logger])))\n * }))\n * await Effect.runPromise(program)\n * flushed // => [[\"Event 1\", \"Event 2\"]]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const batched = /*#__PURE__*/dual(2, (self, options) => effect.suspend(() => {\n let buffer = [];\n const flush = effect.uninterruptible(effect.suspend(() => {\n if (buffer.length === 0) {\n return effect.void;\n }\n const arr = buffer;\n buffer = [];\n return options.flush(arr);\n }));\n return effect.uninterruptibleMask(restore => restore(effect.sleep(options.window).pipe(effect.andThen(flush), effect.forever)).pipe(effect.forkDetach, effect.flatMap(fiber => effect.addFinalizer(() =>\n // Wait for any in-flight flush before draining the remaining buffer.\n effect.andThen(effect.fiberInterrupt(fiber), flush))), effect.as(effect.loggerMake(options => {\n buffer.push(self.log(options));\n }))));\n}));\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Chooses between tty and browser implementation. If the runtime\n * platform is known and fixed, prefer {@link consolePrettyBrowser} or\n * {@link consolePrettyTty}.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePretty()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * **Example** (Logging with console.error, when the environment has TTY)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Logger } from \"effect\"\n *\n * const prettyLoggerLayer = Layer.merge(\n * Logger.layer([Logger.consolePretty()]),\n * Layer.succeed(Logger.LogToStderr, true)\n * )\n *\n * Effect.log('hello').pipe(\n * Effect.provide(prettyLoggerLayer),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePrettyBrowser} for browser-specific implementation\n * @see {@link consolePrettyTty} for the TTY-mode implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePretty = effect.consolePretty;\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Intended to be used on platforms with a browser console.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePrettyBrowser()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePretty} for the platform-independent implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePrettyBrowser = effect.prettyLoggerBrowser;\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Intended to be used on platforms with tty console.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePrettyTty()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * **Example** (Logging with console.error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Logger } from \"effect\"\n *\n * const prettyLoggerLayer = Layer.merge(\n * Logger.layer([Logger.consolePrettyTty()]),\n * Layer.succeed(Logger.LogToStderr, true)\n * )\n *\n * Effect.log('hello').pipe(\n * Effect.provide(prettyLoggerLayer),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePretty} for the platform-independent implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePrettyTty = effect.prettyLoggerTty;\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style and writes them to the console.\n *\n * **Details**\n *\n * For example, a console logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=info`.\n *\n * **Example** (Logging logfmt output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleLogFmt) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleLogFmt = /*#__PURE__*/withConsoleLog(formatLogFmt);\n/**\n * A `Logger` which outputs logs using a structured format and writes them to\n * the console.\n *\n * **Details**\n *\n * For example, console structured output can contain\n * `message: [ \"info\", \"message\" ]`, `level: \"INFO\"`,\n * `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Logging structured output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleStructured) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleStructured = /*#__PURE__*/withConsoleLog(formatStructured);\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line and writes them to the console.\n *\n * **Details**\n *\n * For example, console JSON output can render as\n * `{\"message\":[\"hello\"],\"level\":\"INFO\",\"timestamp\":\"2025-01-03T14:28:57.508Z\",\n * \"annotations\":{\"key\":\"value\"},\"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Logging JSON output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleJson) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleJson = /*#__PURE__*/withConsoleLog(formatJson);\n/**\n * A `Logger` which includes log messages as tracer span events.\n *\n * **Details**\n *\n * This logger integrates logging with distributed tracing by recording\n * all log messages as events on the current local span, making them visible\n * in tracing tools like OpenTelemetry, Jaeger, or Zipkin. A log made with no\n * current span, or while the nearest parent span is an `ExternalSpan`, is not\n * recorded by this logger.\n *\n * This logger is included in the default set of loggers for all Effect programs,\n * so log messages automatically appear as span events unless you override the\n * default loggers.\n *\n * **Example** (Recording logs as trace span events)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"span event\").pipe(\n * Effect.withSpan(\"operation\"),\n * Effect.provide(Logger.layer([Logger.tracerLogger]))\n * )\n * Effect.runSync(program)\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const tracerLogger = effect.tracerLogger;\n/**\n * Creates a `Layer` which will overwrite the current set of loggers with the\n * specified array of `loggers`.\n *\n * **Details**\n *\n * If the specified array of `loggers` should be _merged_ with the current set\n * of loggers (instead of overwriting them), set `mergeWithExisting` to `true`.\n *\n * **Example** (Providing logger layers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n * messages.push(options.message)\n * })\n * const CustomLoggerLayer = Logger.layer([customLogger])\n *\n * const program = Effect.log(\"Application started\").pipe(\n * Effect.provide(CustomLoggerLayer)\n * )\n * Effect.runSync(program)\n * messages // => [[\"Application started\"]]\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (loggers, options) => Layer.effect(CurrentLoggers, withFiber(effect.fnUntraced(function* (fiber) {\n const currentLoggers = new Set(options?.mergeWithExisting === true ? fiber.getRef(effect.CurrentLoggers) : []);\n for (const logger of loggers) {\n currentLoggers.add(isEffect(logger) ? yield* logger : logger);\n }\n return currentLoggers;\n})));\n/**\n * Creates a scoped logger that writes string logger output to a file.\n *\n * **Details**\n *\n * The returned effect requires `FileSystem` and `Scope`. The file logger is\n * built on `batched`, so each log call formats and buffers its string output.\n * Each flushed batch is written to the specified path, and remaining entries\n * are flushed when the scope closes.\n *\n * **Example** (Writing JSON logs to a file)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n * writeAll: (buffer: Uint8Array) => Effect.sync(() => {\n * writes.push(new TextDecoder().decode(buffer).trim())\n * })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/log.txt\")\n * yield* Effect.log(\"a\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * yield* Effect.log(\"b\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * yield* Effect.log(\"c\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"a\\nb\\nc\"]\n * ```\n *\n * **Example** (Writing logs to files)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n * writeAll: (buffer: Uint8Array) => Effect.sync(() => {\n * writes.push(new TextDecoder().decode(buffer).trim())\n * })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/app.log\", {\n * batchWindow: \"1 hour\"\n * })\n * yield* Effect.log(\"Application started\").pipe(\n * Effect.provide(Logger.layer([fileLogger]))\n * )\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"Application started\"]\n * ```\n *\n * @stability unstable\n * @category logging\n * @since 4.0.0\n */\nexport const toFile = /*#__PURE__*/dual(args => isLogger(args[0]), (self, path, options) => effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const logFile = yield* fs.open(path, {\n flag: \"a+\",\n ...options\n });\n const encoder = new TextEncoder();\n return yield* batched(self, {\n window: options?.batchWindow ?? 1000,\n flush: output => effect.ignore(logFile.writeAll(encoder.encode(output.join(\"\\n\") + \"\\n\")))\n });\n}));\n//# sourceMappingURL=Logger.js.map","/**\n * Stores fiber-safe mutable state inside Effect programs.\n *\n * A `Ref<A>` holds one value and exposes reads, writes, and atomic\n * transformations as effects, so state changes compose with Effect's\n * concurrency model. This module includes constructors, safe and unsafe reads,\n * set and get-and-set helpers, update and modify helpers, and conditional\n * update variants that leave the value unchanged when an `Option.none` result\n * is returned.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Effect from \"./Effect.js\";\nimport { dual, identity } from \"./Function.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as MutableRef from \"./MutableRef.js\";\nconst TypeId = \"~effect/Ref\";\nconst RefProto = {\n [TypeId]: {\n _A: identity\n },\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"Ref\",\n ref: this.ref\n };\n }\n};\n/**\n * Creates a new Ref with the specified initial value (unsafe version).\n *\n * **When to use**\n *\n * Use when you need immediate synchronous construction and can guarantee\n * that creating the `Ref` outside of `Effect` is safe.\n *\n * **Gotchas**\n *\n * Prefer `Ref.make` for Effect-wrapped creation in Effect programs.\n *\n * **Example** (Creating a ref unsafely)\n *\n * ```ts import.meta.vitest\n * import { Ref } from \"effect\"\n *\n * const counter = Ref.makeUnsafe(0)\n * Ref.getUnsafe(counter) // => 0\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = value => {\n const self = Object.create(RefProto);\n self.ref = MutableRef.make(value);\n return self;\n};\n/**\n * Creates a new Ref with the specified initial value.\n *\n * **When to use**\n *\n * Use to create a `Ref` for shared mutable state inside an Effect program.\n *\n * **Example** (Creating a ref)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(42)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @see {@link makeUnsafe} for synchronous construction outside Effect code\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = value => Effect.sync(() => makeUnsafe(value));\n/**\n * Gets the current value of the Ref.\n *\n * **When to use**\n *\n * Use to read the current `Ref` value without changing it.\n *\n * **Example** (Getting the current value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(42)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @see {@link set} for replacing the current value\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const get = self => Effect.sync(() => self.ref.current);\n/**\n * Sets the value of the Ref to the specified value.\n *\n * **When to use**\n *\n * Use to replace the current `Ref` value with a known value.\n *\n * **Example** (Setting a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(0)\n * yield* Ref.set(ref, 42)\n * return yield* Ref.get(ref)\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const ref = yield* Ref.make(0)\n * yield* Ref.set(ref, 100)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * await Effect.runPromise(program2) // => 100\n * ```\n *\n * @see {@link getAndSet} for setting while returning the previous value\n * @see {@link setAndGet} for setting while returning the new value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => MutableRef.set(self.ref, value)));\n/**\n * Gets the current value of the Ref, sets it to the specified value, and returns the previous value atomically.\n *\n * **When to use**\n *\n * Use to replace a plain `Ref` value while returning the previous value.\n *\n * **Example** (Replacing a value atomically)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(\"initial\")\n *\n * const previous = yield* Ref.getAndSet(ref, \"updated\")\n * const current = yield* Ref.get(ref)\n * return [previous, current]\n * })\n *\n * await Effect.runPromise(program) // => [\"initial\", \"updated\"]\n * ```\n *\n * @see {@link set} for setting without returning the previous value\n * @see {@link getAndUpdate} for deriving the new value from the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndSet = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => {\n const current = self.ref.current;\n self.ref.current = value;\n return current;\n}));\n/**\n * Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically.\n *\n * **When to use**\n *\n * Use to derive a new `Ref` value while returning the previous value.\n *\n * **Example** (Updating and returning the previous value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const previous = yield* Ref.getAndUpdate(counter, (n) => n * 2)\n * const current = yield* Ref.get(counter)\n * return [previous, current]\n * })\n *\n * await Effect.runPromise(program) // => [10, 20]\n * ```\n *\n * @see {@link update} for updating without returning the previous value\n * @see {@link updateAndGet} for returning the new value instead\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdate = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const current = self.ref.current;\n self.ref.current = f(current);\n return current;\n}));\n/**\n * Gets the current value of the Ref and updates it atomically with the given partial function.\n *\n * **When to use**\n *\n * Use to return the previous `Ref` value while applying a conditional update.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged. The effect\n * always returns the value that was in the Ref before the attempted update.\n *\n * **Example** (Conditionally updating and returning the previous value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const previous1 = yield* Ref.getAndUpdateSome(\n * counter,\n * (n) => n > 3 ? Option.some(n * 2) : Option.none()\n * )\n * const current1 = yield* Ref.get(counter)\n * const previous2 = yield* Ref.getAndUpdateSome(\n * counter,\n * (n) => n < 3 ? Option.some(n * 2) : Option.none()\n * )\n * const current2 = yield* Ref.get(counter)\n * return [previous1, current1, previous2, current2]\n * })\n *\n * await Effect.runPromise(program) // => [5, 10, 10, 10]\n * ```\n *\n * @see {@link getAndUpdate} for always applying an update\n * @see {@link updateSome} for conditional updates without returning the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdateSome = /*#__PURE__*/dual(2, (self, pf) => Effect.sync(() => {\n const current = self.ref.current;\n const option = pf(current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n return current;\n}));\n/**\n * Sets the value of the Ref atomically to the specified value and returns the new value.\n *\n * **When to use**\n *\n * Use when you want to set a `Ref` value and immediately get it back in one\n * atomic operation.\n *\n * **Example** (Setting and returning the new value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(10)\n *\n * const newValue = yield* Ref.setAndGet(ref, 42)\n * const current = yield* Ref.get(ref)\n * return [newValue, current]\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const counter = yield* Ref.make(0)\n * return yield* Ref.setAndGet(counter, 20)\n * })\n *\n * await Effect.runPromise(program) // => [42, 42]\n * await Effect.runPromise(program2) // => 20\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const setAndGet = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => self.ref.current = value));\n/**\n * Modifies the value of the Ref atomically using the given function.\n *\n * **When to use**\n *\n * Use to compute both a separate return value and the next stored `Ref` value\n * in one atomic update.\n *\n * **Details**\n *\n * The function receives the current value and returns a tuple of\n * `[result, newValue]`. The Ref is updated with `newValue`, and `result` is\n * returned by the effect.\n *\n * **Example** (Modifying a value atomically)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const result = yield* Ref.modify(counter, (n) => [\n * `Previous value was ${n}`,\n * n * 2\n * ])\n * const current = yield* Ref.get(counter)\n * return [result, current]\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const state = yield* Ref.make({ count: 0, total: 0 })\n * return yield* Ref.modify(state, (s) => [\n * s.count,\n * { count: s.count + 1, total: s.total + s.count + 1 }\n * ])\n * })\n *\n * await Effect.runPromise(program) // => [\"Previous value was 10\", 20]\n * await Effect.runPromise(program2) // => 0\n * ```\n *\n * @see {@link updateAndGet} for returning the new stored value\n * @see {@link modifySome} for optionally updating while returning a separate result\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const [b, a] = f(self.ref.current);\n self.ref.current = a;\n return b;\n}));\n/**\n * Computes a result atomically and optionally updates the value of the `Ref`.\n *\n * **When to use**\n *\n * Use to compute a return value while optionally updating a plain `Ref`.\n *\n * **Details**\n *\n * The callback receives the current value and returns `[result, nextValue]`,\n * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`,\n * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left\n * unchanged. The returned effect always succeeds with `result`.\n *\n * **Example** (Conditionally modifying a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const result1 = yield* Ref.modifySome(\n * counter,\n * (n) =>\n * n > 3\n * ? [`incremented ${n}`, Option.some(n + 10)]\n * : [\"no change\", Option.none()]\n * )\n * const current1 = yield* Ref.get(counter)\n * const result2 = yield* Ref.modifySome(\n * counter,\n * (n) =>\n * n < 10\n * ? [`decremented ${n}`, Option.some(n - 5)]\n * : [\"no change\", Option.none()]\n * )\n * const current2 = yield* Ref.get(counter)\n * return [result1, current1, result2, current2]\n * })\n *\n * await Effect.runPromise(program) // => [\"incremented 5\", 15, \"no change\", 15]\n * ```\n *\n * @see {@link modify} for always storing a new value\n * @see {@link updateSome} for optional updates without a separate return value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modifySome = /*#__PURE__*/dual(2, (self, pf) => modify(self, value => {\n const [b, option] = pf(value);\n return [b, option._tag === \"None\" ? value : option.value];\n}));\n/**\n * Updates the value of the Ref atomically using the given function.\n *\n * **When to use**\n *\n * Use to apply a `Ref` state transition without returning a value.\n *\n * **Example** (Updating a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * yield* Ref.update(counter, (n) => n * 2)\n * return yield* Ref.get(counter)\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n * yield* Ref.update(counter, (n: number) => n + 10)\n * return yield* Ref.get(counter)\n * })\n *\n * await Effect.runPromise(program) // => 10\n * await Effect.runPromise(program2) // => 15\n * ```\n *\n * @see {@link updateAndGet} for returning the new value\n * @see {@link getAndUpdate} for returning the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n self.ref.current = f(self.ref.current);\n}));\n/**\n * Updates the value of the Ref atomically using the given function and returns the new value.\n *\n * **When to use**\n *\n * Use to apply a `Ref` state transition and return the new stored value.\n *\n * **Example** (Updating and returning the new value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const newValue = yield* Ref.updateAndGet(counter, (n) => n * 3)\n * const current = yield* Ref.get(counter)\n * return [newValue, current]\n * })\n *\n * await Effect.runPromise(program) // => [15, 15]\n * ```\n *\n * @see {@link update} for updating without returning the new value\n * @see {@link getAndUpdate} for returning the previous value instead\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGet = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => self.ref.current = f(self.ref.current)));\n/**\n * Updates the value of the Ref atomically using the given partial function.\n *\n * **When to use**\n *\n * Use to apply a conditional `Ref` update without returning a value.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged.\n *\n * **Example** (Conditionally updating a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * yield* Ref.updateSome(\n * counter,\n * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()\n * )\n * const before = yield* Ref.get(counter)\n * yield* Ref.set(counter, 6)\n * yield* Ref.updateSome(\n * counter,\n * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()\n * )\n * const after = yield* Ref.get(counter)\n * return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [5, 12]\n * ```\n *\n * @see {@link update} for always applying an update\n * @see {@link updateSomeAndGet} for returning the resulting current value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSome = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const option = f(self.ref.current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n}));\n/**\n * Updates the value of the Ref atomically using the given partial function and returns the current value.\n *\n * **When to use**\n *\n * Use to apply a conditional `Ref` update and return the resulting current\n * value.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged. The effect\n * returns the current value of the Ref after the potential update.\n *\n * **Example** (Conditionally updating and returning the current value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const result1 = yield* Ref.updateSomeAndGet(\n * counter,\n * (n) => n > 5 ? Option.some(n / 2) : Option.none()\n * )\n * const result2 = yield* Ref.updateSomeAndGet(\n * counter,\n * (n) => n > 5 ? Option.some(n / 2) : Option.none()\n * )\n * return [result1, result2]\n * })\n *\n * await Effect.runPromise(program) // => [5, 5]\n * ```\n *\n * @see {@link updateSome} for conditional updates without returning a value\n * @see {@link updateAndGet} for always updating and returning the new value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSomeAndGet = /*#__PURE__*/dual(2, (self, pf) => Effect.sync(() => {\n const option = pf(self.ref.current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n return self.ref.current;\n}));\n/**\n * Gets the current value of the Ref synchronously (unsafe version).\n *\n * **When to use**\n *\n * Use when you need immediate synchronous access and can guarantee that\n * reading the `Ref` outside of `Effect` is safe.\n *\n * **Gotchas**\n *\n * Prefer `Ref.get` for Effect-wrapped access in Effect programs.\n *\n * **Example** (Reading a ref unsafely)\n *\n * ```ts import.meta.vitest\n * import { Ref } from \"effect\"\n *\n * const counter = Ref.makeUnsafe(42)\n * Ref.getUnsafe(counter) // => 42\n * ```\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getUnsafe = self => self.ref.current;\n//# sourceMappingURL=Ref.js.map","/**\n * Helpers for turning an `Effect` program into a host application's main entry\n * point. This module is the low-level layer used by platform adapters to run a\n * main effect, observe its fiber, report unhandled failures, and translate the\n * resulting `Exit` into an application or process exit code. It provides\n * `makeRunMain`, the default teardown behavior, and error markers for custom\n * exit codes and already-reported failures. Application code usually calls the\n * platform-provided runner instead of using this module directly.\n *\n * @stability stable\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { constVoid, dual } from \"effect/Function\";\n/**\n * Annotation specifying the exit code for an interruption handled by\n * {@link defaultTeardown}.\n *\n * **When to use**\n *\n * Use when a component finishes a program by interrupting its main fiber on\n * purpose, such as a stdio server shutting down after stdin closes, and that\n * shutdown should not report the `130` code reserved for external interruption.\n *\n * **Details**\n *\n * Pass the annotation through `Fiber.interruptAs`. {@link defaultTeardown}\n * reads it from the interrupt reasons of the final `Cause`.\n *\n * **Gotchas**\n *\n * The annotation is read from the `Cause`, not from the running effect's\n * services, so providing it with `Effect.provideService` has no effect.\n *\n * **Example** (Exiting with 0 after an intentional interruption)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Fiber, Runtime } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const main = yield* Effect.forkChild(Effect.never)\n * yield* Fiber.interruptAs(main, undefined, Context.make(Runtime.InterruptExitCode, 0))\n * return yield* Fiber.await(main)\n * })\n *\n * const exitCodes: Array<number> = []\n * Runtime.defaultTeardown(await Effect.runPromise(program), (code) => exitCodes.push(code))\n *\n * exitCodes // => [0]\n * ```\n *\n * @see {@link defaultTeardown} for how annotated and unannotated interruptions combine\n * @see {@link errorExitCode} for the equivalent marker on failures\n *\n * @stability stable\n * @category annotations\n * @since 4.1.3\n */\nexport class InterruptExitCode extends /*#__PURE__*/Context.Service()(\"effect/Runtime/InterruptExitCode\") {}\n/**\n * The default teardown function that determines exit codes from an Effect exit.\n *\n * **When to use**\n *\n * Use as the standard teardown for main programs with conventional process\n * exit codes and support for {@link errorExitCode}.\n *\n * **Details**\n *\n * This teardown follows these exit-code rules:\n *\n * - `0` for successful completion.\n * - The largest {@link InterruptExitCode} when every reason is an annotated interruption.\n * - `130` for interruption-only failures with any unannotated reason.\n * - The squashed error's {@link errorExitCode} value for other failures when\n * present.\n * - `1` for other failures.\n *\n * **Gotchas**\n *\n * Interruption codes apply only when the Cause contains nothing but\n * interruptions. A Cause that mixes interruptions with errors or defects uses\n * the squashed error path instead.\n *\n * **Example** (Referencing default teardown)\n *\n * ```ts import.meta.vitest\n * import { Exit, Runtime } from \"effect\"\n *\n * const exitCodes: Array<number> = []\n * const collectExitCode = (exit: Exit.Exit<any, any>) =>\n * Runtime.defaultTeardown(exit, (code) => exitCodes.push(code))\n *\n * collectExitCode(Exit.succeed(42))\n * collectExitCode(Exit.fail(\"error\"))\n * collectExitCode(Exit.interrupt(123))\n *\n * exitCodes // => [0, 1, 130]\n * ```\n *\n * **Example** (Distinguishing completion from external interruption)\n *\n * ```ts import.meta.vitest\n * import { Cause, Context, Exit, Runtime } from \"effect\"\n *\n * const completed = Cause.annotate(Cause.interrupt(1), Context.make(Runtime.InterruptExitCode, 0))\n * const custom = Cause.annotate(Cause.interrupt(2), Context.make(Runtime.InterruptExitCode, 7))\n * const external = Cause.interrupt(3)\n * const exitCodes: Array<number> = []\n * const collectExitCode = (cause: Cause.Cause<never>) =>\n * Runtime.defaultTeardown(Exit.failCause(cause), (code) => exitCodes.push(code))\n *\n * collectExitCode(completed)\n * collectExitCode(Cause.combine(completed, custom))\n * collectExitCode(Cause.combine(custom, completed))\n * collectExitCode(Cause.combine(completed, external))\n * collectExitCode(Cause.combine(external, completed))\n *\n * exitCodes // => [0, 7, 7, 130, 130]\n * ```\n *\n * @see {@link errorExitCode} for customizing failure exit codes\n *\n * @stability stable\n * @category running\n * @since 4.0.0\n */\nexport const defaultTeardown = (exit, onExit) => {\n if (Exit.isSuccess(exit)) return onExit(0);\n if (Cause.hasInterruptsOnly(exit.cause)) {\n let code = -Infinity;\n for (const reason of exit.cause.reasons) {\n const annotated = Context.getOrUndefined(Cause.reasonAnnotations(reason), InterruptExitCode);\n if (annotated === undefined) return onExit(130);\n code = Math.max(code, annotated);\n }\n return onExit(code);\n }\n return onExit(getErrorExitCode(Cause.squash(exit.cause)));\n};\n/**\n * Creates a platform-specific main program runner that handles Effect execution lifecycle.\n *\n * **When to use**\n *\n * Use when building a runtime adapter for a host platform.\n *\n * **Details**\n *\n * The setup function runs before user code and receives the main fiber and a\n * teardown callback to install platform-specific signal handlers, observers,\n * and exit behavior.\n *\n * Most applications should use a platform-provided runner, such as\n * `NodeRuntime.runMain`, rather than constructing one directly.\n *\n * `disableErrorReporting` disables the automatic log emitted for unreported\n * non-interruption failures. It does not change exit-code calculation or the\n * custom teardown callback.\n *\n * **Gotchas**\n *\n * The setup function is responsible for observing the fiber and eventually\n * invoking teardown. `makeRunMain` also tries to keep the host process alive\n * with a long interval while the main fiber is running; if the host blocks\n * timers, the runner still starts but cannot use that keep-alive fallback.\n *\n * **Example** (Creating platform runners)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Runtime } from \"effect\"\n *\n * const events: Array<string> = []\n * const completed = new Promise<readonly [Exit.Exit<unknown, unknown>, number]>((resolve) => {\n * // Create a simple runner for a hypothetical platform\n * const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {\n * // Handle fiber completion\n * fiber.addObserver((exit) => {\n * teardown(exit, (code) => resolve([exit, code]))\n * })\n * })\n *\n * // Use the runner\n * const program = Effect.sync(() => {\n * events.push(\"Starting program\", \"Program completed\")\n * return \"success\"\n * })\n *\n * runMain(program, {\n * teardown: (exit, onExit) => {\n * events.push(\"Custom teardown logic\")\n * Runtime.defaultTeardown(exit, onExit)\n * }\n * })\n * })\n *\n * const result = await completed\n * result // => [Exit.succeed(\"success\"), 0]\n * events // => [\"Starting program\", \"Program completed\", \"Custom teardown logic\"]\n * ```\n *\n * @stability stable\n * @category running\n * @since 4.0.0\n */\nexport const makeRunMain = f => dual(args => Effect.isEffect(args[0]), (effect, options) => {\n const main = options?.disableErrorReporting === true ? effect : Effect.tapCause(effect, cause => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.void;\n const isReported = getErrorReported(Cause.squash(cause));\n return isReported ? Effect.logError(cause) : Effect.void;\n });\n const teardown = options?.teardown ?? defaultTeardown;\n Effect.runFork(Effect.withFiber(fiber => {\n try {\n const keepAlive = globalThis.setInterval(constVoid, 2_147_483_647);\n fiber.addObserver(() => {\n clearInterval(keepAlive);\n });\n } catch {}\n f({\n fiber,\n teardown\n });\n return main;\n }));\n});\n/**\n * Allows associating an exit code with an error for determining the process\n * exit code on failure.\n *\n * **When to use**\n *\n * Use when error classes should map failures to a specific process exit code\n * when handled by {@link defaultTeardown}.\n *\n * **Details**\n *\n * Attach this marker as a readonly property on an error object. When the main\n * program fails, {@link defaultTeardown} squashes the Cause and reads the marker\n * from the resulting error value.\n *\n * **Gotchas**\n *\n * The marker is read from the squashed failure value. If a Cause contains\n * multiple failures, the selected squashed error determines the exit code.\n *\n * **Example** (Setting a process exit code)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n * readonly [Runtime.errorExitCode] = 42\n * }\n *\n * Runtime.getErrorExitCode(new MyError()) // => 42\n * ```\n *\n * @see {@link errorReported} for controlling automatic error logging\n * @see {@link defaultTeardown} for the default failure exit-code rules that read this marker\n * @see {@link getErrorExitCode} for reading the marker from unknown error values\n *\n * @stability stable\n * @category symbols\n * @since 4.0.0\n */\nexport const errorExitCode = \"~effect/Runtime/errorExitCode\";\n/**\n * Reads the runtime exit-code marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read a custom failure exit code from an unknown error value, falling\n * back to the default failure code.\n *\n * **Details**\n *\n * Returns the numeric `[Runtime.errorExitCode]` property when it is present on\n * an object. Otherwise returns `1`, the default failure exit code used by\n * `defaultTeardown`.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-number marker values all return\n * `1`.\n *\n * @see {@link errorExitCode} for the marker read by this function\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorExitCode = u => {\n if (typeof u === \"object\" && u !== null && errorExitCode in u) {\n const code = u[errorExitCode];\n if (typeof code === \"number\") {\n return code;\n }\n }\n return 1;\n};\n/**\n * Defines the runtime marker that controls default `runMain` error logging for an error.\n *\n * **When to use**\n *\n * Use when you need error classes reported by application code to avoid being\n * logged again by the default main runner.\n *\n * **Details**\n *\n * Set `[Runtime.errorReported]` to `false` on an error object to suppress the\n * runtime log because the error has already been reported. Omitted or\n * non-boolean values are treated as `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * This marker controls only automatic error logging. It does not change the\n * failure Cause or the process exit code.\n * `makeRunMain` reads the marker from `Cause.squash(cause)`, so for causes\n * with multiple failures, the squashed error determines whether default logging\n * is suppressed.\n *\n * **Example** (Suppressing error reporting)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n * readonly [Runtime.errorReported] = false\n * }\n *\n * Runtime.getErrorReported(new MyError()) // => false\n * ```\n *\n * @see {@link errorExitCode} for controlling failure exit codes\n * @see {@link getErrorReported} for reading the marker from unknown error values\n *\n * @stability stable\n * @category symbols\n * @since 4.0.0\n */\nexport const errorReported = \"~effect/Runtime/errorReported\";\n/**\n * Reads the runtime error-reporting marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read whether an unknown error value should be treated as already\n * reported by the default main runner.\n *\n * **Details**\n *\n * Returns a boolean `[Runtime.errorReported]` property when it is present on an\n * object. Otherwise returns `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-boolean marker values all return\n * `true`.\n *\n * @see {@link errorReported} for the marker read by this function\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorReported = u => {\n if (typeof u === \"object\" && u !== null && errorReported in u) {\n const isReported = u[errorReported];\n if (typeof isReported === \"boolean\") {\n return isReported;\n }\n }\n return true;\n};\n//# sourceMappingURL=Runtime.js.map","/** @internal */\nexport const version = \"4.2.0\";\n//# sourceMappingURL=version.js.map","/**\n * The `effect` package version used in telemetry headers, resources, and scopes.\n *\n * @stability unstable\n * @since 4.0.2\n */\nimport { version } from \"./internal/version.js\";\nlet currentVersion = version;\n/**\n * Returns the current version of the `effect` package.\n *\n * **Details**\n *\n * Defaults to the release version unless overridden by `setCurrentVersion`.\n *\n * @stability unstable\n * @category getters\n * @since 4.0.2\n */\nexport const getCurrentVersion = () => currentVersion;\n/**\n * Overrides the version returned by `getCurrentVersion`.\n *\n * **Gotchas**\n *\n * Applies to this copy of the module. Existing telemetry layers retain the\n * version they read when built.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.2\n */\nexport const setCurrentVersion = version => {\n currentVersion = version;\n};\n//# sourceMappingURL=Version.js.map","/**\n * Describes HTTP request and response bodies before they reach a platform\n * adapter.\n *\n * `HttpBody` is the shared body representation used by the HTTP modules. Each\n * variant stores the payload together with metadata that can be known before\n * sending it, such as `contentType` and `contentLength`. This module includes\n * body constructors for common payload shapes, support for schema-encoded JSON\n * bodies, streaming and file-backed bodies, and the error type used when body\n * construction fails.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as ByteSize from \"../ByteSize.js\";\nimport * as Data from \"../Data.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { format } from \"../Formatter.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Option from \"../Option.js\";\nimport * as PlatformError from \"../PlatformError.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as SchemaParser from \"../SchemaParser.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpBody\";\n/**\n * Returns `true` if the provided value is an `HttpBody`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpBody = u => Predicate.hasProperty(u, TypeId);\nconst HttpBodyErrorTypeId = \"~effect/http/HttpBody/HttpBodyError\";\n/**\n * Error produced while constructing an HTTP body from JSON or schema-encoded input.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class HttpBodyError extends /*#__PURE__*/Data.TaggedError(\"HttpBodyError\") {\n /**\n * Marks this value as an HTTP body error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [HttpBodyErrorTypeId] = HttpBodyErrorTypeId;\n}\n/**\n * Checks whether a value is an `HttpBodyError`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpBodyError = u => Predicate.hasProperty(u, HttpBodyErrorTypeId);\nclass Proto {\n [TypeId];\n constructor() {\n this[TypeId] = TypeId;\n }\n [Inspectable.NodeInspectSymbol]() {\n return this.toJSON();\n }\n toString() {\n return format(this, {\n ignoreToString: true\n });\n }\n}\n/**\n * HTTP body variant representing the absence of request content.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Empty extends Proto {\n _tag = \"Empty\";\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Empty\"\n };\n }\n}\n/**\n * Provides the singleton empty HTTP body.\n *\n * **When to use**\n *\n * Use when you need an HTTP body value that represents no body content.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/new Empty();\n/**\n * HTTP body variant containing an arbitrary runtime body value with optional content metadata.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Raw extends Proto {\n _tag = \"Raw\";\n body;\n contentType;\n contentLength;\n constructor(body, contentType, contentLength) {\n super();\n this.body = body;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Raw\",\n body: this.body,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a raw HTTP body from an arbitrary value and optional `contentType` and `contentLength` metadata.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const raw = (body, options) => new Raw(body, options?.contentType, options?.contentLength);\n/**\n * HTTP body variant backed by a `Uint8Array`.\n *\n * **Details**\n *\n * It stores the bytes, content type, and byte length.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Uint8Array extends Proto {\n _tag = \"Uint8Array\";\n contentType;\n contentLength;\n /** Original text retained for adapters that can skip encoding. */\n text;\n _body;\n constructor(body, contentType, contentLength, text) {\n super();\n this._body = body;\n this.text = text;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n get body() {\n return this._body ??= encodeText(this.text);\n }\n toJSON() {\n const toString = this.contentType.startsWith(\"text/\") || this.contentType.endsWith(\"json\");\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Uint8Array\",\n body: toString ? new TextDecoder().decode(this.body) : `Uint8Array(${this.body.length})`,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a byte-array HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`, and the content length is the byte array length.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const uint8Array = (body, contentType) => new Uint8Array(body, contentType ?? \"application/octet-stream\", body.length);\nconst encoder = /*#__PURE__*/new TextEncoder();\n// Buffer encodes UTF-8 faster than TextEncoder when available.\nconst buffer = globalThis.Buffer;\nconst encodeText = buffer !== undefined ? body => buffer.from(body, \"utf8\") : body => encoder.encode(body);\n/**\n * Creates a UTF-8 encoded text HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `text/plain`. Text bodies are encoded lazily.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const text = (body, contentType) => {\n if (typeof body !== \"string\") {\n // Preserve untyped callers that relied on TextEncoder coercion.\n body = body === undefined ? \"\" : String(body);\n }\n if (buffer !== undefined) {\n return new Uint8Array(undefined, contentType ?? \"text/plain\", buffer.byteLength(body, \"utf8\"), body);\n }\n const bytes = encoder.encode(body);\n return new Uint8Array(bytes, contentType ?? \"text/plain\", bytes.length, body);\n};\n/**\n * Creates a JSON HTTP body using `JSON.stringify`, throwing if serialization fails.\n *\n * **Details**\n *\n * The content type defaults to `application/json`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonUnsafe = (body, contentType) => text(JSON.stringify(body), contentType ?? \"application/json\");\n/**\n * Creates a JSON HTTP body in an `Effect`.\n *\n * **Details**\n *\n * `JSON.stringify` failures are captured as `HttpBodyError` values, and the content type defaults to `application/json`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const json = (body, contentType) => Effect.try({\n try: () => text(JSON.stringify(body), contentType ?? \"application/json\"),\n catch: cause => new HttpBodyError({\n reason: {\n _tag: \"JsonError\"\n },\n cause\n })\n});\n/**\n * Creates a JSON body constructor that first encodes values with the schema's JSON codec.\n *\n * **Details**\n *\n * Schema encoding issues and JSON serialization failures are returned as `HttpBodyError` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonSchema = (schema, options) => {\n const encode = SchemaParser.encodeUnknownEffect(Schema.toCodecJson(schema));\n return (body, contentType) => encode(body, options).pipe(Effect.mapError(issue => new HttpBodyError({\n reason: {\n _tag: \"SchemaError\",\n issue\n },\n cause: issue\n })), Effect.flatMap(body => json(body, contentType)));\n};\n/**\n * Creates an `application/x-www-form-urlencoded` HTTP body from `UrlParams`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const urlParams = (urlParams, contentType) => text(UrlParams.toString(UrlParams.fromInput(urlParams)), contentType ?? \"application/x-www-form-urlencoded\");\n/**\n * HTTP body variant backed by Web `FormData`.\n *\n * **Details**\n *\n * The content type and content length are left unset so the runtime can supply multipart boundaries.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class FormData extends Proto {\n _tag = \"FormData\";\n contentType = undefined;\n contentLength = undefined;\n formData;\n constructor(formData) {\n super();\n this.formData = formData;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"FormData\",\n formData: this.formData\n };\n }\n}\n/**\n * Wraps a Web `FormData` value as an HTTP body.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const formData = body => new FormData(body);\nconst appendFormDataValue = (formData, key, value) => {\n if (value == null) {\n return;\n }\n if (typeof value === \"object\") {\n formData.append(key, value);\n return;\n }\n formData.append(key, String(value));\n};\n/**\n * Creates a `FormData` HTTP body from a record.\n *\n * **Details**\n *\n * Array fields append each item under the same key; primitive values are stringified, `File` and `Blob` values are appended directly, and nullish values are skipped.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const formDataRecord = entries => {\n const data = new globalThis.FormData();\n for (const [key, value] of Object.entries(entries)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n appendFormDataValue(data, key, item);\n }\n } else {\n appendFormDataValue(data, key, value);\n }\n }\n return formData(data);\n};\n/**\n * HTTP body variant backed by a stream of `Uint8Array` chunks.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Stream extends Proto {\n _tag = \"Stream\";\n stream;\n contentType;\n contentLength;\n constructor(stream, contentType, contentLength) {\n super();\n this.stream = stream;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Stream\",\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a streaming HTTP body from a stream of byte chunks.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`; content length is optional.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (body, contentType, contentLength) => new Stream(body, contentType ?? \"application/octet-stream\", contentLength);\nconst fileRangeSize = (input, field, method) => {\n const size = ByteSize.fromInput(input);\n return Option.isSome(size) ? Effect.succeed(size.value) : Effect.fail(PlatformError.badArgument({\n module: \"HttpBody\",\n method,\n description: `Invalid ${field}: ${input}`\n }));\n};\nconst fileContentLength = /*#__PURE__*/Effect.fnUntraced(function* (size, method, options) {\n const offset = options?.offset === undefined ? ByteSize.zero : yield* fileRangeSize(options.offset, \"offset\", method);\n const bytesToRead = options?.bytesToRead === undefined ? undefined : yield* fileRangeSize(options.bytesToRead, \"bytesToRead\", method);\n const available = offset >= size ? BigInt(\"0\") : size - offset;\n const length = bytesToRead === undefined || bytesToRead > available ? available : bytesToRead;\n if (length > BigInt(Number.MAX_SAFE_INTEGER)) {\n return yield* Effect.fail(PlatformError.badArgument({\n module: \"HttpBody\",\n method,\n description: `Content length exceeds Number.MAX_SAFE_INTEGER: ${length}`\n }));\n }\n return Number(length);\n});\n/**\n * Creates a streaming HTTP body for a file path.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, stats the file to set the selected content length, and can fail with\n * `PlatformError`.\n *\n * Range validation and file access are deferred until the effect runs. Numeric range inputs must be\n * non-negative safe integers; bigint and byte-size strings can represent larger values. Malformed strings,\n * negative values, and non-finite, fractional, or unsafe numbers fail with `PlatformError` / `BadArgument`.\n *\n * The selected length is calculated exactly with bigint arithmetic and clamped to the bytes available after\n * `offset` (zero at or past EOF). Since `Stream.contentLength` is a number, a final length above\n * `Number.MAX_SAFE_INTEGER` fails with `BadArgument`. Larger sizes, offsets, and byte counts are valid when\n * the final clamped length is representable; the resulting Content-Length header preserves that exact length.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (path, options) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.flatMap(fs.stat(path), info => Effect.map(fileContentLength(info.size, \"file\", options), contentLength => stream(fs.stream(path, options), options?.contentType, contentLength))));\n/**\n * Creates a streaming HTTP body for a file path using already-known file information.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, uses the provided file size to determine the selected content length, and can\n * fail with `PlatformError`.\n *\n * Like {@link file}, this constructor validates ranges lazily and calculates the EOF-clamped length with exact\n * bigint arithmetic. Invalid range inputs and final lengths above `Number.MAX_SAFE_INTEGER` fail with\n * `PlatformError` / `BadArgument`. Larger sizes, offsets, and byte counts remain valid when the final length\n * is representable as a safe integer, preserving the exact Content-Length header.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fileFromInfo = (path, info, options) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.map(fileContentLength(info.size, \"fileFromInfo\", options), contentLength => stream(fs.stream(path, options), options?.contentType, contentLength)));\n//# sourceMappingURL=HttpBody.js.map","/**\n * Defines supported HTTP method names for the unstable HTTP modules.\n *\n * Values are uppercase string literals such as `\"GET\"` and `\"POST\"`, matching\n * the method tokens used by HTTP requests and routes. This module also includes\n * helpers for checking whether a method can carry a request body and whether an\n * unknown value is one of the supported methods.\n *\n * @stability unstable\n * @since 4.0.0\n */\nexport function hasBody(method) {\n return method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" && method !== \"TRACE\";\n}\n/**\n * Provides a readonly set containing every supported `HttpMethod` literal.\n *\n * **When to use**\n *\n * Use when you need to iterate over or test membership against every supported\n * HTTP method literal.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const all = /*#__PURE__*/new Set([\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"HEAD\", \"OPTIONS\", \"TRACE\", \"QUERY\"]);\n/**\n * Provides tuples mapping each supported HTTP method to its short\n * request-constructor name.\n *\n * **When to use**\n *\n * Use when you need the mapping from supported HTTP method literals to their\n * short request-constructor names.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const allShort = [[\"GET\", \"get\"], [\"POST\", \"post\"], [\"PUT\", \"put\"], [\"DELETE\", \"del\"], [\"PATCH\", \"patch\"], [\"HEAD\", \"head\"], [\"OPTIONS\", \"options\"], [\"TRACE\", \"trace\"], [\"QUERY\", \"query\"]];\n/**\n * Checks whether a value is a `HttpMethod`.\n *\n * **Example** (Checking HTTP method values)\n *\n * ```ts import.meta.vitest\n * import { HttpMethod } from \"effect/http\"\n *\n * HttpMethod.isHttpMethod(\"GET\") // => true\n * HttpMethod.isHttpMethod(\"get\") // => false\n * HttpMethod.isHttpMethod(1) // => false\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpMethod = u => all.has(u);\n//# sourceMappingURL=HttpMethod.js.map","import * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as HttpBody from \"../HttpBody.js\";\n/**\n * @internal\n */\nexport const compressionTransformWeb = format => stream => stream.pipeThrough(new CompressionStream(format));\n/**\n * @internal\n */\nexport const singleChunkStream = data => new ReadableStream({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n }\n});\n/**\n * @internal\n */\nexport const compressBody = (body, algorithm, options) => {\n if (body._tag !== \"Uint8Array\" && body._tag !== \"Stream\") {\n return Effect.succeed(body);\n }\n if (body.contentLength !== undefined && body.contentLength < (options?.minSize ?? 1024)) {\n return Effect.succeed(body);\n }\n if (body._tag === \"Uint8Array\") {\n return Effect.map(Effect.promise(() => new globalThis.Response(compressionTransformWeb(algorithm)(singleChunkStream(body.body))).arrayBuffer()), buffer => HttpBody.uint8Array(new Uint8Array(buffer), body.contentType));\n }\n return Effect.succeed(HttpBody.stream(Stream.fromReadableStream({\n evaluate: () => compressionTransformWeb(algorithm)(Stream.toReadableStream(body.stream)),\n onError: identity\n }), body.contentType));\n};\n//# sourceMappingURL=compressionBody.js.map","import * as Headers from \"../Headers.js\";\n/**\n * @internal\n */\nexport const updateHeaders = (headers, body) => {\n if (body._tag === \"Empty\" || body._tag === \"FormData\") {\n return Headers.remove(Headers.remove(headers, \"content-type\"), \"content-length\");\n }\n headers = body.contentType === undefined ? Headers.remove(headers, \"content-type\") : Headers.set(headers, \"content-type\", body.contentType);\n return updateContentLength(headers, body);\n};\n/**\n * @internal\n */\nexport const updateContentLength = (headers, body) => {\n const contentLength = body._tag === \"Empty\" || body._tag === \"FormData\" ? undefined : body.contentLength;\n return contentLength === undefined ? Headers.remove(headers, \"content-length\") : Headers.set(headers, \"content-length\", contentLength.toString());\n};\n/**\n * @internal\n */\nexport const parseContentLength = contentLength => {\n if (contentLength === null || contentLength === undefined || !/^\\d+$/.test(contentLength)) {\n return undefined;\n }\n const parsed = Number(contentLength);\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n};\n//# sourceMappingURL=httpBody.js.map","/**\n * Parses and edits platform `URL` values.\n *\n * The HTTP modules use the standard `URL` object as their URL representation.\n * This module adds safe parsing and helpers that return updated copies when\n * changing credentials, host, path, protocol, query, or hash parts. Query\n * strings can also be read or updated through `UrlParams`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Cause from \"../Cause.js\";\nimport * as Data from \"../Data.js\";\nimport { dual } from \"../Function.js\";\nimport * as Redacted from \"../Redacted.js\";\nimport * as Result from \"../Result.js\";\nimport * as internal from \"./internal/urlParams.js\";\nimport * as UrlParams from \"./UrlParams.js\";\n/**\n * Error returned when constructing a `URL` fails.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UrlError extends /*#__PURE__*/Data.TaggedError(\"UrlError\") {}\n/**\n * Creates a `URL` safely by appending `UrlParams` and an optional hash to a URL string.\n *\n * **Details**\n *\n * Returns a `Result` that fails with `UrlError` if the URL cannot be constructed.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (url, params, hash) => Result.try({\n try: () => {\n const urlInstance = new URL(url, baseUrl());\n for (let i = 0; i < params.params.length; i++) {\n const [key, value] = params.params[i];\n if (value !== undefined) {\n urlInstance.searchParams.append(key, internal.unwrap(value));\n }\n }\n if (hash !== undefined) {\n urlInstance.hash = hash;\n }\n return urlInstance;\n },\n catch: cause => new UrlError({\n cause\n })\n});\nconst baseUrl = () => {\n if (\"location\" in globalThis && globalThis.location !== undefined && globalThis.location.origin !== undefined && globalThis.location.pathname !== undefined) {\n const base = location.origin + location.pathname;\n try {\n return new URL(base).href;\n } catch {\n return undefined;\n }\n }\n return undefined;\n};\n/**\n * Parses a URL string safely into a `URL` object, returning a `Result` type for\n * error handling.\n *\n * **Details**\n *\n * This function converts a string into a `URL` object, enabling safe URL\n * parsing with built-in error handling. If the string is invalid or fails to\n * parse, this function does not throw an error; instead, it wraps the error in\n * a `IllegalArgumentError` and returns it as the `Failure` value of an\n * `Result`. The `Success` value contains the successfully parsed `URL`.\n *\n * An optional `base` parameter can be provided to resolve relative URLs. If\n * specified, the function interprets the input `url` as relative to this\n * `base`. This is especially useful when dealing with URLs that might not be\n * fully qualified.\n *\n * **Example** (Parsing absolute and relative URLs)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n * import { Url } from \"effect/http\"\n *\n * // Parse an absolute URL\n * //\n * // ┌─── Result<URL, IllegalArgumentError>\n * // ▼\n * const parsed = Url.fromString(\"https://example.com/path\")\n *\n * Result.map(parsed, (url) => url.toString()) // => Result.succeed(\"https://example.com/path\")\n *\n * // Parse a relative URL with a base\n * const relativeParsed = Url.fromString(\"/relative-path\", \"https://example.com\")\n *\n * Result.map(relativeParsed, (url) => url.toString()) // => Result.succeed(\"https://example.com/relative-path\")\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromString = (url, base) => Result.try({\n try: () => new URL(url, base),\n catch: () => new Cause.IllegalArgumentError(`Invalid URL: \"${url}\"${base !== undefined ? ` with base \"${base}\"` : \"\"}`)\n});\n/**\n * Updates a cloned `URL` with a callback, allowing multiple changes at once.\n *\n * **Example** (Mutating URL credentials)\n *\n * ```ts import.meta.vitest\n * import { Url } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com\")\n *\n * const mutatedUrl = Url.mutate(myUrl, (url) => {\n * url.username = \"user\"\n * url.password = \"pass\"\n * })\n *\n * mutatedUrl.toString() // => \"https://user:pass@example.com/\"\n * ```\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const mutate = /*#__PURE__*/dual(2, (self, f) => {\n const copy = new URL(self);\n f(copy);\n return copy;\n});\n/**\n * @internal\n */\nconst immutableURLSetter = property => dual(2, (url, value) => mutate(url, url => {\n url[property] = value;\n}));\n/**\n * Updates the hash fragment of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHash = /*#__PURE__*/immutableURLSetter(\"hash\");\n/**\n * Updates the host (domain and port) of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHost = /*#__PURE__*/immutableURLSetter(\"host\");\n/**\n * Updates the domain of the URL without modifying the port.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHostname = /*#__PURE__*/immutableURLSetter(\"hostname\");\n/**\n * Replaces the entire URL string.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHref = /*#__PURE__*/immutableURLSetter(\"href\");\n/**\n * Updates the password used for authentication.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPassword = /*#__PURE__*/dual(2, (url, password) => mutate(url, url => {\n url.password = typeof password === \"string\" ? password : Redacted.value(password);\n}));\n/**\n * Updates the path of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPathname = /*#__PURE__*/immutableURLSetter(\"pathname\");\n/**\n * Updates the port of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPort = /*#__PURE__*/immutableURLSetter(\"port\");\n/**\n * Updates the protocol (e.g., `http`, `https`).\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setProtocol = /*#__PURE__*/immutableURLSetter(\"protocol\");\n/**\n * Updates the query string of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setSearch = /*#__PURE__*/immutableURLSetter(\"search\");\n/**\n * Updates the username used for authentication.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setUsername = /*#__PURE__*/immutableURLSetter(\"username\");\n/**\n * Updates the query parameters of a URL.\n *\n * **Details**\n *\n * This function allows you to set or replace the query parameters of a `URL`\n * object using the provided `UrlParams`. It creates a new `URL` object with the\n * updated parameters, leaving the original object unchanged.\n *\n * **Example** (Replacing query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * // Write parameters\n * const updatedUrl = Url.setUrlParams(\n * myUrl,\n * UrlParams.fromInput([[\"key\", \"value\"]])\n * )\n *\n * updatedUrl.toString() // => \"https://example.com/?key=value\"\n * ```\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setUrlParams = /*#__PURE__*/dual(2, (url, urlParams) => mutate(url, url => {\n url.search = UrlParams.toString(UrlParams.fromInput(urlParams));\n}));\n/**\n * Retrieves the query parameters from a URL.\n *\n * **Details**\n *\n * This function extracts the query parameters from a `URL` object and returns\n * them as `UrlParams`. The resulting structure can be easily manipulated or\n * inspected.\n *\n * **Example** (Reading query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * // Read parameters\n * const params = Url.urlParams(myUrl)\n *\n * UrlParams.toString(params) // => \"foo=bar\"\n * ```\n *\n * @stability unstable\n * @category getters\n * @since 4.0.0\n */\nexport const urlParams = url => UrlParams.fromInput(url.searchParams);\n/**\n * Reads the query parameters of a URL, modifies them, and updates the URL.\n *\n * **Details**\n *\n * This function provides a functional way to interact with query parameters by\n * reading the current parameters, applying a transformation function, and then\n * writing the updated parameters back to the URL. It returns a new `URL` object\n * with the modified parameters, ensuring immutability.\n *\n * **Example** (Modifying query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * const changedUrl = Url.modifyUrlParams(myUrl, UrlParams.append(\"key\", \"value\"))\n *\n * changedUrl.toString() // => \"https://example.com/?foo=bar&key=value\"\n * ```\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const modifyUrlParams = /*#__PURE__*/dual(2, (url, f) => mutate(url, url => {\n const params = f(UrlParams.fromInput(url.searchParams));\n url.search = UrlParams.toString(params);\n}));\n//# sourceMappingURL=Url.js.map","import * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Base64 from \"../encoding/Base64.js\";\nimport { dual } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport { stringOrRedacted } from \"../internal/redacted.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { redact } from \"../Redactable.js\";\nimport * as Result from \"../Result.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport { hasBody } from \"./HttpMethod.js\";\nimport * as compression from \"./internal/compressionBody.js\";\nimport * as bodyInternal from \"./internal/httpBody.js\";\nimport * as Url from \"./Url.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpClientRequest\";\n/**\n * Returns `true` when a value is an `HttpClientRequest`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpClientRequest = u => hasProperty(u, TypeId);\nconst Proto = {\n [TypeId]: TypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"HttpClientRequest\",\n method: this.method,\n url: UrlParams.redactUrl(this.url),\n urlParams: this.urlParams,\n hash: this.hash,\n headers: redact(this.headers),\n body: this.body.toJSON()\n };\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Constructs an `HttpClientRequest` from fully normalized request components.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport function makeWith(method, url, urlParams, hash, headers, body) {\n const self = Object.create(Proto);\n self.method = method;\n self.url = url;\n self.urlParams = urlParams;\n self.hash = hash;\n self.headers = headers;\n self.body = body;\n return self;\n}\n/**\n * An empty `GET` request with no URL, query parameters, hash, headers, or body.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/makeWith(\"GET\", \"\", UrlParams.empty, /*#__PURE__*/Option.none(), Headers.empty, HttpBody.empty);\n/**\n * Creates a request constructor for the specified HTTP method.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = method => (url, options) => modify(empty, {\n method,\n url,\n ...(options ?? undefined)\n});\n/**\n * Creates a `GET` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/make(\"GET\");\n/**\n * Creates a `QUERY` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const query = /*#__PURE__*/make(\"QUERY\");\n/**\n * Creates a `POST` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const post = /*#__PURE__*/make(\"POST\");\n/**\n * Creates a `PATCH` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const patch = /*#__PURE__*/make(\"PATCH\");\n/**\n * Creates a `PUT` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const put = /*#__PURE__*/make(\"PUT\");\nconst del = /*#__PURE__*/make(\"DELETE\");\n/**\n * @stability unstable\n */\nexport {\n/**\n * Creates a `DELETE` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\ndel as delete };\n/**\n * Creates a `HEAD` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const head = /*#__PURE__*/make(\"HEAD\");\n/**\n * Creates an `OPTIONS` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const options = /*#__PURE__*/make(\"OPTIONS\");\n/**\n * Creates a `TRACE` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const trace = /*#__PURE__*/make(\"TRACE\");\n/**\n * Applies request options to an `HttpClientRequest`, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, options) => {\n let result = self;\n if (options.method) {\n result = setMethod(result, options.method);\n }\n if (options.url) {\n result = setUrl(result, options.url);\n }\n if (options.headers) {\n result = setHeaders(result, options.headers);\n }\n if (options.urlParams) {\n result = setUrlParams(result, options.urlParams);\n }\n if (options.hash) {\n result = setHash(result, options.hash);\n }\n if (options.body) {\n result = setBody(result, options.body);\n }\n if (options.accept) {\n result = accept(result, options.accept);\n }\n if (options.acceptJson) {\n result = acceptJson(result);\n }\n return result;\n});\n/**\n * Sets the HTTP method on a request, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setMethod = /*#__PURE__*/dual(2, (self, method) => makeWith(method, self.url, self.urlParams, self.hash, self.headers, self.body));\n/**\n * Sets a single request header, replacing any existing value for that header.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeader = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(self.headers, key, value), self.body));\n/**\n * Adds a value to a request header, keeping any existing value.\n *\n * **Details**\n *\n * An existing value is joined with the new one by `\", \"`, and an empty value\n * leaves the request unchanged.\n *\n * @see {@link setHeader} to replace a header value\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.6\n */\nexport const appendHeader = /*#__PURE__*/dual(3, (self, key, value) => value === \"\" ? self : updateHeaders(self, Headers.append(key, value)));\n/**\n * Sets multiple request headers from an input collection, replacing existing values with matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeaders = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.setAll(self.headers, input), self.body));\n/**\n * Transforms the request headers with the provided function, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const updateHeaders = /*#__PURE__*/dual(2, (self, f) => makeWith(self.method, self.url, self.urlParams, self.hash, f(self.headers), self.body));\n/**\n * Removes a single request header by name, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const removeHeader = /*#__PURE__*/dual(2, (self, key) => updateHeaders(self, Headers.remove(key)));\n/**\n * Sets the `Authorization` header using HTTP Basic authentication credentials,\n * encoded as UTF-8 before base64 encoding.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const basicAuth = /*#__PURE__*/dual(3, (self, username, password) => setHeader(self, \"Authorization\", `Basic ${Base64.encode(`${stringOrRedacted(username)}:${stringOrRedacted(password)}`)}`));\n/**\n * Sets the `Authorization` header using a bearer token.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bearerToken = /*#__PURE__*/dual(2, (self, token) => setHeader(self, \"Authorization\", `Bearer ${stringOrRedacted(token)}`));\n/**\n * Sets the `Accept` header to the specified media type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const accept = /*#__PURE__*/dual(2, (self, mediaType) => setHeader(self, \"Accept\", mediaType));\n/**\n * Sets the `Accept` header to `application/json`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const acceptJson = /*#__PURE__*/accept(\"application/json\");\n/**\n * Asks the server to switch the connection to another protocol by setting the\n * `Connection: Upgrade` and `Upgrade` headers.\n *\n * **When to use**\n *\n * Use to switch an HTTP/1.1 connection to a raw byte stream, such as Docker's\n * `Upgrade: tcp` for container attach. For WebSocket, use `Socket.makeWebSocket`.\n *\n * **Details**\n *\n * The request is otherwise ordinary, so client transforms such as base URLs,\n * authentication, and tracing apply to it. When the server answers `101\n * Switching Protocols`, `HttpClientResponse.upgrade` hands over the\n * connection as a `Socket`. Any other response is read as usual.\n *\n * **Example** (Attaching to a Docker container)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpClient, HttpClientRequest } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = yield* HttpClient.HttpClient\n * const response = yield* client.execute(\n * HttpClientRequest.post(\"/containers/abc/attach?stream=1&stdout=1\").pipe(\n * HttpClientRequest.upgrade(\"tcp\")\n * )\n * )\n * const socket = yield* response.upgrade\n * const reader = yield* socket.reader\n * return yield* reader.pull\n * })\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.6\n */\nexport const upgrade = /*#__PURE__*/dual(2, (self, protocol) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(Headers.set(self.headers, \"connection\", \"Upgrade\"), \"upgrade\", protocol), self.body));\n/**\n * Sets the request URL. When given a `URL`, its search parameters and hash are extracted into the request's structured fields.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrl = /*#__PURE__*/dual(2, (self, url) => {\n if (typeof url === \"string\") {\n return makeWith(self.method, url, self.urlParams, self.hash, self.headers, self.body);\n }\n const clone = new URL(url.toString());\n const urlParams = UrlParams.fromInput(clone.searchParams);\n const hash = Option.fromNullishOr(clone.hash === \"\" ? undefined : clone.hash.slice(1));\n clone.search = \"\";\n clone.hash = \"\";\n return makeWith(self.method, clone.toString(), urlParams, hash, self.headers, self.body);\n});\n/**\n * Prepends a URL segment to the request URL, inserting or trimming one slash as needed.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const prependUrl = /*#__PURE__*/dual(2, (self, path) => {\n if (path === \"\") return self;\n return makeWith(self.method, joinSegments(path, self.url), self.urlParams, self.hash, self.headers, self.body);\n});\n/**\n * Appends a URL segment to the request URL, inserting or trimming one slash as needed.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrl = /*#__PURE__*/dual(2, (self, path) => {\n if (path === \"\") return self;\n return makeWith(self.method, joinSegments(self.url, path), self.urlParams, self.hash, self.headers, self.body);\n});\nconst joinSegments = (first, second) => {\n const endsWithSlash = first.endsWith(\"/\");\n const startsWithSlash = second.startsWith(\"/\");\n const needsTrim = endsWithSlash && startsWithSlash;\n const needsSlash = !endsWithSlash && !startsWithSlash;\n return needsTrim ? first + second.slice(1) : needsSlash ? first + \"/\" + second : first + second;\n};\n/**\n * Updates the request URL by applying a function to the current URL string.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const updateUrl = /*#__PURE__*/dual(2, (self, f) => makeWith(self.method, f(self.url), self.urlParams, self.hash, self.headers, self.body));\n/**\n * Sets one query parameter, replacing existing values for that parameter name.\n *\n * **Details**\n *\n * A `Redacted` value is sent unwrapped and stays redacted in inspection, errors and spans.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrlParam = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, UrlParams.set(self.urlParams, key, value), self.hash, self.headers, self.body));\n/**\n * Sets query parameters from an input collection, replacing existing values for matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrlParams = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, UrlParams.setAll(self.urlParams, input), self.hash, self.headers, self.body));\n/**\n * Appends one query parameter value without removing existing values for the same name.\n *\n * **Details**\n *\n * A `Redacted` value is sent unwrapped and stays redacted in inspection, errors and spans.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrlParam = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, UrlParams.append(self.urlParams, key, value), self.hash, self.headers, self.body));\n/**\n * Appends query parameters from an input collection without removing existing values for matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrlParams = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, UrlParams.appendAll(self.urlParams, input), self.hash, self.headers, self.body));\n/**\n * Sets the URL fragment on a request without the leading `#`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHash = /*#__PURE__*/dual(2, (self, hash) => makeWith(self.method, self.url, self.urlParams, Option.some(hash), self.headers, self.body));\n/**\n * Removes the URL fragment from a request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const removeHash = self => makeWith(self.method, self.url, self.urlParams, Option.none(), self.headers, self.body);\n/**\n * Sets the request body and updates `Content-Type` and `Content-Length` headers from the body metadata when available.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setBody = /*#__PURE__*/dual(2, (self, body) => {\n return makeWith(self.method, self.url, self.urlParams, self.hash, bodyInternal.updateHeaders(self.headers, body), body);\n});\n/**\n * Compresses a request body using Web `CompressionStream` and sets `Content-Encoding`.\n *\n * **Details**\n *\n * Byte-array bodies (including text, JSON, and URL-encoded bodies) are compressed\n * into a new `Uint8Array` body, preserving the content type and updating\n * `Content-Length`. The compressed body does not retain the original lazy text.\n * Stream bodies are compressed lazily and have their content length removed.\n * They still require a client runtime that supports streaming request bodies\n * (stable Safari and Firefox do not; see `FetchHttpClient.StreamBodyFallback`).\n *\n * Returns the original request unchanged for empty, FormData, and raw bodies,\n * bodies with a known length below `options.minSize`, or requests with any\n * existing `Content-Encoding` header, including `identity`. Unknown-length\n * streams are always compressed. The default minimum is 1024 bytes because\n * gzip can make very small bodies larger.\n *\n * Requires `CompressionStream` (available in browsers, Node 18+, Bun, and Deno).\n * There is no typed error channel: byte compression failures are defects;\n * stream failures surface when the body is sent.\n *\n * To compress every request, use\n * `HttpClient.mapRequestEffect(HttpClientRequest.compressBody(\"gzip\"))`.\n * `HttpClient.retryTransient` re-runs preprocessing, so this recompresses on\n * every retry. For large bodies, compress once before calling `client.execute`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const compressBody = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, algorithm, options) => {\n if (self.headers[\"content-encoding\"] !== undefined) {\n return Effect.succeed(self);\n }\n return Effect.map(compression.compressBody(self.body, algorithm, options), body => body === self.body ? self : makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(bodyInternal.updateContentLength(self.headers, body), \"content-encoding\", algorithm), body));\n});\n/**\n * Sets a `Uint8Array` request body with an optional content type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyUint8Array = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, contentType) => setBody(self, HttpBody.uint8Array(body, contentType)));\n/**\n * Sets a text request body with an optional content type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyText = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, contentType) => setBody(self, HttpBody.text(body, contentType)));\n/**\n * Encodes a value as a JSON request body and sets it on the request, failing with `HttpBodyError` if encoding fails.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyJson = /*#__PURE__*/dual(2, (self, body) => Effect.map(HttpBody.json(body), body => setBody(self, body)));\n/**\n * Sets a JSON request body using unsafe JSON encoding.\n *\n * **When to use**\n *\n * Use when the request body is known to be JSON-serializable and a synchronous\n * `HttpClientRequest` result is needed.\n *\n * **Gotchas**\n *\n * JSON encoding may throw instead of failing in the Effect error channel.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyJsonUnsafe = /*#__PURE__*/dual(2, (self, body) => setBody(self, HttpBody.jsonUnsafe(body)));\n/**\n * Creates a schema-based JSON body encoder that sets the encoded value on a request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const encode = HttpBody.jsonSchema(schema, options);\n return dual(2, (self, body) => Effect.map(encode(body), body => setBody(self, body)));\n};\n/**\n * Sets an `application/x-www-form-urlencoded` request body from URL parameter input.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyUrlParams = /*#__PURE__*/dual(2, (self, input) => setBody(self, HttpBody.urlParams(UrlParams.fromInput(input))));\n/**\n * Sets a `FormData` request body.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFormData = /*#__PURE__*/dual(2, (self, body) => setBody(self, HttpBody.formData(body)));\n/**\n * Creates a `FormData` request body from record-style entries and sets it on the request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFormDataRecord = /*#__PURE__*/dual(2, (self, entries) => setBody(self, HttpBody.formDataRecord(entries)));\n/**\n * Sets a streaming `Uint8Array` request body with optional content type and content length metadata.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyStream = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, options) => setBody(self, HttpBody.stream(body, options?.contentType, options?.contentLength)));\n/**\n * Creates a file-backed request body from a filesystem path and sets it on the request.\n *\n * **Details**\n *\n * Uses {@link HttpBody.file} to validate ranges lazily and calculate the EOF-clamped content length with exact\n * bigint arithmetic. Invalid range inputs or a final length above `Number.MAX_SAFE_INTEGER` fail with\n * `PlatformError` / `BadArgument`. Larger sizes, offsets, and byte counts are valid when the final length is\n * representable as a safe integer. The request's Content-Length header contains that exact length.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFile = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, path, options) => Effect.map(HttpBody.file(path, options), body => setBody(self, body)));\n/**\n * Builds a `URL` from the request URL, query parameters, and hash, returning `Option.none()` if the URL is invalid.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport function toUrl(self) {\n const r = Url.make(self.url, self.urlParams, Option.getOrUndefined(self.hash));\n if (Result.isSuccess(r)) {\n return Option.some(r.success);\n }\n return Option.none();\n}\n/**\n * Converts a Web `Request` into an `HttpClientRequest`, preserving method, URL, headers, and supported request bodies.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const fromWeb = request => {\n const method = request.method.toUpperCase();\n return modify(makeWith(method, \"\", UrlParams.empty, Option.none(), Headers.empty, HttpBody.empty), {\n url: new URL(request.url),\n headers: request.headers,\n body: fromWebBody(request, method)\n });\n};\nconst fromWebBody = (request, method) => {\n if (!hasBody(method) || request.body === null) {\n return HttpBody.empty;\n }\n return HttpBody.raw(request.body, {\n contentType: request.headers.get(\"content-type\") ?? undefined,\n contentLength: bodyInternal.parseContentLength(request.headers.get(\"content-length\"))\n });\n};\n/**\n * Converts an `HttpClientRequest` safely to a Web `Request` as a `Result`, failing when the request URL is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWebResult = (self, options) => {\n const url = Url.make(self.url, self.urlParams, Option.getOrUndefined(self.hash));\n if (Result.isFailure(url)) {\n return Result.fail(url.failure);\n }\n const requestInit = {\n method: self.method,\n headers: self.headers\n };\n if (options?.signal) {\n requestInit.signal = options.signal;\n }\n if (hasBody(self.method)) {\n switch (self.body._tag) {\n case \"Empty\":\n {\n break;\n }\n case \"Raw\":\n {\n requestInit.body = self.body.body;\n if (isReadableStream(self.body.body)) {\n ;\n requestInit.duplex = \"half\";\n }\n break;\n }\n case \"Uint8Array\":\n {\n requestInit.body = self.body.body;\n break;\n }\n case \"FormData\":\n {\n requestInit.body = self.body.formData;\n break;\n }\n case \"Stream\":\n {\n requestInit.body = Stream.toReadableStreamWith(self.body.stream, options?.context ?? Context.empty());\n requestInit.duplex = \"half\";\n break;\n }\n }\n }\n return Result.try({\n try: () => new Request(url.success, requestInit),\n catch: cause => new Url.UrlError({\n cause\n })\n });\n};\nconst isReadableStream = u => typeof ReadableStream !== \"undefined\" && u instanceof ReadableStream;\n/**\n * Converts an `HttpClientRequest` to a Web `Request`, failing with `UrlError` when the request URL is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = (self, options) => Effect.contextWith(context => Effect.fromResult(toWebResult(self, {\n context: context,\n signal: options?.signal\n})));\n//# sourceMappingURL=HttpClientRequest.js.map","import * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { redact } from \"../Redactable.js\";\nimport * as Schema from \"../Schema.js\";\n/**\n * Type identifier for `HttpIncomingMessage` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpIncomingMessage\";\n/**\n * Returns `true` when a value is an `HttpIncomingMessage`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpIncomingMessage = u => hasProperty(u, TypeId);\n/**\n * Creates a decoder that reads an incoming message's JSON body and decodes it with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema));\n const decodeJson = options?.reviver === undefined ? undefined : Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema), options));\n return self => decodeJson === undefined ? Effect.flatMap(self.json, u => decode(u, options)) : Effect.flatMap(self.text, body => body === \"\" ? Effect.flatMap(self.json, u => decode(u, options)) : decodeJson(body, options));\n};\n/**\n * Creates a decoder that reads an incoming message's URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyUrlParams = (schema, options) => {\n const decode = Schema.RecordFromUrlParams.pipe(Schema.decodeTo(schema), Schema.decodeEffect);\n return self => Effect.flatMap(self.urlParamsBody, u => decode(u, options));\n};\n/**\n * Creates a decoder that validates and decodes an incoming message's headers with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaHeaders = (schema, options) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return self => decode(self.headers, options);\n};\n/**\n * Context reference for the optional maximum size allowed when reading an incoming message body.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const MaxBodySize = /*#__PURE__*/Context.Reference(\"effect/http/HttpIncomingMessage/MaxBodySize\", {\n defaultValue: () => undefined\n});\n/**\n * Builds an inspectable object for an incoming message and redacts headers.\n * The body is left unread.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const inspect = (self, that) => {\n return {\n ...that,\n headers: redact(self.headers),\n remoteAddress: self.remoteAddress\n };\n};\n//# sourceMappingURL=HttpIncomingMessage.js.map","/**\n * Returns the original Web `Response` of a fetch-backed client response.\n * Wrappers forward it to the response they wrap.\n *\n * @internal\n */\nexport const WebSourceSymbol = \"~effect/http/HttpClientResponse/WebSource\";\n/**\n * @internal\n */\nexport const getWebSource = self => self[WebSourceSymbol]?.();\n//# sourceMappingURL=webResponse.js.map","/**\n * Represents responses returned by the Effect HTTP client.\n *\n * An `HttpClientResponse` keeps the original request together with the response\n * status, headers, cookies, and body accessors from the shared incoming-message\n * model. This module includes constructors, schema-based decoders, helpers for\n * streaming response bodies, and utilities for matching or filtering by HTTP\n * status.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"../Effect.js\";\nimport { dual } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as Error from \"./HttpClientError.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as internalUrlParams from \"./internal/urlParams.js\";\nimport { getWebSource, WebSourceSymbol } from \"./internal/webResponse.js\";\nimport * as UrlParams from \"./UrlParams.js\";\n/**\n * @stability unstable\n */\nexport {\n/**\n * Creates a decoder that reads a response JSON body and decodes it with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyJson,\n/**\n * Creates a decoder that reads response URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyUrlParams,\n/**\n * Creates a decoder that validates and decodes response headers with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaHeaders } from \"./HttpIncomingMessage.js\";\n/**\n * Type identifier for `HttpClientResponse` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpClientResponse\";\n/**\n * Wraps a Web `Response` and its original `HttpClientRequest` as an `HttpClientResponse`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWeb = (request, source) => new WebHttpClientResponse(request, source);\n/**\n * Returns the original Web `Response` of a fetch-backed `HttpClientResponse`.\n *\n * **When to use**\n *\n * Use to hand a response body to a Web API without copying it, such as\n * writing a fetched file to Cloudflare R2. The original body keeps runtime\n * capabilities, such as workerd's known length, that a stream converted from\n * `stream` does not.\n *\n * **Details**\n *\n * Returns `Some` for responses created with `fromWeb`, which includes every\n * response from `FetchHttpClient`, and `None` for other backends.\n *\n * Calling `toWeb` hands the body over: the response is no longer aborted when\n * the `HttpClientResponse` is garbage collected, so read or cancel the body\n * through the returned `Response`.\n *\n * **Gotchas**\n *\n * The body can be read once. After converting, read it from the returned\n * `Response`, not from the `HttpClientResponse`.\n *\n * After the hand-off, Effect aborts the request only when the scope of\n * `HttpClient.withScope` closes. When the request streams its body, finishing\n * or cancelling the returned body does not stop the upload; execute the\n * request with `HttpClient.withScope` and close the scope to stop it.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = self => Option.fromUndefinedOr(getWebSource(self));\n/**\n * Creates a decoder for a response's status, headers, and JSON body using the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema), options);\n const decodeBody = HttpIncomingMessage.schemaBodyJson(Schema.Unknown, options);\n return self => Effect.flatMap(decodeBody(self), body => decode({\n status: self.status,\n headers: self.headers,\n body: body\n }));\n};\n/**\n * Creates a decoder for a response's status and headers without reading a response body.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaNoBody = (schema, options) => {\n const decode = Schema.decodeEffect(schema, options);\n return self => decode({\n status: self.status,\n headers: self.headers\n });\n};\n/**\n * Converts an effect producing an `HttpClientResponse` into a stream of response body bytes.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const stream = effect => Stream.unwrap(Effect.map(effect, self => self.stream));\n/**\n * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`.\n *\n * @stability unstable\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchStatus = /*#__PURE__*/dual(2, (self, cases) => {\n const status = self.status;\n if (cases[status]) {\n return cases[status](self);\n } else if (status >= 200 && status < 300 && cases[\"2xx\"]) {\n return cases[\"2xx\"](self);\n } else if (status >= 300 && status < 400 && cases[\"3xx\"]) {\n return cases[\"3xx\"](self);\n } else if (status >= 400 && status < 500 && cases[\"4xx\"]) {\n return cases[\"4xx\"](self);\n } else if (status >= 500 && status < 600 && cases[\"5xx\"]) {\n return cases[\"5xx\"](self);\n }\n return cases.orElse(self);\n});\n/**\n * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatus = /*#__PURE__*/dual(2, (self, f) => Effect.suspend(() => f(self.status) ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"invalid status code\"\n })\n}))));\n/**\n * Succeeds with the response only when its status is in the 2xx range, otherwise fails with `HttpClientError`.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatusOk = self => self.status >= 200 && self.status < 300 ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"non 2xx status code\"\n })\n}));\n/**\n * Returns the links of the response's `Link` header with absolute targets.\n *\n * **Details**\n *\n * Each target is resolved against the response URL, which is the final URL\n * after redirects, so `target` holds an absolute href. Links whose target does\n * not resolve are dropped. A response without a `Link` header gives `[]`.\n *\n * **Gotchas**\n *\n * Links with an `anchor` parameter are dropped, because they describe a\n * resource other than this response (RFC 8288 section 3.2). Parse the raw header\n * with `Headers.parseLink` to read them.\n *\n * @see {@link link} to look up a single link by relation type\n *\n * @stability unstable\n * @category accessors\n * @since 4.1.6\n */\nexport const links = self => {\n const header = self.headers.link;\n if (header === undefined) return [];\n const base = self.url || undefined;\n const out = [];\n for (const link of Headers.parseLink(header)) {\n if (Object.hasOwn(link.params, \"anchor\")) continue;\n const url = resolveUrl(link.target, base);\n if (url !== undefined) out.push({\n ...link,\n target: url.href\n });\n }\n return out;\n};\nconst resolveUrl = (target, base) => {\n try {\n return new URL(target, base);\n } catch {\n return undefined;\n }\n};\n/**\n * Returns the URL of the first link in the response's `Link` header with the\n * given relation type.\n *\n * **When to use**\n *\n * Use to follow pagination links such as `next` with `Stream.paginate`.\n *\n * **Details**\n *\n * The relation type is compared case-insensitively, and the URL is resolved\n * against the response URL. Returns `Option.none()` when no link matches.\n * Links are read as by {@link links}, so links with an `anchor` parameter\n * never match.\n *\n * **Example** (Reading the next page link)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { HttpClientRequest, HttpClientResponse } from \"effect/http\"\n *\n * const response = HttpClientResponse.fromWeb(\n * HttpClientRequest.get(\"https://example.com/items\"),\n * new Response(null, { headers: { link: '</items?page=2>; rel=\"next\"' } })\n * )\n *\n * Option.map(HttpClientResponse.link(response, \"next\"), (url) => url.href) // => Option.some(\"https://example.com/items?page=2\")\n * ```\n *\n * @see {@link links} to read every link\n *\n * @stability unstable\n * @category accessors\n * @since 4.1.6\n */\nexport const link = /*#__PURE__*/dual(2, (self, rel) => {\n const type = rel.toLowerCase();\n const found = links(self).find(link => link.rel.includes(type));\n return found === undefined ? Option.none() : Option.some(new URL(found.target));\n});\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nclass WebHttpClientResponse extends Inspectable.Class {\n [HttpIncomingMessage.TypeId];\n [TypeId];\n request;\n source;\n constructor(request, source) {\n super();\n this.request = request;\n this.source = source;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this[TypeId] = TypeId;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpClientResponse\",\n request: this.request.toJSON(),\n status: this.status\n });\n }\n get status() {\n return this.source.status;\n }\n get url() {\n if (this.source.url) return this.source.url.split(\"#\")[0];\n const url = HttpClientRequest.toUrl(this.request);\n if (Option.isNone(url)) return \"\";\n url.value.hash = \"\";\n return url.value.href;\n }\n cachedHeaders;\n get headers() {\n return this.cachedHeaders ??= Headers.fromInput(this.source.headers);\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n // React Native's Headers does not implement getSetCookie, and it never\n // exposes Set-Cookie to JavaScript anyway.\n return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie?.() ?? []);\n }\n get remoteAddress() {\n return Option.none();\n }\n [WebSourceSymbol]() {\n return this.source;\n }\n get stream() {\n return this.source.body ? Stream.fromReadableStream({\n evaluate: () => this.source.body,\n onError: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }) : Stream.fail(new Error.HttpClientError({\n reason: new Error.EmptyBodyError({\n request: this.request,\n response: this,\n description: \"can not create stream from empty body\"\n })\n }));\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n textBody;\n get text() {\n return this.textBody ??= Effect.map(this.arrayBuffer, _ => new TextDecoder().decode(_));\n }\n get urlParamsBody() {\n return Effect.flatMap(this.arrayBuffer, bytes => Effect.try({\n try: () => UrlParams.fromInput(internalUrlParams.fromBody(bytes)),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n formDataBody;\n get formData() {\n return this.formDataBody ??= Effect.tryPromise({\n try: () => this.source.formData(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n }\n arrayBufferBody;\n get arrayBuffer() {\n if (this.arrayBufferBody) {\n return this.arrayBufferBody;\n }\n this.arrayBufferBody = Effect.tryPromise({\n try: () => this.source.arrayBuffer(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n return this.arrayBufferBody;\n }\n get upgrade() {\n return Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n request: this.request,\n response: this,\n description: \"fetch cannot hand over the connection of an HTTP upgrade\"\n })\n }));\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\n//# sourceMappingURL=HttpClientResponse.js.map","/**\n * HTTP propagation helpers for trace context and W3C baggage.\n *\n * This module converts Effect `Tracer.Span` values into outbound trace headers\n * and decodes inbound propagation headers into `Tracer.ExternalSpan` parents.\n * HTTP clients use it to continue the current span across outgoing requests, and\n * server middleware uses it to parent request spans from upstream services.\n *\n * Baggage propagation is opt-in: `HttpMiddleware.baggage` populates\n * `CurrentBaggage` and `HttpClient.withBaggage` forwards it.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Option from \"../Option.js\";\nimport * as Str from \"../String.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Headers from \"./Headers.js\";\n/**\n * Encodes a span into HTTP trace propagation headers.\n *\n * **Details**\n *\n * The generated headers include both compact B3 (`b3`) and W3C `traceparent`\n * formats.\n *\n * @stability unstable\n * @category encoding\n * @since 4.0.0\n */\nexport const toHeaders = span => Headers.fromRecordUnsafe({\n b3: `${span.traceId}-${span.spanId}-${span.sampled ? \"1\" : \"0\"}${Option.match(span.parent, {\n onNone: () => \"\",\n onSome: parent => `-${parent.spanId}`\n })}`,\n traceparent: `00-${span.traceId.padStart(32, \"0\")}-${span.spanId}-${span.sampled ? \"01\" : \"00\"}`\n});\n/**\n * Decodes an external span safely from HTTP trace propagation headers.\n *\n * **Details**\n *\n * W3C `traceparent` is tried first, followed by compact B3 (`b3`) and then\n * multi-header B3 (`x-b3-*`).\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const fromHeaders = headers => {\n let span = w3c(headers);\n if (Option.isSome(span)) {\n return span;\n }\n span = b3(headers);\n if (Option.isSome(span)) {\n return span;\n }\n return xb3(headers);\n};\n/**\n * Decodes an external span safely from the compact B3 `b3` header.\n *\n * **Details**\n *\n * Returns `Option.none` when the header is missing or does not contain trace and\n * span identifiers.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const b3 = headers => {\n if (!(\"b3\" in headers)) {\n return Option.none();\n }\n const parts = headers[\"b3\"].split(\"-\");\n if (parts.length < 2 || isB3Ids(parts[0], parts[1]) === false) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: parts[0],\n spanId: parts[1],\n sampled: parts[2] ? parts[2] === \"1\" || parts[2] === \"d\" : true\n }));\n};\n/**\n * Decodes an external span safely from multi-header B3 propagation headers.\n *\n * **Details**\n *\n * The decoder reads `x-b3-traceid`, `x-b3-spanid`, and optional `x-b3-sampled`\n * and `x-b3-flags` headers. Debug flags override the sampling decision.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const xb3 = headers => {\n if (!headers[\"x-b3-traceid\"] || !headers[\"x-b3-spanid\"] || isB3Ids(headers[\"x-b3-traceid\"], headers[\"x-b3-spanid\"]) === false) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: headers[\"x-b3-traceid\"],\n spanId: headers[\"x-b3-spanid\"],\n sampled: headers[\"x-b3-flags\"] === \"1\" || (headers[\"x-b3-sampled\"] ? headers[\"x-b3-sampled\"] === \"1\" || headers[\"x-b3-sampled\"] === \"true\" : true)\n }));\n};\nconst w3cTraceId = /^[0-9a-f]{32}$/;\nconst w3cSpanId = /^[0-9a-f]{16}$/;\nconst w3cTraceFlags = /^[0-9a-f]{2}$/;\nconst b3TraceId = /^(?:[0-9a-f]{16}|[0-9a-f]{32})$/;\nconst isB3Ids = (traceId, spanId) => b3TraceId.test(traceId) && w3cSpanId.test(spanId);\n/**\n * Decodes an external span safely from the W3C `traceparent` header.\n *\n * **Details**\n *\n * Only version `00` headers with valid trace and span identifiers and trace\n * flags are accepted.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const w3c = headers => {\n if (!headers[\"traceparent\"]) {\n return Option.none();\n }\n const parts = headers[\"traceparent\"].split(\"-\");\n if (parts.length !== 4) {\n return Option.none();\n }\n const [version, traceId, spanId, flags] = parts;\n switch (version) {\n case \"00\":\n {\n if (w3cTraceId.test(traceId) === false || w3cSpanId.test(spanId) === false || w3cTraceFlags.test(flags) === false || traceId === \"00000000000000000000000000000000\" || spanId === \"0000000000000000\") {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId,\n spanId,\n sampled: (parseInt(flags, 16) & 1) === 1\n }));\n }\n default:\n {\n return Option.none();\n }\n }\n};\n/**\n * Context reference for current baggage, defaulting to an empty map.\n *\n * **Details**\n *\n * Read propagated values without adding a service requirement.\n * `HttpMiddleware.baggage` sets the reference from incoming headers;\n * `HttpClient.withBaggage` forwards it to outgoing requests.\n *\n * **Gotchas**\n *\n * Baggage is untrusted caller input. Validate it independently before using it\n * for authorization.\n *\n * **Example** (Reading baggage in a handler)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpServerResponse, HttpTraceContext } from \"effect/http\"\n *\n * const handler = Effect.gen(function*() {\n * const baggage = yield* HttpTraceContext.CurrentBaggage\n * return HttpServerResponse.text(baggage.get(\"tenant\")?.value ?? \"unknown\")\n * })\n * ```\n *\n * @see {@link baggageFromHeader} to decode a `baggage` header\n * @stability unstable\n * @category references\n * @since 4.1.8\n */\nexport const CurrentBaggage = /*#__PURE__*/Context.Reference(\"effect/http/HttpTraceContext/CurrentBaggage\", {\n defaultValue: () => new Map()\n});\n/**\n * Decodes a W3C `baggage` header into baggage entries.\n *\n * **Details**\n *\n * Skips members without `=` or a valid token key. Splits on the first `=`\n * and percent-decodes values as UTF-8, replacing invalid sequences with U+FFFD\n * and preserving stray `%` characters. The last value wins for duplicate keys.\n *\n * **Example** (Decoding a baggage header)\n *\n * ```ts import.meta.vitest\n * import { HttpTraceContext } from \"effect/http\"\n *\n * HttpTraceContext.baggageFromHeader(\"tenant=acme%20corp;ttl=30\").get(\"tenant\") // => { value: \"acme corp\", properties: \"ttl=30\" }\n * ```\n *\n * @see {@link baggageToHeader} for the inverse\n * @stability unstable\n * @category decoding\n * @since 4.1.8\n */\nexport const baggageFromHeader = header => {\n const baggage = new Map();\n for (const member of header.split(\",\")) {\n const semicolon = member.indexOf(\";\");\n const pair = semicolon === -1 ? member : member.slice(0, semicolon);\n const equals = pair.indexOf(\"=\");\n if (equals === -1) continue;\n const key = pair.slice(0, equals).trim();\n if (!token.test(key)) continue;\n const value = decodeValue(pair.slice(equals + 1).trim());\n const properties = semicolon === -1 ? \"\" : member.slice(semicolon + 1).trim();\n baggage.set(key, properties === \"\" ? {\n value\n } : {\n value,\n properties\n });\n }\n return baggage;\n};\n/**\n * Encodes baggage entries as a W3C `baggage` header value.\n *\n * **Details**\n *\n * Values are percent-encoded, with unpaired surrogates replaced by U+FFFD.\n * Properties are written unchanged unless they contain a `,` or a character\n * other than a tab or printable ASCII, in which case they are dropped and the\n * value is kept. Entries whose key is not a valid token are skipped. Returns an\n * empty string when no entries remain.\n *\n * @see {@link baggageFromHeader} for the inverse\n * @stability unstable\n * @category encoding\n * @since 4.1.8\n */\nexport const baggageToHeader = self => {\n let header = \"\";\n for (const [key, {\n properties,\n value\n }] of self) {\n if (!token.test(key)) continue;\n if (header !== \"\") header += \",\";\n header += `${key}=${encodeURIComponent(Str.toWellFormed(value))}`;\n if (properties && validProperties.test(properties)) header += `;${properties}`;\n }\n return header;\n};\n// RFC 7230 token\nconst token = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n// Allow tabs and printable ASCII except commas, which would add a member.\nconst validProperties = /^[\\t\\x20-\\x2b\\x2d-\\x7e]+$/;\nconst percentEncoded = /(?:%[0-9A-Fa-f]{2})+/g;\nconst utf8Decoder = /*#__PURE__*/new TextDecoder(\"utf-8\", {\n ignoreBOM: true\n});\n// Replace invalid UTF-8 with U+FFFD instead of throwing as decodeURIComponent does.\nconst decodeValue = value => value.replace(percentEncoded, run => utf8Decoder.decode(Uint8Array.from(run.slice(1).split(\"%\"), byte => parseInt(byte, 16))));\n//# sourceMappingURL=HttpTraceContext.js.map","import * as Headers from \"../Headers.js\";\nimport * as UrlParams from \"../UrlParams.js\";\nimport { redactClientPath } from \"./clientPath.js\";\nconst defaultPorts = {\n \"http:\": 80,\n \"https:\": 443,\n \"ws:\": 80,\n \"wss:\": 443\n};\n/**\n * Records `url.*` and `server.*` attributes with URL redaction.\n *\n * @internal\n */\nexport const addUrlAttributes = (span, url, redactedNames, path) => {\n const redactPath = url => path === undefined ? url : redactClientPath(url, path);\n const query = UrlParams.redactUrl(url.search, redactedNames).slice(1);\n span.attribute(\"url.full\", redactPath(UrlParams.redactUrl(url.href, redactedNames)));\n span.attribute(\"url.path\", redactPath(url.pathname));\n if (query !== \"\") {\n span.attribute(\"url.query\", query);\n }\n span.attribute(\"url.scheme\", url.protocol.slice(0, -1));\n if (url.hostname !== \"\") {\n // URL keeps IPv6 brackets in the hostname, but the semantic conventions do not.\n span.attribute(\"server.address\", url.hostname.startsWith(\"[\") ? url.hostname.slice(1, -1) : url.hostname);\n const port = url.port === \"\" ? defaultPorts[url.protocol] : Number(url.port);\n if (port !== undefined) {\n span.attribute(\"server.port\", port);\n }\n }\n};\n/**\n * Adds the names of `Redacted` parameters to the redacted names.\n *\n * @internal\n */\nexport const redactedNames = (urlParams, redactedNames) => {\n const keys = urlParams.params.filter(([, value]) => typeof value !== \"string\").map(([key]) => key);\n return keys.length === 0 ? redactedNames : [...redactedNames, ...new URLSearchParams(keys.map(key => [key, \"\"])).keys()];\n};\n/** @internal */\nexport const addHeaderAttributes = (span, phase, headers, filter, redactedNames) => {\n for (const name in headers) {\n if (!filter(name, phase)) continue;\n span.attribute(`http.${phase}.header.${name}`, Headers.isRedactedName(name, redactedNames) ? \"<redacted>\" : headers[name]);\n }\n};\n//# sourceMappingURL=tracing.js.map","import * as Cause from \"../Cause.js\";\nimport { Clock } from \"../Clock.js\";\nimport * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Exit from \"../Exit.js\";\nimport * as Fiber from \"../Fiber.js\";\nimport { constant, constFalse, constTrue, dual, flow, identity } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"../internal/stackTraceLimit.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Ref from \"../Ref.js\";\nimport * as References from \"../References.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport * as Error from \"./HttpClientError.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpClientResponse from \"./HttpClientResponse.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as HttpMethod from \"./HttpMethod.js\";\nimport * as TraceContext from \"./HttpTraceContext.js\";\nimport { CurrentClientPath, urlTemplate, withoutTemplate } from \"./internal/clientPath.js\";\nimport * as tracing from \"./internal/tracing.js\";\nimport { getWebSource, WebSourceSymbol } from \"./internal/webResponse.js\";\nimport * as Url from \"./Url.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpClient\";\n/**\n * Returns `true` if the provided value is an `HttpClient`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpClient = u => Predicate.hasProperty(u, TypeId);\n/**\n * Service tag for the default outgoing HTTP client service.\n *\n * **When to use**\n *\n * Use to provide the default outgoing HTTP client service used by request\n * accessors such as `execute`, `get`, and `post`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const HttpClient = /*#__PURE__*/Context.Service(\"effect/HttpClient\");\nconst accessor = method => (...args) => Effect.flatMap(HttpClient, client => client[method](...args));\n/**\n * Executes a prebuilt `HttpClientRequest` using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const execute = /*#__PURE__*/accessor(\"execute\");\n/**\n * Executes a `GET` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/accessor(\"get\");\n/**\n * Executes a `QUERY` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const query = /*#__PURE__*/accessor(\"query\");\n/**\n * Executes a `HEAD` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const head = /*#__PURE__*/accessor(\"head\");\n/**\n * Executes a `POST` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const post = /*#__PURE__*/accessor(\"post\");\n/**\n * Executes a `PATCH` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const patch = /*#__PURE__*/accessor(\"patch\");\n/**\n * Executes a `PUT` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const put = /*#__PURE__*/accessor(\"put\");\n/**\n * Executes a `DELETE` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const del = /*#__PURE__*/accessor(\"del\");\n/**\n * Executes an `OPTIONS` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const options = /*#__PURE__*/accessor(\"options\");\n/**\n * Transforms a client by wrapping the response effect for each request.\n *\n * **Details**\n *\n * The transformation receives both the response effect and the original request, allowing it to change success, error, and environment behavior.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const transform = /*#__PURE__*/dual(2, (self, f) => makeWith(Effect.flatMap(request => f(self.postprocess(Effect.succeed(request)), request)), self.preprocess));\n/**\n * Transforms a client by applying an effectful transformation to each response effect.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const transformResponse = /*#__PURE__*/dual(2, (self, f) => makeWith(request => f(self.postprocess(request)), self.preprocess));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.catch(f)));\n/**\n * @stability unstable\n */\nexport {\n/**\n * Handles all client failures with an effectful recovery function and returns a transformed client.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Handles client failures with one or more matching `_tag` values and returns a transformed client.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(3, (self, tag, f) => transformResponse(self,\n// TypeScript 7.1 does not relate the error type `Effect.catchTag` returns\n// to the `ExcludeTag` declared here, because each declares its own copy\n// of the conditional on `K`. The assertion restates the declared type.\neffect => Effect.catchTag(effect, tag, f)));\n/**\n * Handles client failures by matching their `_tag` values against a case map.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTags = /*#__PURE__*/dual(2, (self, cases) => transformResponse(self, Effect.catchTags(cases)));\n/**\n * Filters the result of a response, or runs an alternative effect if the predicate fails.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterOrElse = /*#__PURE__*/dual(3, (self, f, orElse) => transformResponse(self, Effect.filterOrElse(f, orElse)));\n/**\n * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterOrFail = /*#__PURE__*/dual(3, (self, f, orFailWith) => transformResponse(self, Effect.filterOrFail(f, orFailWith)));\n/**\n * Filters responses by HTTP status code.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatus = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.flatMap(HttpClientResponse.filterStatus(f))));\n/**\n * Filters responses that return a 2xx status code.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatusOk = /*#__PURE__*/transformResponse(/*#__PURE__*/Effect.flatMap(HttpClientResponse.filterStatusOk));\n/**\n * Constructs an `HttpClient.With` from a preprocessing function and a postprocessing function.\n *\n * **Details**\n *\n * `execute` applies preprocessing to the request and then passes the resulting request effect to postprocessing.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWith = (postprocess, preprocess) => {\n const self = Object.create(Proto);\n self.preprocess = preprocess;\n self.postprocess = postprocess;\n self.execute = function (request) {\n return postprocess(preprocess(request));\n };\n return self;\n};\nconst Proto = {\n [TypeId]: TypeId,\n pipe() {\n return pipeArguments(this, arguments);\n },\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"effect/HttpClient\"\n };\n },\n ... /*#__PURE__*/Object.fromEntries(/*#__PURE__*/HttpMethod.allShort.map(([fullMethod, method]) => [method, function (url, options) {\n return this.execute(HttpClientRequest.make(fullMethod)(url, options));\n }]))\n};\n/**\n * Constructs an `HttpClient` from a low-level request runner.\n *\n * **Details**\n *\n * The runner receives the request, resolved URL, abort signal, and current fiber. The client wrapper handles URL construction failures, tracing and propagation, header redaction, aborting the signal when the request is interrupted before a response arrives, and attaching each request to the scope of an enclosing `withScope`.\n *\n * `HttpClientError` reasons redact their URL with the `UrlParams.CurrentRedactedNames` of the fiber that executed the request, even when a callback outside that fiber creates them. The client adds those names to the errors the runner fails with and to errors built later from the response. Rendering an error then adds the names of the rendering fiber. A runner that returns one response object to several executions gives its errors the names of all of them.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = f => makeWith(effect => Effect.flatMap(effect, request => Effect.withFiber(fiber => {\n const scope = fiber.getRef(RequestScope);\n const controller = new AbortController();\n const urlParamsRedactedNames = fiber.getRef(UrlParams.CurrentRedactedNames);\n const redactedPath = fiber.getRef(CurrentClientPath);\n const urlResult = Url.make(request.url, request.urlParams, Option.getOrUndefined(request.hash));\n if (Result.isFailure(urlResult)) {\n const cause = Cause.fail(new Error.HttpClientError({\n reason: new Error.InvalidUrlError({\n request,\n cause: urlResult.failure\n })\n }));\n Error.addFailureRedactedNames(cause, urlParamsRedactedNames, redactedPath);\n return Effect.failCause(cause);\n }\n const url = urlResult.success;\n const send = request => scope === undefined ? f(request, url, controller.signal, fiber)\n // Register the abort before dispatch, so a scope that is already\n // closed aborts the signal before the transport sees it\n : Effect.flatMap(Scope.addFinalizer(scope, Effect.sync(() => controller.abort())), () => f(request, url, controller.signal, fiber));\n const exchange = (request, onResponse) => Effect.uninterruptibleMask(restore => Effect.matchCauseEffect(restore(send(request)), {\n onSuccess: response => {\n response = trackResponse(response, controller, scope !== undefined, urlParamsRedactedNames, redactedPath);\n onResponse?.(response);\n return Effect.succeed(response);\n },\n onFailure: cause => {\n if (Cause.hasInterrupts(cause)) {\n controller.abort();\n }\n Error.addFailureRedactedNames(cause, urlParamsRedactedNames, redactedPath);\n return Effect.failCause(cause);\n }\n }));\n const tracerDisabled = !fiber.getRef(References.TracerEnabled) || fiber.getRef(Tracer.DisablePropagation) || fiber.getRef(TracerDisabledWhen)(request);\n if (tracerDisabled) {\n return exchange(request);\n }\n const template = urlTemplate(request.url, redactedPath);\n return Effect.useSpan(fiber.getRef(SpanNameGenerator)(request, {\n template\n }), {\n kind: \"client\"\n }, span => {\n span.attribute(\"http.request.method\", request.method);\n if (template !== undefined) {\n span.attribute(\"url.template\", template);\n }\n const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames);\n tracing.addUrlAttributes(span, url, tracing.redactedNames(request.urlParams, urlParamsRedactedNames), redactedPath);\n const headerFilter = fiber.getRef(TracerHeaderFilter);\n tracing.addHeaderAttributes(span, \"request\", request.headers, headerFilter, redactedHeaderNames);\n request = fiber.getRef(TracerPropagationEnabled) ? HttpClientRequest.setHeaders(request, TraceContext.toHeaders(span)) : request;\n return Effect.withParentSpan(exchange(request, response => {\n span.attribute(\"http.response.status_code\", response.status);\n tracing.addHeaderAttributes(span, \"response\", response.headers, headerFilter, redactedHeaderNames);\n // OpenTelemetry marks client spans as failed for 4xx and\n // 5xx responses, while the response itself still succeeds.\n if (response.status >= 400 && response.status < 600) {\n span.attribute(\"error.type\", String(response.status));\n endSpanWithStatusError(fiber, span, request, response);\n }\n }), span, {\n captureStackTrace: false\n });\n });\n})), Effect.succeed);\nconst endSpanWithStatusError = (fiber, span, request, response) => {\n const stackTraceLimit = getStackTraceLimit();\n setStackTraceLimit(0);\n let exit;\n try {\n exit = Exit.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n request,\n response\n })\n }));\n } finally {\n setStackTraceLimit(stackTraceLimit);\n }\n span.end(fiber.getRef(References.TracerTimingEnabled) ? fiber.getRef(Clock).currentTimeNanosUnsafe() : BigInt(0), exit);\n};\n/**\n * Appends a transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequest = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.map(self.preprocess(request), f)));\n/**\n * Appends an effectful transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestEffect = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.flatMap(self.preprocess(request), f)));\n/**\n * Prepends a transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestInput = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => self.preprocess(f(request))));\n/**\n * Prepends an effectful transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestInputEffect = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.flatMap(f(request), self.preprocess)));\n/**\n * Retries the request based on a provided schedule or policy.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, policy) => transformResponse(self, Effect.retry(policy)));\n/**\n * Retries common transient errors, such as rate limiting, timeouts or network issues.\n *\n * **When to use**\n *\n * Use to focus on retrying errors, transient responses, or both.\n *\n * **Details**\n *\n * Specifying a `while` predicate allows you to consider other errors as\n * transient, and is ignored in \"response-only\" mode.\n *\n * A `Retry-After` header on a transient response, or on the response of a\n * status code error, sets the minimum delay before the next attempt. `times`\n * does not bound that wait; add `Schedule.while(retryAfterAtMost(max))` to the\n * `schedule` to stop when the server requests a delay greater than `max`.\n *\n * @see {@link retryAfterAtMost} for rejecting long server-requested delays\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const retryTransient = /*#__PURE__*/dual(2, (self, options) => {\n const isOnlySchedule = Schedule.isSchedule(options);\n const retryOn = isOnlySchedule ? \"errors-and-responses\" : options.retryOn ?? \"errors-and-responses\";\n const schedule = withRetryAfter(isOnlySchedule ? options : options.schedule ?? Schedule.forever);\n const times = isOnlySchedule ? undefined : options.times;\n return transformResponse(self, flow(retryOn === \"errors-only\" ? identity : Effect.repeat({\n schedule,\n times,\n while: isTransientResponse\n }), retryOn === \"response-only\" ? identity : Effect.retry({\n while: isOnlySchedule || options.while === undefined ? isTransientError : Predicate.or(isTransientError, options.while),\n schedule,\n times\n })));\n});\n/**\n * Fails requests that do not receive a response within the given duration.\n *\n * **When to use**\n *\n * Use to configure a timeout once on the client, for example when providing\n * the `HttpClient` service, while keeping the standard `HttpClientError` error\n * model.\n *\n * **Details**\n *\n * A timed out request is interrupted and fails with an `HttpClientError` whose\n * reason is a `TransportError` with a `Cause.TimeoutError` cause.\n * `retryTransient` treats it as transient. Interrupting a request while it\n * waits for response headers aborts the underlying transport.\n *\n * The timer starts after request preprocessing and covers everything the\n * wrapped client does to produce a response. For a plain client this ends when\n * the response headers arrive, but response middleware applied before\n * `timeout`, such as `tap` or `retryTransient`, runs inside the budget,\n * including any body reads it performs. Composition order therefore decides\n * how it interacts with retries: applying `timeout` before `retryTransient`\n * gives each attempt its own budget, while applying it after bounds the whole\n * retry loop.\n *\n * **Gotchas**\n *\n * Body reads outside the timed client are not covered, including those made\n * by response middleware applied after `timeout` and by consumers of the\n * `HttpClient` service. Apply a separate timeout to body reads such as\n * `response.json` or `response.stream` when needed.\n *\n * For a client wrapped with `withScope`, a timeout that fires after the\n * response headers arrive, such as during a body read by response middleware,\n * does not abort the transport. The connection stays open until the scope\n * closes.\n *\n * **Example** (Timing out each attempt)\n *\n * ```ts\n * import { Effect, Layer } from \"effect\"\n * import { FetchHttpClient, HttpClient } from \"effect/http\"\n *\n * const TimedHttpClient = Layer.effect(\n * HttpClient.HttpClient,\n * Effect.map(\n * HttpClient.HttpClient,\n * HttpClient.timeout(\"5 seconds\")\n * )\n * ).pipe(Layer.provide(FetchHttpClient.layer))\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.retryTransient({ times: 3 })\n * )\n * return yield* client.get(\"https://example.com\")\n * }).pipe(Effect.provide(TimedHttpClient))\n * ```\n *\n * @stability unstable\n * @category error handling\n * @since 4.1.0\n */\nexport const timeout = /*#__PURE__*/dual(2, (self, duration) => {\n const decoded = Duration.fromInputUnsafe(duration);\n const description = `timed out after ${Duration.format(decoded)}`;\n return transform(self, (effect, request) => Effect.timeoutOrElse(effect, {\n duration: decoded,\n orElse: () => Effect.fail(new Error.HttpClientError({\n reason: new Error.TransportError({\n request,\n cause: new Cause.TimeoutError(`Operation ${description}`),\n description\n })\n }))\n }));\n});\n/**\n * Applies request rate limiting using the `RateLimiter` service.\n *\n * **Details**\n *\n * It can update limits by inspecting common rate limit response headers and\n * automatically retries HTTP `429` responses (or `HttpClientError` values\n * wrapping a `429` response) by forcing the retry back through the limiter.\n * When a response reports the remaining budget, requests wait for the\n * reported reset once that budget is exhausted.\n *\n * At runtime, omitting `failsWith` leaves limiter failures as `RateLimiterError`.\n * To narrow the inferred error type, specify `\"RateLimiterError\"` or\n * `\"HttpClientError\"` explicitly. Each literal adds only its corresponding\n * error type. Errors from the wrapped client pass through unchanged.\n *\n * **Gotchas**\n *\n * Automatic HTTP `429` retries are unlimited unless `times` is specified.\n * Disabling response inspection does not disable retries; set `times` to `0`\n * to return or fail with the first `429`.\n *\n * If the mode is omitted, hidden by an options type, or union-valued, the\n * inferred type includes both errors: a type without `failsWith` can still\n * describe an object that carries it at runtime. Use\n * `satisfies WithRateLimiter.Options` to preserve an explicit literal mode.\n *\n * With `\"HttpClientError\"`, an outer `retryTransient` can retry limiter\n * failures, and `circuitBreakerClassifier` counts them as transport failures.\n *\n * @stability unstable\n * @category rate limiting\n * @since 4.0.0\n */\nexport const withRateLimiter = /*#__PURE__*/dual(2, (self, options) => {\n const mapLimiterEffect = options.failsWith === \"HttpClientError\" ? (effect, request) => Effect.mapError(effect, cause => new Error.HttpClientError({\n reason: new Error.TransportError({\n request,\n cause\n })\n })) : identity;\n const initialState = {\n initial: true,\n limit: options.limit,\n window: Duration.max(Duration.fromInputUnsafe(options.window), Duration.millis(1))\n };\n const states = new Map();\n const keyOption = options.key;\n const resolveKey = typeof keyOption === \"function\" ? keyOption : constant(keyOption);\n const tokensOption = options.tokens;\n const resolveTokens = typeof tokensOption === \"function\" ? tokensOption : constant(tokensOption ?? 1);\n const adaptiveLearningEnabled = !options.disableAdaptiveLearning;\n const headerNames = resolveRateLimiterHeaderNames(options.responseHeaders);\n const getState = key => {\n const current = states.get(key);\n if (current !== undefined) {\n return current;\n }\n states.set(key, initialState);\n return initialState;\n };\n const budgets = new Map();\n const getBudget = key => {\n let budget = budgets.get(key);\n if (budget === undefined) {\n budget = {\n sent: 0,\n observed: 0,\n remaining: 0,\n resetAt: 0\n };\n budgets.set(key, budget);\n }\n return budget;\n };\n const onResponse = options.disableResponseInspection ? undefined : (clock, key, headers, tokens, sent) => {\n const current = getState(key);\n const next = parseRateLimiterState(current, clock, headers, tokens, headerNames);\n if (next.limit !== current.limit || !Duration.equals(next.window, current.window)) {\n states.set(key, next);\n }\n const remaining = parseRateLimitRemaining(headers, headerNames);\n const budget = getBudget(key);\n // responses to earlier requests carry stale counts\n if (remaining === undefined || sent <= budget.observed) {\n return;\n }\n const resetAfter = parseRateLimitWindow(clock, headers, headerNames);\n budget.observed = sent;\n budget.remaining = remaining;\n if (resetAfter !== undefined) {\n budget.resetAt = clock.currentTimeMillisUnsafe() + Duration.toMillis(resetAfter);\n }\n };\n return transform(self, function loop(effect, request, retries = 0) {\n const fiber = Fiber.getCurrent();\n const clock = fiber.getRef(Clock);\n const key = resolveKey(request);\n const tokens = Math.max(resolveTokens(request), 1);\n const budget = getBudget(key);\n const now = clock.currentTimeMillisUnsafe();\n // requests admitted after the observed one are not reflected in its count\n if (budget.resetAt > now && budget.remaining - (budget.sent - budget.observed) < tokens) {\n return Effect.flatMap(Effect.sleep(budget.resetAt - now), () => loop(effect, request, retries));\n }\n // counted at admission, so requests already admitted are sent even if a\n // later response exhausts the budget\n const sent = budget.sent += tokens;\n const current = getState(key);\n const canRetry = options.times === undefined || retries < options.times;\n function retry(retryAfter) {\n return retryAfter ? Effect.flatMap(Effect.sleep(retryAfter), () => loop(effect, request, retries + 1)) : loop(effect, request, retries + 1);\n }\n const inspectResponse = (response, adaptive) => {\n onResponse?.(clock, key, response.headers, tokens, sent);\n if (options.disableResponseInspection || response.status !== 429) {\n return Effect.succeed(undefined);\n }\n const retryAfter = parseRetryAfter(clock.currentTimeMillisUnsafe(), getHeader(response.headers, ...headerNames.retryAfter));\n if (retryAfter === undefined) {\n return Effect.succeed(undefined);\n }\n const delay = parseRateLimitWindow(clock, response.headers, headerNames) ?? retryAfter;\n if (adaptive === undefined) {\n return Effect.succeed(delay);\n }\n return Effect.as(mapLimiterEffect(options.limiter.adaptiveFeedback({\n key,\n epoch: adaptive.epoch,\n tokens,\n status: response.status,\n retryAfter: delay\n }), request), delay);\n };\n return Effect.flatMap(mapLimiterEffect(options.limiter.consume({\n algorithm: options.algorithm,\n onExceeded: \"delay\",\n key,\n limit: current.limit,\n window: current.window,\n tokens\n }), request), ({\n delay\n }) => {\n const runAdaptive = () => {\n const runRequest = adaptive => {\n const request = Effect.matchEffect(effect, {\n onSuccess(response) {\n return Effect.flatMap(inspectResponse(response, adaptive), retryAfter => {\n if (response.status !== 429 || !canRetry) return Effect.succeed(response);\n return retry(retryAfter);\n });\n },\n onFailure(error) {\n if (isTooManyRequestsHttpClientError(error)) {\n return Effect.flatMap(inspectResponse(error.reason.response, adaptive), retryAfter => canRetry ? retry(retryAfter) : Effect.fail(error));\n }\n return Effect.fail(error);\n }\n });\n return adaptive === undefined || Duration.isZero(adaptive.delay) ? request : Effect.delay(request, adaptive.delay);\n };\n if (!adaptiveLearningEnabled) {\n return runRequest(undefined);\n }\n return Effect.flatMap(mapLimiterEffect(options.limiter.adaptiveConsume({\n key,\n tokens,\n fallbackLimit: current.limit,\n fallbackWindow: current.window\n }), request), adaptive => {\n if (!Duration.isZero(adaptive.delay) && adaptive.phase === \"cooldown\") {\n return Effect.flatMap(Effect.sleep(adaptive.delay), runAdaptive);\n }\n return runRequest(adaptive);\n });\n };\n return Duration.isZero(delay) ? runAdaptive() : Effect.flatMap(Effect.sleep(delay), runAdaptive);\n });\n });\n});\n/**\n * Guards requests with a `CircuitBreaker`.\n *\n * **Details**\n *\n * Requests are keyed by origin unless `key` is set, and classified with\n * `circuitBreakerClassifier` unless `classify` is set. A rejected request\n * fails with `CircuitBreakerError` without reaching the wrapped client.\n *\n * Apply it after `withRateLimiter` and `retryTransient`, so the breaker sees\n * one outcome per call and an open circuit skips the retry loop.\n * `retryTransient` never retries a `CircuitBreakerError`. A custom `classify`\n * can delegate the cases it doesn't handle to `circuitBreakerClassifier`.\n *\n * **Gotchas**\n *\n * - The breaker only sees the response headers. To count an error in the\n * body, lift it into the error channel below the breaker with\n * `transformResponse` and count it in `classify`.\n * - `withRateLimiter` retries `429` without limit by default, which can hold\n * the probe slot for minutes. Set its `times`.\n * - A rejected request has no client span. The rejection fails the caller's\n * span instead.\n *\n * **Example** (Guarding an API in the recommended order)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Ref, Schedule } from \"effect\"\n * import { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\"\n * import { CircuitBreaker, RateLimiter } from \"effect/persistence\"\n *\n * const program = Effect.gen(function*() {\n * const requests = yield* Ref.make(0)\n * // A dependency that always answers 503.\n * const unavailable = HttpClient.make((request) =>\n * Effect.as(Ref.update(requests, (n) => n + 1), HttpClientResponse.fromWeb(request, new Response(null, { status: 503 })))\n * )\n *\n * const breaker = yield* CircuitBreaker.make({\n * tripPolicy: CircuitBreaker.consecutive(1),\n * openDuration: \"30 seconds\"\n * })\n * const client = unavailable.pipe(\n * HttpClient.withRateLimiter({\n * limiter: yield* RateLimiter.RateLimiter,\n * key: \"inventory\",\n * limit: 100,\n * window: \"1 second\",\n * times: 3\n * }),\n * HttpClient.retryTransient({ times: 2, schedule: Schedule.exponential(\"1 millis\") }),\n * HttpClient.withCircuitBreaker({ breaker })\n * )\n *\n * // Three attempts, then the breaker records one failure and opens.\n * yield* client.execute(HttpClientRequest.get(\"http://inventory.test/items\"))\n * // Rejected before the retry loop starts, so no further request is sent.\n * const rejected = yield* Effect.flip(client.execute(HttpClientRequest.get(\"http://inventory.test/items\")))\n *\n * return [yield* Ref.get(requests), rejected._tag]\n * }).pipe(\n * Effect.scoped,\n * Effect.provide(Layer.merge(\n * CircuitBreaker.layerStoreMemory(),\n * RateLimiter.layer.pipe(Layer.provide(RateLimiter.layerStoreMemory))\n * ))\n * )\n *\n * await Effect.runPromise(program) // => [3, \"CircuitBreakerError\"]\n * ```\n *\n * **Example** (Counting an error in the body as a failure)\n *\n * This API answers `200` with `{ \"status\": \"degraded\" }` when it is failing.\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Exit, Option } from \"effect\"\n * import { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\"\n * import { CircuitBreaker } from \"effect/persistence\"\n *\n * class Degraded extends Data.TaggedError(\"Degraded\") {}\n *\n * const degraded = HttpClient.make((request) =>\n * Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ status: \"degraded\" })))\n * )\n *\n * const program = Effect.gen(function*() {\n * const breaker = yield* CircuitBreaker.make({\n * tripPolicy: CircuitBreaker.consecutive(1),\n * openDuration: \"30 seconds\"\n * })\n * const client = degraded.pipe(\n * HttpClient.transformResponse(Effect.flatMap((response) =>\n * Effect.flatMap(response.json, (body) =>\n * typeof body === \"object\" && body !== null && \"status\" in body && body.status === \"degraded\"\n * ? Effect.fail(new Degraded())\n * : Effect.succeed(response))\n * )),\n * HttpClient.withCircuitBreaker({\n * breaker,\n * classify: (exit) =>\n * Option.exists(Exit.findErrorOption(exit), (error) => error._tag === \"Degraded\")\n * ? CircuitBreaker.failure()\n * : HttpClient.circuitBreakerClassifier(exit)\n * })\n * )\n *\n * yield* Effect.flip(client.get(\"http://status.test/\"))\n * const state = yield* breaker.state(\"http://status.test\")\n * return state._tag\n * }).pipe(Effect.scoped, Effect.provide(CircuitBreaker.layerStoreMemory()))\n *\n * await Effect.runPromise(program) // => \"Open\"\n * ```\n *\n * @stability experimental\n * @category circuit breaking\n * @since 4.0.7\n */\nexport const withCircuitBreaker = /*#__PURE__*/dual(2, (self, options) => {\n const keyOption = options.key;\n const resolveKey = typeof keyOption === \"function\" ? keyOption : keyOption === undefined ? requestOrigin : constant(keyOption);\n const classify = options.classify ?? circuitBreakerClassifier;\n return transform(self, (effect, request) => options.breaker.execute(effect, {\n key: resolveKey(request),\n classify\n }));\n});\nconst requestOrigin = request => Option.match(HttpClientRequest.toUrl(request), {\n onNone: () => request.url,\n onSome: url => url.origin\n});\n/**\n * The default `withCircuitBreaker` classifier.\n *\n * **Details**\n *\n * - Failure: status 408, 500, 502, 503 or 504, returned or wrapped in a\n * `StatusCodeError`, and any `TransportError` or `Cause.TimeoutError`.\n * - Success: any other response, including other 4xx, since the dependency\n * answered.\n * - Ignored: status 429 (left to `withRateLimiter`), `EncodeError`,\n * `InvalidUrlError`, `DecodeError`, `EmptyBodyError`, unknown typed errors\n * and defects. HttpClient errors are typed, so a defect here is a bug in\n * the caller.\n *\n * When a cause holds several errors, a failure beats a success and a success\n * beats an ignored outcome. A failure carries the longest `Retry-After` it\n * saw. The result is an `Effect` only because parsing an HTTP-date\n * `Retry-After` reads `Clock`.\n *\n * **Gotchas**\n *\n * `TransportError` also covers client-side refusals, which count as failures.\n *\n * @stability experimental\n * @category circuit breaking\n * @since 4.0.7\n */\nexport const circuitBreakerClassifier = exit => Effect.clockWith(clock => Effect.succeed(classifyCircuitBreakerExit(exit, clock.currentTimeMillisUnsafe())));\nconst classifyCircuitBreakerExit = (exit, nowMillis) => {\n if (Exit.isSuccess(exit)) {\n const outcome = circuitBreakerStatusOutcome(exit.value.status);\n return outcome === \"Failure\" ? circuitBreakerFailure(retryAfterOf(exit.value, nowMillis)) : {\n _tag: outcome\n };\n }\n let failed = false;\n let succeeded = false;\n let retryAfter;\n for (const reason of exit.cause.reasons) {\n if (!Cause.isFailReason(reason)) {\n continue;\n }\n const outcome = circuitBreakerErrorOutcome(reason.error);\n if (outcome === \"Failure\") {\n failed = true;\n const hint = retryAfterOf(reason.error, nowMillis);\n if (hint !== undefined) {\n retryAfter = retryAfter === undefined ? hint : Duration.max(retryAfter, hint);\n }\n } else if (outcome === \"Success\") {\n succeeded = true;\n }\n }\n return failed ? circuitBreakerFailure(retryAfter) : {\n _tag: succeeded ? \"Success\" : \"Ignored\"\n };\n};\nconst circuitBreakerFailure = retryAfter => ({\n _tag: \"Failure\",\n retryAfter\n});\nconst circuitBreakerErrorOutcome = error => {\n if (Cause.isTimeoutError(error)) {\n return \"Failure\";\n }\n if (!Error.isHttpClientError(error)) {\n return \"Ignored\";\n }\n switch (error.reason._tag) {\n case \"TransportError\":\n return \"Failure\";\n case \"StatusCodeError\":\n return circuitBreakerStatusOutcome(error.reason.response.status);\n default:\n return \"Ignored\";\n }\n};\nconst circuitBreakerStatusOutcome = status => status === 429 ? \"Ignored\" : status === 408 || status === 500 || status === 502 || status === 503 || status === 504 ? \"Failure\" : \"Success\";\nconst resolveRateLimiterHeaderNames = responseHeaders => ({\n limit: responseHeaders?.limit === undefined ? [\"ratelimit-limit\", \"x-ratelimit-limit\"] : [responseHeaders.limit.toLowerCase()],\n remaining: responseHeaders?.remaining === undefined ? [\"ratelimit-remaining\", \"x-ratelimit-remaining\"] : [responseHeaders.remaining.toLowerCase()],\n reset: responseHeaders?.reset === undefined ? [\"ratelimit-reset\", \"x-ratelimit-reset\"] : [responseHeaders.reset.toLowerCase()],\n resetAfter: responseHeaders?.resetAfter === undefined ? [\"ratelimit-reset-after\", \"x-ratelimit-reset-after\"] : [responseHeaders.resetAfter.toLowerCase()],\n retryAfter: responseHeaders?.retryAfter === undefined ? [\"retry-after\"] : [responseHeaders.retryAfter.toLowerCase()]\n});\nconst parseRateLimiterState = (state, clock, headers, tokens, headerNames) => {\n const limit = parseRateLimitLimit(state, headers, tokens, headerNames) ?? state.limit;\n const window = parseRateLimitWindow(clock, headers, headerNames) ?? state.window;\n if (limit === state.limit && Duration.equals(window, state.window)) {\n return state;\n }\n return {\n limit,\n window,\n initial: false\n };\n};\nconst parseRateLimitLimit = (state, headers, tokens, headerNames) => {\n const raw = getHeader(headers, ...headerNames.limit);\n const value = parseNumberHeader(raw);\n if (value !== undefined && value > 0) {\n return value;\n }\n const remaining = parseRateLimitRemaining(headers, headerNames);\n if (remaining === undefined) {\n return undefined;\n }\n return state.initial ? remaining + tokens : Math.max(remaining + tokens, state.limit);\n};\nconst parseRateLimitRemaining = (headers, headerNames) => {\n const raw = getHeader(headers, ...headerNames.remaining);\n const value = parseNumberHeader(raw);\n return value !== undefined && value >= 0 ? value : undefined;\n};\nconst parseRateLimitWindow = (clock, headers, headerNames) => {\n const resetAfter = parseResetAfter(getHeader(headers, ...headerNames.resetAfter));\n if (resetAfter !== undefined) {\n return resetAfter;\n }\n return parseResetHeader(clock, getHeader(headers, ...headerNames.reset));\n};\nconst retryAfterDelay = (nowMillis, value) => {\n if (value === undefined) {\n return undefined;\n }\n const retryAfter = Headers.parseRetryAfter(value);\n return Result.isSuccess(retryAfter) ? Headers.retryAfterDelay(retryAfter.success, nowMillis) : undefined;\n};\n// The one millisecond floor keeps a past date or `0` from retrying immediately.\nconst parseRetryAfter = (nowMillis, value) => {\n const delay = retryAfterDelay(nowMillis, value);\n return delay === undefined ? undefined : Duration.max(delay, Duration.millis(1));\n};\nconst parseResetAfter = value => {\n const numeric = parseNumberHeader(value);\n if (numeric === undefined || numeric <= 0) {\n return undefined;\n }\n return Duration.max(Duration.seconds(numeric), Duration.millis(1));\n};\nconst parseResetHeader = (clock, value) => {\n const numeric = parseNumberHeader(value);\n if (numeric === undefined || numeric <= 0) {\n return undefined;\n }\n const nowMillis = clock.currentTimeMillisUnsafe();\n if (numeric > 1_000_000_000_000) {\n return Duration.millis(Math.max(numeric - nowMillis, 1));\n }\n if (numeric > 1_000_000_000) {\n return Duration.millis(Math.max(numeric * 1_000 - nowMillis, 1));\n }\n return Duration.max(Duration.seconds(numeric), Duration.millis(1));\n};\nconst parseNumberHeader = value => {\n if (value === undefined) {\n return undefined;\n }\n const match = /-?\\d+(?:\\.\\d+)?/.exec(value);\n if (match === null) {\n return undefined;\n }\n const parsed = Number(match[0]);\n return Number.isFinite(parsed) ? parsed : undefined;\n};\nconst getHeader = (headers, ...keys) => {\n for (let i = 0; i < keys.length; i++) {\n const value = headers[keys[i]];\n if (value !== undefined) {\n return value;\n }\n }\n return undefined;\n};\n/**\n * Performs an additional effect after a successful request.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.tap(f)));\n/**\n * Performs an additional effect after an unsuccessful request.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.tapError(f)));\n/**\n * Performs an additional effect on the request before sending it.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapRequest = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.tap(self.preprocess(request), f)));\n/**\n * Adds a `Ref` of stored cookies to the client for handling cookies across\n * requests.\n *\n * **When to use**\n *\n * Use to add shared cookie storage to a client so response cookies are retained\n * and sent by later requests to a matching host, path, and scheme.\n *\n * **Details**\n *\n * Response cookies are merged into the ref with `Cookies.mergeIntoArray` for\n * the response URL. When a request is sent, `Cookies.toRequestCookieHeader`\n * selects the cookies for its final URL, after later transformations such as\n * `HttpClientRequest.prependUrl`, and sets them as the `cookie` header. With\n * `followRedirects` applied after `withCookiesRef`, this runs for every hop.\n * Expiry uses the current `Clock`.\n *\n * @stability unstable\n * @category cookies\n * @since 4.0.0\n */\nexport const withCookiesRef = /*#__PURE__*/dual(2, (self, ref) => {\n const now = () => Fiber.getCurrent().getRef(Clock).currentTimeMillisUnsafe();\n const addCookies = request => Effect.map(Ref.get(ref), cookies => {\n const header = Cookies.toRequestCookieHeader(cookies, request.url, now());\n if (header === undefined) return request;\n return HttpClientRequest.setHeader(request, \"cookie\", header);\n });\n return makeWith(request => Effect.tap(self.postprocess(Effect.flatMap(request, addCookies)), response => Ref.update(ref, Cookies.mergeIntoArray(response.url, response.cookies, now()))), self.preprocess);\n});\n/**\n * Attaches every request the client sends to the current `Scope`, and aborts\n * them when the scope closes.\n *\n * **When to use**\n *\n * Use when a response body, an upgraded socket or a `toWeb` hand-off must\n * stay open after the response effect completes, and close it by closing the\n * scope.\n *\n * **Details**\n *\n * Ownership follows the execution, not the request value. Each request the\n * transport sends while this client executes belongs to the scope: every\n * redirect hop, retry attempt and request rewritten by middleware, whichever\n * side of `followRedirects`, `withCookiesRef` or `retryTransient` the\n * `withScope` is on. Reusing one request, or one response effect,\n * concurrently under different scopes gives each execution its own owner.\n *\n * Closing the scope aborts pending requests and open response bodies. A\n * request sent after the scope has closed is aborted before the transport\n * starts it. Interrupting a request before its response arrives still aborts\n * it, so a `timeout` that fires before then releases the connection. Once a\n * response is returned, its body is released only when the scope closes.\n *\n * **Gotchas**\n *\n * Requests that middleware sends with another client while this client\n * executes, such as a token fetch in `mapRequestEffect`, are also attached to\n * the scope. When `withScope` is nested, the innermost one owns the requests,\n * so to give a helper request a different lifetime, apply `withScope` to the\n * helper client and run its request in its own scope, for example with\n * `Effect.scoped`.\n *\n * @stability unstable\n * @category resource management\n * @since 4.0.0\n */\nexport const withScope = self => transformResponse(self, Effect.provideServiceEffect(RequestScope, Effect.scope));\n/**\n * Adds `HttpTraceContext.CurrentBaggage` to outgoing requests as a W3C `baggage` header.\n *\n * **Details**\n *\n * Keeps an existing `baggage` header and adds none when the current baggage is empty.\n *\n * **Gotchas**\n *\n * Baggage can carry application data. Apply this only within your trust boundary.\n * `followRedirects` strips baggage on cross-origin redirects; Fetch's automatic\n * redirects can forward it. With `FetchHttpClient`, provide\n * `FetchHttpClient.RequestInit` with `{ redirect: \"manual\" }` and use\n * `followRedirects`, or disable redirects with `{ redirect: \"error\" }`.\n *\n * **Example** (Forwarding baggage to an internal service)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(HttpClient.withBaggage)\n * return yield* client.get(\"http://orders.internal/orders\")\n * })\n * ```\n *\n * @see {@link TraceContext.CurrentBaggage} for the baggage that is sent\n * @stability unstable\n * @category tracing\n * @since 4.1.8\n */\nexport const withBaggage = self => mapRequestEffect(self, request => request.headers.baggage !== undefined ? Effect.succeed(request) : Effect.map(TraceContext.CurrentBaggage, baggage => {\n const header = TraceContext.baggageToHeader(baggage);\n return header === \"\" ? request : HttpClientRequest.setHeader(request, \"baggage\", header);\n}));\nconst crossOriginHeaders = [\"authorization\", \"proxy-authorization\", \"cookie\", \"baggage\"];\n/**\n * Enables following HTTP redirects up to a specified number of times.\n *\n * **Details**\n *\n * Follows `3xx` responses that include a `Location` header, up to\n * `maxRedirects` (default `10`) times. When the limit is reached or the\n * `Location` header is not a valid URL, the last redirect response is returned.\n * Redirects to another origin drop the `authorization`,\n * `proxy-authorization`, `cookie` and `baggage` headers.\n *\n * **Gotchas**\n *\n * This only sees redirects that the underlying client returns. `fetch`\n * follows redirects itself by default, so with `FetchHttpClient` provide\n * `FetchHttpClient.RequestInit` with `{ redirect: \"manual\" }`. Browsers return\n * an opaque response without a `Location` header for manual redirects, so\n * this cannot follow them there.\n *\n * **Example** (Following redirects with FetchHttpClient)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { FetchHttpClient, HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.followRedirects(5)\n * )\n * return yield* client.get(\"https://example.com/redirect\")\n * }).pipe(\n * Effect.provide(FetchHttpClient.layer),\n * Effect.provideService(FetchHttpClient.RequestInit, { redirect: \"manual\" })\n * )\n * ```\n *\n * @stability unstable\n * @category redirects\n * @since 4.0.0\n */\nexport const followRedirects = /*#__PURE__*/dual(args => isHttpClient(args[0]), (self, maxRedirects) => makeWith(request => {\n const loop = (request, redirects) => Effect.suspend(() => {\n let currentRequest;\n return Effect.flatMap(self.postprocess(Effect.map(request, request => {\n currentRequest = request;\n return request;\n })), response => {\n if (response.status < 300 || response.status >= 400 || !response.headers.location || redirects >= (maxRedirects ?? 10)) {\n return Effect.succeed(response);\n }\n const urlResult = Url.fromString(response.headers.location, response.request.url);\n if (Result.isFailure(urlResult)) {\n return Effect.succeed(response);\n }\n const url = urlResult.success;\n const request = currentRequest ?? response.request;\n let nextRequest = request;\n if ((response.status === 301 || response.status === 302) && request.method === \"POST\" || response.status === 303 && request.method !== \"GET\" && request.method !== \"HEAD\") {\n nextRequest = HttpClientRequest.setMethod(nextRequest, \"GET\");\n nextRequest = HttpClientRequest.setBody(nextRequest, HttpBody.empty);\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-encoding\");\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-language\");\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-location\");\n }\n // Request the Location as sent: setUrl with a URL object would re-encode its query\n const hash = url.hash === \"\" ? Option.none() : Option.some(url.hash.slice(1));\n url.hash = \"\";\n nextRequest = HttpClientRequest.makeWith(nextRequest.method, url.href, UrlParams.empty, hash, url.origin === new URL(response.request.url).origin ? nextRequest.headers : Headers.removeMany(nextRequest.headers, crossOriginHeaders), nextRequest.body);\n // Abort the discarded response to release its connection without reading the body\n return Effect.andThen(Effect.sync(() => responseControllers.get(response)?.abort()),\n // A redirect hop is a new request, so it does not get the endpoint's url.template\n Effect.updateService(loop(Effect.succeed(nextRequest), redirects + 1), CurrentClientPath, withoutTemplate));\n });\n });\n return loop(request, 0);\n}, self.preprocess));\n/**\n * Context reference for a predicate that disables client-side tracing for matching outgoing requests.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerDisabledWhen = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerDisabledWhen\", {\n defaultValue: () => constFalse\n});\n/**\n * Context reference for filtering request and response headers added to client spans.\n *\n * **Details**\n *\n * Header capture is opt-in: the default filter records no headers. Captured\n * headers listed in `Headers.CurrentRedactedNames` are recorded as `<redacted>`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerHeaderFilter = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerHeaderFilter\", {\n defaultValue: () => constFalse\n});\n/**\n * Context reference that controls whether outgoing client spans are propagated to request headers.\n *\n * **Details**\n *\n * When this is `true`, the client writes the compact B3 `b3` header and the\n * W3C `traceparent` header. The default is on. The client span is still\n * created when this is `false`.\n *\n * **Gotchas**\n *\n * A browser preflight fails when the target does not list `b3` and\n * `traceparent` in `Access-Control-Allow-Headers`. Set this to `false` for\n * those requests.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerPropagationEnabled = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerPropagationEnabled\", {\n defaultValue: constTrue\n});\n/**\n * Context reference for generating the span name used for outgoing client request spans.\n *\n * **Details**\n *\n * The second argument carries the request's `template`, the declared path of\n * an `HttpApiClient` endpoint request such as `/users/:id`, or `undefined`\n * for other requests. The default returns `GET /users/:id` when there is a\n * template and the method otherwise. Provide `(request) => request.method` to\n * use method-only names.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const SpanNameGenerator = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/SpanNameGenerator\", {\n defaultValue: () => (request, {\n template\n }) => template === undefined ? request.method : `${request.method} ${template}`\n});\n/**\n * Creates an `HttpClient` layer and merges the layer construction context into client response effects.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerMergedContext = effect => Layer.effect(HttpClient)(Effect.contextWith(context => Effect.map(effect, client => transformResponse(client, Effect.updateContext(input => Context.merge(context, input))))));\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nconst responseRegistry = /*#__PURE__*/(() => {\n if (\"FinalizationRegistry\" in globalThis && globalThis.FinalizationRegistry) {\n const registry = /*#__PURE__*/new FinalizationRegistry(controller => {\n try {\n controller.abort();\n } catch {\n // Runtimes such as workerd disallow aborting I/O outside its request context.\n }\n });\n return {\n register(response, controller) {\n registry.register(response, controller, response);\n },\n unregister(response) {\n registry.unregister(response);\n }\n };\n }\n const timers = /*#__PURE__*/new WeakMap();\n return {\n register(response, controller) {\n timers.set(response, setTimeout(() => controller.abort(), 5000));\n },\n unregister(response) {\n const timer = timers.get(response);\n if (timer === undefined) return;\n clearTimeout(timer);\n timers.delete(response);\n }\n };\n})();\nconst RequestScope = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/RequestScope\", {\n defaultValue: () => undefined\n});\nconst responseControllers = /*#__PURE__*/new WeakMap();\nconst trackResponse = (response, controller, scoped, urlParamsRedactedNames, redactedPath) => {\n // Body readers create errors with the runner's response, while callers hold\n // the wrapper, so both carry the names of the executing fiber.\n Error.addResponseRedactedNames(response, urlParamsRedactedNames, redactedPath);\n if (!scoped) {\n responseRegistry.register(response, controller);\n response = new InterruptibleResponse(response, controller);\n Error.addResponseRedactedNames(response, urlParamsRedactedNames, redactedPath);\n }\n responseControllers.set(response, controller);\n return response;\n};\nclass InterruptibleResponse {\n original;\n controller;\n constructor(original, controller) {\n this.original = original;\n this.controller = controller;\n }\n [HttpClientResponse.TypeId] = HttpClientResponse.TypeId;\n [HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n applyInterrupt(effect) {\n return Effect.suspend(() => {\n responseRegistry.unregister(this.original);\n return Effect.onInterrupt(effect, () => Effect.sync(() => {\n this.controller.abort();\n }));\n });\n }\n get request() {\n return this.original.request;\n }\n get url() {\n return this.original.url;\n }\n get status() {\n return this.original.status;\n }\n get headers() {\n return this.original.headers;\n }\n get cookies() {\n return this.original.cookies;\n }\n get remoteAddress() {\n return this.original.remoteAddress;\n }\n get formData() {\n return this.applyInterrupt(this.original.formData);\n }\n get text() {\n return this.applyInterrupt(this.original.text);\n }\n get json() {\n return this.applyInterrupt(this.original.json);\n }\n get urlParamsBody() {\n return this.applyInterrupt(this.original.urlParamsBody);\n }\n get arrayBuffer() {\n return this.applyInterrupt(this.original.arrayBuffer);\n }\n get upgrade() {\n return this.applyInterrupt(this.original.upgrade);\n }\n [WebSourceSymbol]() {\n const source = getWebSource(this.original);\n // A handed-over Web body outlives this wrapper, so collecting it must not abort the request.\n if (source !== undefined) responseRegistry.unregister(this.original);\n return source;\n }\n get stream() {\n return Stream.suspend(() => {\n responseRegistry.unregister(this.original);\n return Stream.ensuring(this.original.stream, Effect.sync(() => {\n this.controller.abort();\n }));\n });\n }\n toJSON() {\n return this.original.toJSON();\n }\n [Inspectable.NodeInspectSymbol]() {\n return this.original[Inspectable.NodeInspectSymbol]();\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\n/**\n * Returns `true` for an error that `retryTransient` retries by default: a\n * timeout, a transport error, or a status code error with a transient response.\n *\n * **When to use**\n *\n * Use to classify failures the same way `retryTransient` does, for example in a\n * custom retry policy or a circuit breaker.\n *\n * **Example** (Classifying client errors)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n * import { HttpClient, HttpClientError, HttpClientRequest } from \"effect/http\"\n *\n * const request = HttpClientRequest.get(\"https://example.com\")\n * const transportError = new HttpClientError.HttpClientError({\n * reason: new HttpClientError.TransportError({ request })\n * })\n *\n * HttpClient.isTransientError(transportError) // => true\n * HttpClient.isTransientError(new Cause.TimeoutError()) // => true\n * HttpClient.isTransientError(new Error(\"boom\")) // => false\n * ```\n *\n * @see {@link isTransientResponse} for the response statuses it accepts\n * @see {@link retryTransient} for the retry policy that uses it\n * @stability unstable\n * @category predicates\n * @since 4.1.0\n */\nexport const isTransientError = error => Cause.isTimeoutError(error) || isTransientHttpError(error);\nconst isTransientHttpError = error => Error.isHttpClientError(error) && (error.reason._tag === \"TransportError\" || error.reason._tag === \"StatusCodeError\" && isTransientResponse(error.reason.response));\nconst retryAfterHeaderOf = input => {\n const response = Error.isHttpClientError(input) ? input.response : Predicate.hasProperty(input, HttpClientResponse.TypeId) ? input : undefined;\n return response?.headers[\"retry-after\"];\n};\nconst retryAfterOf = (input, nowMillis) => parseRetryAfter(nowMillis, retryAfterHeaderOf(input));\n/**\n * Creates a predicate for `Schedule.while` that returns `false` when the\n * server requests a `Retry-After` delay greater than `max`.\n *\n * **When to use**\n *\n * Use with `retryTransient` to stop retries before a long `Retry-After` sleep.\n *\n * **Details**\n *\n * Reads the header from an `HttpClientResponse` or the response of an\n * `HttpClientError`. Returns `true` for delays at or below `max` and for inputs\n * without a valid header, including application errors. HTTP dates are compared\n * with the schedule's `now`.\n *\n * When the predicate returns `false`, `Schedule.while` stops before sleeping.\n * `retryTransient` then returns the last response or fails with the original error.\n *\n * **Gotchas**\n *\n * `max` limits the delay requested by the server, not the schedule's delay or\n * total retry time. `retryTransient` honors the header's delay automatically;\n * with `HttpClient.retry` or `Effect.retry`, the schedule supplies the delay.\n *\n * **Example** (Giving up on a long Retry-After)\n *\n * ```ts\n * import { Effect, Schedule } from \"effect\"\n * import { HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.retryTransient({\n * times: 3,\n * schedule: Schedule.exponential(\"100 millis\").pipe(\n * Schedule.while(HttpClient.retryAfterAtMost(\"30 seconds\"))\n * )\n * })\n * )\n * return yield* client.get(\"https://example.com\")\n * })\n * ```\n *\n * @see {@link retryTransient} for the retry policy that honors `Retry-After`\n * @stability unstable\n * @category predicates\n * @since 4.1.8\n */\nexport const retryAfterAtMost = max => {\n const limit = Duration.fromInputUnsafe(max);\n return ({\n input,\n now\n }) => {\n const delay = retryAfterDelay(now, retryAfterHeaderOf(input));\n return delay === undefined || Duration.isLessThanOrEqualTo(delay, limit);\n };\n};\nconst withRetryAfter = schedule => Schedule.fromStep(Effect.map(Schedule.toStep(schedule), step => (now, input) => {\n const retryAfter = retryAfterOf(input, now);\n if (retryAfter === undefined) {\n return step(now, input);\n }\n return Effect.map(step(now, input), ([output, delay]) => [output, Duration.max(delay, retryAfter)]);\n}));\nconst isTooManyRequestsHttpClientError = error => Error.isHttpClientError(error) && error.reason._tag === \"StatusCodeError\" && error.reason.response.status === 429;\n/**\n * Returns `true` for a response whose status `retryTransient` retries by\n * default: 408, 429, 500, 502, 503 or 504.\n *\n * **When to use**\n *\n * Use to retry the same responses as `retryTransient` in a custom retry policy.\n *\n * @see {@link isTransientError} for the matching error predicate\n * @see {@link retryTransient} for the retry policy that uses it\n * @stability unstable\n * @category predicates\n * @since 4.1.0\n */\nexport const isTransientResponse = response => response.status === 408 || response.status === 429 || response.status === 500 || response.status === 502 || response.status === 503 || response.status === 504;\n//# sourceMappingURL=HttpClient.js.map","/**\n * Service contract for servers that accept socket connections.\n *\n * `SocketServer` exposes the bound server `address` and a long-running `run`\n * loop that hands each accepted connection to a handler as a `Socket.Socket`.\n * Bound addresses use the shared `NetAddress.SocketAddress` model. This module also\n * defines server-level errors reported while opening or running a server.\n * Platform layers provide concrete implementations of this service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Data from \"../Data.js\";\n/**\n * Context service for a socket server, exposing its bound address and a run\n * loop that handles each accepted `Socket`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class SocketServer extends /*#__PURE__*/Context.Service()(\"@effect/platform/SocketServer\") {}\n/**\n * Runtime type identifier attached to `SocketServerError` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const ErrorTypeId = \"@effect/platform/SocketServer/SocketServerError\";\n/**\n * Error reason for failures that occur while opening a socket server.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerOpenError extends /*#__PURE__*/Data.TaggedError(\"SocketServerOpenError\") {\n get message() {\n return \"Open\";\n }\n}\n/**\n * Error reason for uncategorized socket server failures.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerUnknownError extends /*#__PURE__*/Data.TaggedError(\"SocketServerUnknownError\") {\n get message() {\n return \"Unknown\";\n }\n}\n/**\n * Tagged socket server error that wraps a server error reason and exposes its\n * cause.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerError extends /*#__PURE__*/Data.TaggedError(\"SocketServerError\") {\n constructor(props) {\n super({\n ...props,\n cause: props.reason.cause\n });\n }\n /**\n * Marks this value as a socket server error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [ErrorTypeId] = ErrorTypeId;\n /**\n * Delegates the public message to the underlying socket server error reason.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return this.reason.message;\n }\n}\n//# sourceMappingURL=SocketServer.js.map","import * as Bytes from \"../Bytes.js\";\nimport * as Cause from \"../Cause.js\";\nimport * as Context from \"../Context.js\";\nimport * as Deferred from \"../Deferred.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Exit from \"../Exit.js\";\nimport * as Fiber from \"../Fiber.js\";\nimport { constant, constTrue, constVoid, identity } from \"../Function.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpServerRequest from \"../http/HttpServerRequest.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport { reportCauseUnsafe } from \"../internal/effect.js\";\nimport * as Latch from \"../Latch.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Pull from \"../Pull.js\";\nimport * as Queue from \"../Queue.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as SchemaIssue from \"../SchemaIssue.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Semaphore from \"../Semaphore.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as SocketServer from \"../socket/SocketServer.js\";\nimport { Stdio } from \"../Stdio.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as WorkerRunner from \"../workers/WorkerRunner.js\";\nimport * as RpcTracing from \"./internal/tracing.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { constEof, constPong, RequestId, ResponseDefectEncoded } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport { withRun } from \"./Utils.js\";\n/**\n * Creates an RPC server for an already-decoded message channel, running\n * handlers for a group and sending decoded server responses through\n * `onFromServer`.\n *\n * **Details**\n *\n * If writing a stream `Chunk` fails with anything other than an interruption,\n * the request fails with that cause. `onFromServer` is assumed to have already\n * answered the client and reported it, so nothing else is sent or reported.\n *\n * A request with `isNotification` set runs like any other, but no `Exit`,\n * `Chunk` or `Defect` is sent for it. Its failures are still reported.\n *\n * A request with `discard` set is acknowledged with a successful `Exit` once\n * its handler starts, after the concurrency permit is taken and the\n * middleware has run. Nothing else is sent for it after that, and its\n * failures are only reported. A failure before the acknowledgement is sent as\n * a failed `Exit` for that request.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const enableTracing = options.disableTracing !== true;\n const enableSpanPropagation = options.disableSpanPropagation !== true;\n const supportsAck = options.disableClientAcks !== true;\n const spanPrefix = options.spanPrefix;\n const concurrency = options.concurrency ?? \"unbounded\";\n const disableFatalDefects = options.disableFatalDefects ?? false;\n const services = yield* Effect.context();\n const scope = Context.get(services, Scope.Scope);\n const trackFiber = Fiber.runIn(Scope.forkUnsafe(scope, \"parallel\"));\n const concurrencySemaphore = concurrency === \"unbounded\" ? undefined : yield* Semaphore.make(concurrency);\n const clients = new Map();\n let isShutdown = false;\n const shutdownLatch = Latch.makeUnsafe(false);\n yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n isShutdown = true;\n for (const client of clients.values()) {\n client.ended = true;\n if (client.fibers.size === 0) {\n trackFiber(Effect.runForkWith(services)(endClient(client)));\n continue;\n }\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n }\n if (clients.size === 0) {\n return Effect.void;\n }\n return shutdownLatch.await;\n }));\n const disconnect = clientId => Effect.withFiber(parent => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n clients.delete(clientId);\n return Effect.void;\n });\n const write = (clientId, message, opts) => Effect.catchDefect(Effect.withFiber(requestFiber => {\n if (isShutdown) return Effect.interrupt;\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n latches: undefined,\n fibers: new Map(),\n ended: false,\n serverClient: new Rpc.ServerClient(clientId)\n };\n clients.set(clientId, client);\n } else if (client.ended && (message._tag !== \"Interrupt\" && message._tag !== \"Ack\" || !client.fibers.has(message.requestId))) {\n return Effect.interrupt;\n }\n switch (message._tag) {\n case \"Request\":\n {\n return handleRequest(requestFiber, client, message, opts);\n }\n case \"Ack\":\n {\n const latch = client.latches?.get(message.requestId);\n return latch ? Effect.asVoid(latch.open) : Effect.void;\n }\n case \"Interrupt\":\n {\n const fiber = client.fibers.get(message.requestId);\n if (fiber) {\n fiber.interruptUnsafe(requestFiber.id, RpcSchema.ClientAbort.annotation);\n return Effect.void;\n }\n return options.onFromServer({\n _tag: \"Exit\",\n clientId,\n requestId: message.requestId,\n exit: Exit.interrupt()\n });\n }\n case \"Eof\":\n {\n client.ended = true;\n if (client.fibers.size > 0) return Effect.void;\n return endClient(client);\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${message._tag}`);\n }\n }\n }), defect => sendDefect(clients.get(clientId), defect));\n const endClient = client => {\n clients.delete(client.id);\n const write = options.onFromServer({\n _tag: \"ClientEnd\",\n clientId: client.id\n });\n if (isShutdown && clients.size === 0) {\n return Effect.andThen(write, shutdownLatch.open);\n }\n return write;\n };\n const handleRequest = (requestFiber, client, request, opts) => {\n if (client.fibers.has(request.id)) {\n return Effect.interrupt;\n }\n const isNotification = request.isNotification === true;\n const isDiscard = !isNotification && request.discard === true;\n let acknowledged = false;\n // a notification, or a discarded call once it has been acknowledged, gets\n // no reply of any kind\n const respond = exit => isNotification || acknowledged ? Effect.void : options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit\n });\n const rpc = group.requests.get(request.tag);\n const entry = Context.getOrUndefinedUnsafe(services, rpc?.key);\n if (!rpc || !entry) {\n const write = Effect.catchDefect(respond(Exit.die(`Unknown request tag: ${request.tag}`)), defect => sendDefect(client, defect));\n if (!client.ended || client.fibers.size > 0) return write;\n return Effect.ensuring(write, endClient(client));\n }\n const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n const metadata = {\n rpc,\n client: client.serverClient,\n requestId: request.id,\n remoteParentSpan: enableSpanPropagation && request.traceId && request.spanId ? Tracer.externalSpan({\n traceId: request.traceId,\n spanId: request.spanId,\n sampled: request.sampled\n }) : undefined,\n headers: request.headers,\n payload: request.payload\n };\n let handlerResult;\n // a handler that throws while being constructed never starts, so it is\n // neither streamed nor acknowledged\n let constructionFailed = false;\n try {\n handlerResult = entry.handler(request.payload, metadata);\n } catch (defect) {\n handlerResult = Effect.die(defect);\n constructionFailed = true;\n }\n // a const, so that the narrowing below can be aliased\n const result = handlerResult;\n // if the handler requested forking, then we skip the concurrency control\n const isWrapper = Rpc.isWrapper(result);\n const isFork = isWrapper && result.fork;\n const isUninterruptible = isWrapper && result.uninterruptible;\n // unwrap the fork data type\n const streamOrEffect = isWrapper ? result.value : result;\n // set when a chunk could not be written; the writer has already responded\n let writeFailure;\n let handler = isStream && !constructionFailed ? streamEffect(client, request, streamOrEffect, cause => {\n writeFailure = cause;\n }) : streamOrEffect;\n if (isDiscard && !constructionFailed) {\n // the acknowledgement runs inside the middleware, so it is only sent\n // once the permit is held and the middleware has started the handler\n handler = Effect.andThen(Effect.suspend(() => {\n const ack = respond(Exit.void);\n acknowledged = true;\n return ack;\n }), handler);\n }\n const withMiddleware = rpc.middlewares.size === 0 ? handler : isStream\n // middleware may rewrite or swallow a chunk write failure, so restore it\n ? Effect.flatMap(Effect.exit(applyMiddleware(services, handler, metadata)), exit => writeFailure ? Effect.failCause(writeFailure) : exit) : applyMiddleware(services, handler, metadata);\n let responded = false;\n const scope = Scope.makeUnsafe();\n let deferred = undefined;\n let effect = Effect.onExit(withMiddleware, exit => {\n responded = true;\n let write;\n if (exit._tag === \"Success\") {\n if (Deferred.isDeferred(exit.value)) {\n deferred = exit.value;\n write = Effect.void;\n } else {\n write = respond(exit);\n }\n } else if (writeFailure) {\n // onFromServer has already answered the client and reported the failure\n return Scope.closeUnsafe(scope, exit) ?? Effect.void;\n } else if (!disableFatalDefects &&\n // a notification or a discarded call only ever fails itself\n !isNotification && !isDiscard && Cause.hasDies(exit.cause) && !Cause.hasInterrupts(exit.cause)) {\n write = sendDefect(client, Cause.squash(exit.cause));\n } else {\n write = respond(exit);\n }\n const close = Scope.closeUnsafe(scope, exit);\n if (exit._tag === \"Failure\") {\n reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n }\n return close ? Effect.ensuring(write, close) : write;\n });\n if (opts?.onRequest) {\n effect = opts.onRequest(effect, request);\n }\n const tracing = Context.get(rpc.annotations, Rpc.TracingEnabled);\n if (enableTracing && (tracing === \"both\" || tracing === \"server\")) {\n const parentSpan = Context.getOrUndefined(requestFiber.context, Tracer.ParentSpan);\n effect = Effect.withSpan(effect, RpcTracing.spanName(spanPrefix, request.tag), {\n captureStackTrace: false,\n kind: \"server\",\n attributes: RpcTracing.spanAttributes(request.tag, options.spanAttributes),\n parent: metadata.remoteParentSpan,\n links: enableSpanPropagation && parentSpan ? [{\n span: parentSpan,\n attributes: {}\n }] : undefined\n });\n }\n if (!isFork && concurrencySemaphore) {\n effect = concurrencySemaphore.withPermit(effect);\n }\n const runFork = Effect.runForkWith(Context.add(handlerContext(entry, requestFiber.context), Scope.Scope, scope));\n const fiber = trackFiber(runFork(\n // Register before the handler runs to catch synchronous cancellation.\n Effect.withFiber(fiber => {\n client.fibers.set(request.id, fiber);\n return effect;\n }), isUninterruptible ? {\n uninterruptible: true\n } : undefined));\n fiber.addObserver(function onExit(exit) {\n if (deferred) {\n const fiber = trackFiber(runFork(Effect.onExit(Deferred.await(deferred), exit => {\n // a failure with no reply to carry it is only reported\n if (exit._tag === \"Failure\" && (isNotification || acknowledged)) {\n reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n }\n return respond(exit);\n })));\n client.fibers.set(request.id, fiber);\n deferred = undefined;\n fiber.addObserver(onExit);\n return;\n }\n if (!responded && !isNotification && !acknowledged && exit._tag === \"Failure\") {\n trackFiber(runFork(respond(Exit.interrupt())));\n }\n client.fibers.delete(request.id);\n client.latches?.delete(request.id);\n if (client.ended && client.fibers.size === 0) {\n trackFiber(runFork(endClient(client)));\n }\n });\n return Effect.void;\n };\n const streamEffect = (client, request, stream, onWriteFailure) => {\n // the chunks of a notification or a discarded call have no reader, so they\n // are neither sent nor acknowledged\n const silent = request.isNotification === true || request.discard === true;\n const writeChunk = values => silent ? Effect.void : Effect.onError(options.onFromServer({\n _tag: \"Chunk\",\n clientId: client.id,\n requestId: request.id,\n values\n }), cause => {\n if (!Cause.hasInterruptsOnly(cause)) onWriteFailure(cause);\n return Effect.void;\n });\n let latch;\n if (supportsAck && !silent) {\n client.latches ??= new Map();\n latch = client.latches.get(request.id);\n if (!latch) {\n latch = Latch.makeUnsafe(false);\n client.latches.set(request.id, latch);\n }\n }\n if (Effect.isEffect(stream)) {\n return stream.pipe(Effect.flatMap(queue => Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.takeAll(queue), values => {\n const write = writeChunk(values);\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.flatMap(write, () => latch.await);\n })),\n step: constVoid\n })), Pull.catchDone(() => Effect.void), Effect.scoped);\n }\n return Stream.runForEachArray(stream, values => {\n const write = writeChunk(values);\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.andThen(write, latch.await);\n });\n };\n const sendDefect = (client, defect) => Effect.suspend(() => {\n const shouldEnd = client.ended && client.fibers.size === 0;\n const write = options.onFromServer({\n _tag: \"Defect\",\n clientId: client.id,\n defect\n });\n if (!shouldEnd) return write;\n return Effect.andThen(write, endClient(client));\n });\n return identity({\n write,\n disconnect\n });\n});\n// Built-in JSON codecs depend only on the RPC schemas and can be shared.\n// Other factories may capture state at construction, so keep them per server.\nconst isSharedCodecFor = codecFor => codecFor === RpcSerialization.json.codecFor;\nconst sharedRpcCodecs = /*#__PURE__*/new WeakMap();\nconst rpcCodecs = (codecFor, rpc) => {\n const shared = isSharedCodecFor(codecFor);\n let codecs = shared ? sharedRpcCodecs.get(rpc) : undefined;\n if (codecs === undefined) {\n const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n const parseOptions = Context.get(rpc.annotations, Rpc.ParseOptions);\n codecs = {\n decode: Schema.decodeUnknownEffect(codecFor(rpc.payloadSchema), parseOptions),\n encodeChunk: Schema.encodeUnknownEffect(codecFor(Schema.NonEmptyArray(Option.isSome(streamSchemas) ? streamSchemas.value.success : Schema.Any)), parseOptions),\n encodeExit: Schema.encodeUnknownEffect(codecFor(Rpc.exitSchema(rpc)), parseOptions)\n };\n if (shared) sharedRpcCodecs.set(rpc, codecs);\n }\n return codecs;\n};\nlet sharedDefectCodecs;\nconst makeDefectCodecs = codecFor => ({\n encodeDefectUnsafe: Schema.encodeSync(codecFor(Schema.Defect())),\n // Unknown tags have no RPC schema, so use a defect-only exit schema.\n encodeUnknownRequestExit: Schema.encodeUnknownEffect(codecFor(Schema.Exit(Schema.Never, Schema.Never, Schema.Defect())))\n});\nconst defectCodecs = codecFor => isSharedCodecFor(codecFor) ? sharedDefectCodecs ??= makeDefectCodecs(codecFor) : makeDefectCodecs(codecFor);\n// Merging the handler entry services with the request fiber services costs\n// O(services), so the merged context is cached per (entry, fiber context)\n// pair. Request fibers on persistent connections keep one context across\n// requests, leaving a single O(1) overlay per request for the request scope.\nconst handlerContextCache = /*#__PURE__*/new WeakMap();\nconst handlerContext = (entry, fiberContext) => {\n let cache = handlerContextCache.get(entry);\n if (cache === undefined) {\n cache = new WeakMap();\n handlerContextCache.set(entry, cache);\n }\n let merged = cache.get(fiberContext);\n if (merged === undefined) {\n merged = Context.merge(entry.context, fiberContext);\n cache.set(fiberContext, merged);\n }\n return merged;\n};\nconst applyMiddleware = (context, handler, options) => {\n for (const service of options.rpc.middlewares) {\n try {\n const middleware = Context.getUnsafe(context, service);\n handler = middleware(handler, options);\n } catch (defect) {\n handler = Effect.die(defect);\n }\n }\n return handler;\n};\n/**\n * Runs an RPC server for a group using the current server `Protocol`, decoding\n * requests, invoking handlers, encoding responses, and managing in-flight\n * request lifetime.\n *\n * **Details**\n *\n * The server consumes `Protocol.disconnects` to interrupt a disconnected\n * client's requests, so use the `onDisconnect` option to observe disconnects\n * instead of taking from that queue.\n *\n * `onRequest` wraps the effect that runs one decoded request: its middleware\n * and handler and, when the handler returns its result directly, the response\n * write. The wrapped effect is interrupted when the request is cancelled, its\n * client disconnects or the server stops. It runs inside the request's tracing\n * span unless tracing is disabled.\n *\n * `onDisconnect` is called for each disconnect reported by the `Protocol`,\n * after the server has requested interruption of that client's in-flight\n * requests. It does not wait for those requests to finish. It is not called\n * when a client ends its input normally, or for clients still connected when\n * the server stops.\n *\n * Each callback runs in its own fiber, so a slow callback does not delay\n * cleanup for other clients, and callbacks may run concurrently. Pending\n * callbacks are interrupted when the server stops. Failures are ignored and\n * logged at `References.UnhandledLogLevel`.\n *\n * `onInvalidRequest` observes unknown tags and invalid payloads, headers or ids\n * that never reach `onRequest` or middleware. It runs on the delivering\n * fiber before the rejection is sent or the notification is logged and dropped.\n * A slow callback delays subsequent messages on that fiber. Callback failures\n * and defects are ignored and logged at `References.UnhandledLogLevel`;\n * rejection responses and notification handling are unchanged.\n *\n * **Gotchas**\n *\n * When a handler succeeds with a `Deferred`, the effect wrapped by\n * `onRequest` ends at that point. The reply is sent once the `Deferred`\n * completes, outside the wrapped effect.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n codecFor,\n disconnects,\n end,\n run,\n send,\n supportsAck,\n supportsSpanPropagation,\n supportsTransferables\n } = yield* Protocol;\n const {\n encodeDefectUnsafe,\n encodeUnknownRequestExit\n } = defectCodecs(codecFor);\n const services = yield* Effect.context();\n const scope = yield* Scope.make();\n const writeOptions = options?.onRequest ? {\n onRequest: options.onRequest\n } : undefined;\n const server = yield* makeNoSerialization(group, {\n ...options,\n disableClientAcks: !supportsAck,\n disableSpanPropagation: !supportsSpanPropagation,\n onFromServer(response) {\n const client = clients.get(response.clientId);\n if (!client) return Effect.void;\n switch (response._tag) {\n case \"Chunk\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n return handleEncode(client, response.requestId, schemas, schemas.encodeChunk(response.values), \"Chunk\");\n }\n case \"Exit\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n client.schemas.delete(response.requestId);\n return handleEncode(client, response.requestId, schemas, schemas.encodeExit(response.exit), \"Exit\");\n }\n case \"Defect\":\n {\n return sendDefect(client, response.defect);\n }\n case \"ClientEnd\":\n {\n clients.delete(response.clientId);\n return end(response.clientId);\n }\n }\n }\n }).pipe(Scope.provide(scope));\n // handle disconnects\n const onDisconnect = options?.onDisconnect;\n const handleDisconnect = onDisconnect ? clientId => Effect.andThen(server.disconnect(clientId), Effect.ignoreCause(Effect.suspend(() => onDisconnect(clientId)), {\n log: \"Unhandled\",\n message: \"RpcServer onDisconnect hook failed\"\n }).pipe(Effect.forkIn(scope))) : server.disconnect;\n yield* Effect.forkChild(Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.take(disconnects), clientId => {\n clients.delete(clientId);\n return handleDisconnect(clientId);\n })),\n step: constVoid\n }));\n const schemasCache = new WeakMap();\n const getSchemas = rpc => {\n let schemas = schemasCache.get(rpc);\n if (!schemas) {\n const entry = Context.getOrUndefinedUnsafe(services, rpc.key);\n schemas = {\n tag: rpc._tag,\n ...rpcCodecs(codecFor, rpc),\n context: entry.context\n };\n schemasCache.set(rpc, schemas);\n }\n return schemas;\n };\n // The only successful Exit sent for a discarded call is its acknowledgement,\n // which carries no value, so its Exits are encoded with a void success.\n const discardSchemasCache = new WeakMap();\n const getDiscardSchemas = (rpc, schemas) => {\n let discardSchemas = discardSchemasCache.get(rpc);\n if (!discardSchemas) {\n const exitSchema = Rpc.exitSchema(rpc);\n discardSchemas = {\n ...schemas,\n encodeExit: Schema.encodeUnknownEffect(codecFor(Schema.Exit(Schema.Void, exitSchema.error, exitSchema.defect)), Context.get(rpc.annotations, Rpc.ParseOptions))\n };\n discardSchemasCache.set(rpc, discardSchemas);\n }\n return discardSchemas;\n };\n const clients = new Map();\n const responseEnvelope = (requestId, tag, value) => tag === \"Chunk\" ? {\n _tag: \"Chunk\",\n requestId,\n values: value\n } : {\n _tag: \"Exit\",\n requestId,\n exit: value\n };\n const handleEncode = (client, requestId, schemas, effect, tag) => {\n const collector = schemas.collector;\n let encodeFailed = false;\n // The schema encoders evaluate eagerly, so an encode that needs no\n // services is already a resolved success and can skip the effect wrappers.\n const write = Exit.isExit(effect) && Exit.isSuccess(effect) ? send(client.id, responseEnvelope(requestId, tag, effect.value), collector && collector.clearUnsafe()) : Effect.flatMap(Effect.catch(Effect.provideContext(collector ? Effect.provideService(effect, Transferable.Collector, collector) : effect, schemas.context), error => Effect.withFiber(fiber => {\n const defect = Cause.die(`Failed to encode response for RPC \"${schemas.tag}\": ${SchemaIssue.defaultFormatter(error.issue)}`);\n reportCauseUnsafe(fiber, defect);\n encodeFailed = true;\n return Effect.failCause(defect);\n })), value => send(client.id, responseEnvelope(requestId, tag, value), collector && collector.clearUnsafe()));\n return Effect.catchCause(write, cause => {\n client.schemas.delete(requestId);\n // An encode failure ends the request with the defect, so the request\n // span records it. Other failures stop the request as a cancellation.\n return Effect.andThen(sendRequestDefect(client, requestId, schemas.encodeExit, Cause.squash(cause)), encodeFailed ? Effect.failCause(cause) : server.write(client.id, {\n _tag: \"Interrupt\",\n requestId,\n interruptors: []\n }));\n });\n };\n const sendRequestDefect = (client, requestId, encodeExit, defect) => Effect.catchCause(Effect.flatMap(encodeExit(Exit.die(defect)), exit => send(client.id, responseEnvelope(requestId, \"Exit\", exit))), cause => sendDefect(client, Cause.squash(cause)));\n const sendDefect = (client, defect) => Effect.catchCause(send(client.id, ResponseDefectEncoded(encodeDefectUnsafe(defect))), cause => Effect.annotateLogs(Effect.logDebug(cause), {\n module: \"RpcServer\",\n method: \"sendDefect\"\n }));\n // a notification has no reply to carry the error, so it is only logged\n const dropNotification = reason => Effect.annotateLogs(Effect.logDebug(`Dropped RPC notification: ${reason}`), {\n module: \"RpcServer\",\n method: \"dropNotification\"\n });\n const onInvalidRequest = options?.onInvalidRequest;\n // An invalid id requires a connection-level defect.\n const rejectRequest = (client, request, reason, message, requestId, encodeExit = encodeUnknownRequestExit) => {\n // Preserve the reply decision if the hook mutates the envelope.\n const isNotification = request.isNotification === true;\n // Defer sending until after the hook: `Protocol.send` may write eagerly.\n const reply = () => isNotification ? dropNotification(message) : requestId === undefined ? sendDefect(client, message) : sendRequestDefect(client, requestId, encodeExit, message);\n return onInvalidRequest ? Effect.andThen(Effect.ignoreCause(Effect.suspend(() => onInvalidRequest({\n reason,\n message,\n clientId: client.id,\n request\n })), {\n log: \"Unhandled\",\n message: \"RpcServer onInvalidRequest hook failed\"\n }), reply) : reply();\n };\n const writeDecodedRequest = (client, requestId, schemas, request, payload) => {\n // the headers come from the wire unvalidated, and malformed input makes\n // `Headers.fromInput` throw\n let headers;\n try {\n headers = Headers.fromInput(request.headers);\n } catch {\n return rejectRequest(client, request, \"InvalidHeaders\", \"Invalid request headers\", requestId, schemas.encodeExit);\n }\n // nothing is encoded for a notification, and only a reply would remove its schemas\n if (request.isNotification !== true) {\n client.schemas.set(requestId, supportsTransferables ? {\n ...schemas,\n collector: Transferable.makeCollectorUnsafe()\n } : schemas);\n }\n // the envelope is owned by this protocol loop, so it is decoded in place\n // instead of copied for every request\n const decoded = request;\n decoded.id = requestId;\n decoded.payload = payload;\n decoded.headers = headers;\n return server.write(client.id, decoded, writeOptions);\n };\n let notificationCount = 0;\n // main server loop\n return yield* run((clientId, request) => {\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n schemas: new Map()\n };\n clients.set(clientId, client);\n }\n switch (request._tag) {\n case \"Request\":\n {\n const tag = Object.hasOwn(request, \"tag\") ? request.tag : \"\";\n const isNotification = request.isNotification === true;\n let requestId;\n if (isNotification) {\n // JSON-RPC notifications share an empty id, and no reply ever names one\n requestId = RequestId(`@effect/rpc/notification/${notificationCount++}`);\n } else {\n switch (typeof request.id) {\n case \"number\":\n case \"string\":\n {\n requestId = RequestId(request.id);\n break;\n }\n default:\n {\n return rejectRequest(client, request, \"InvalidId\", `Invalid request id: ${request.id}`);\n }\n }\n }\n const rpc = group.requests.get(tag);\n if (!rpc) {\n return rejectRequest(client, request, \"UnknownTag\", `Unknown request tag: ${tag}`, requestId);\n }\n const schemas = getSchemas(rpc);\n const replySchemas = !isNotification && request.discard === true ? getDiscardSchemas(rpc, schemas) : schemas;\n const decoded = schemas.decode(request.payload);\n // The schema decoders evaluate eagerly, so a decode that needs no\n // services is already a resolved success and can skip the effect\n // wrappers.\n if (Exit.isExit(decoded) && Exit.isSuccess(decoded)) {\n return writeDecodedRequest(client, requestId, replySchemas, request, decoded.value);\n }\n return Effect.matchEffect(Effect.provideContext(decoded, schemas.context), {\n onFailure: error => rejectRequest(client, request, \"InvalidPayload\", SchemaIssue.defaultFormatter(error.issue), requestId, replySchemas.encodeExit),\n onSuccess: payload => writeDecodedRequest(client, requestId, replySchemas, request, payload)\n });\n }\n case \"Ping\":\n {\n return Effect.catchCause(send(client.id, constPong), cause => sendDefect(client, Cause.squash(cause)));\n }\n case \"Eof\":\n {\n return server.write(clientId, request);\n }\n case \"Ack\":\n {\n // the branded `RequestId` shares the runtime representation of the\n // encoded id, so the message can be forwarded as-is\n return server.write(clientId, request);\n }\n case \"Interrupt\":\n {\n return server.write(clientId, {\n ...request,\n requestId: RequestId(request.requestId),\n interruptors: []\n });\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${request._tag}`);\n }\n }\n }).pipe(Effect.tapCause(cause => Effect.logFatal(\"BUG: RpcServer protocol crashed\", cause)), Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Provides a scoped layer that starts an RPC server for a group using the\n * current server `Protocol`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (group, options) => Layer.effectDiscard(Effect.forkScoped(make(group, options)));\n/**\n * Creates a RPC server that registers a HTTP route with a `HttpRouter`.\n *\n * **Details**\n *\n * Defaults to using websockets for communication, but can be configured to use\n * HTTP.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttp = options => layer(options.group, options).pipe(Layer.provide(options.protocol === \"http\" ? layerProtocolHttp(options) : layerProtocolWebsocket(options)));\n/**\n * Defines the service interface for an RPC server transport, responsible for receiving\n * encoded client messages, sending encoded responses, tracking clients, and\n * declaring transport capabilities.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC servers over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcServer/Protocol\") {\n /**\n * Creates a server protocol service from the supplied RPC implementation.\n *\n * @stability unstable\n * @since 4.0.0\n */\n static make = /*#__PURE__*/withRun();\n}\n/**\n * Creates a server `Protocol` backed by the current `SocketServer`, accepting\n * socket connections and routing decoded RPC messages.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocketServer = /*#__PURE__*/Effect.gen(function* () {\n const server = yield* SocketServer.SocketServer;\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n yield* Effect.forkScoped(server.run(socket => Effect.scoped(onSocket(socket))));\n return protocol;\n});\n/**\n * RPC protocol that uses `SocketServer` for communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolSocketServer = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolSocketServer);\n/**\n * Creates a websocket server `Protocol` together with an HTTP effect that\n * upgrades the current request to a websocket and attaches it to the protocol.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffectWebsocket = /*#__PURE__*/Effect.gen(function* () {\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n const httpEffect = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const socket = yield* Effect.orDie(request.upgrade);\n yield* onSocket(socket, Object.entries(request.headers));\n return HttpServerResponse.empty();\n });\n return {\n protocol,\n httpEffect\n };\n});\n/**\n * Creates a websocket server `Protocol` and registers its upgrade handler as a\n * GET route on the current `HttpRouter`.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"GET\", options.path, httpEffect);\n return protocol;\n});\n/**\n * RPC protocol that uses WebSockets for communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWebsocket = options => {\n return Layer.effect(Protocol)(makeProtocolWebsocket(options));\n};\n/**\n * Creates an HTTP request/response server `Protocol` together with an HTTP\n * effect that decodes the current request and streams or returns encoded RPC\n * responses.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (options = {}) {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n const includesFraming = serialization.includesFraming;\n const isBinary = !serialization.contentType.includes(\"json\");\n const disconnects = yield* Queue.make();\n let writeRequest;\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n const encoder = new TextEncoder();\n const httpEffect = Effect.gen(function* () {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, HttpServerRequest.HttpServerRequest);\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n const requestHeaders = Object.entries(request.headers);\n const data = yield* Effect.orDie(isBinary ? Effect.map(request.arrayBuffer, buf => new Uint8Array(buf)) : request.text);\n const id = clientId++;\n const queue = yield* Queue.make({\n capacity: includesFraming && options.streamBufferSize !== \"unbounded\" ? options.streamBufferSize ?? 16 : undefined\n });\n const parser = serialization.makeUnsafe();\n const requestIds = [];\n const offer = data => typeof data === \"string\" ? Queue.offer(queue, encoder.encode(data)) : Queue.offer(queue, data);\n const client = {\n write: !includesFraming ? response =>\n // buffered responses cannot carry notifications, so they are dropped\n response._tag === \"Request\" && response.isNotification === true ? Effect.void : Queue.offer(queue, response) : response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) return Effect.void;\n return offer(encoded);\n } catch (cause) {\n return offer(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause))));\n }\n },\n end: Effect.andThen(Queue.end(queue), Queue.flush(queue))\n };\n // Ends an unfinished response, failing it with `cause` when given, and interrupts its requests.\n const terminate = cause => Effect.suspend(() => {\n if (queue.state._tag === \"Done\") return Effect.void;\n if (cause) Queue.failCauseUnsafe(queue, cause);\n Queue.shutdownUnsafe(queue);\n return Effect.forEach(requestIds, requestId => writeRequest(id, {\n _tag: \"Interrupt\",\n requestId\n }), {\n discard: true\n });\n });\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n Queue.offerUnsafe(disconnects, id);\n return terminate();\n });\n clients.set(id, client);\n clientIds.add(id);\n const dispatch = Effect.gen(function* () {\n // @effect-diagnostics-next-line tryCatchInEffectGen:off\n try {\n const decoded = parser.decode(data);\n for (let i = 0; i < decoded.length; i++) {\n const message = decoded[i];\n if (message._tag === \"Request\") {\n requestIds.push(RequestId(message.id));\n message.headers = requestHeaders.concat(message.headers);\n }\n yield* writeRequest(id, message);\n }\n } catch (cause) {\n yield* client.write(ResponseDefectEncoded(encodeDefectUnsafe(cause)));\n }\n yield* writeRequest(id, constEof);\n });\n if (!includesFraming) {\n yield* dispatch;\n // Allow request aborts during response waits without unmasking response construction.\n const responses = yield* Effect.interruptible(Queue.collect(queue));\n // Notification-only batches encode without a response body.\n const encoded = parser.encode(responses);\n return HttpServerResponse.text(encoded === undefined ? \"\" : encoded, {\n contentType: serialization.contentType\n });\n }\n // Dispatch concurrently so the bounded queue can drain; a failed dispatch fails the response.\n yield* Effect.forkIn(Effect.onError(dispatch, terminate), scope, {\n startImmediately: true\n });\n const initialChunk = yield* Effect.interruptible(Pull.catchDone(Queue.takeAll(queue), () => Effect.succeed([])));\n if (queue.state._tag === \"Done\") {\n // A failed dispatch may have completed the queue after the initial chunk was taken.\n yield* Pull.doneExitFromCause(queue.state.exit.cause);\n return HttpServerResponse.uint8Array(initialChunk.length === 1 ? initialChunk[0] : Bytes.concat(initialChunk), {\n contentType: serialization.contentType\n });\n }\n return HttpServerResponse.stream(Stream.fromArray(initialChunk).pipe(Stream.concat(Stream.fromQueue(queue))), {\n contentType: serialization.contentType\n });\n });\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send(clientId, response) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.write(response);\n },\n end(clientId) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.end;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: false,\n supportsTransferables: false,\n supportsSpanPropagation: false,\n supportsNotifications: includesFraming,\n codecFor: serialization.codecFor\n });\n });\n return {\n protocol,\n httpEffect\n };\n});\n/**\n * Creates an HTTP server `Protocol` and registers its request handler as a POST\n * route on the current `HttpRouter`.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect(options);\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"POST\", options.path, httpEffect);\n return protocol;\n});\n/**\n * Provides a server `Protocol` that uses HTTP POST requests for RPC\n * communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => {\n return Layer.effect(Protocol)(makeProtocolHttp(options));\n};\n/**\n * Starts an RPC server for a group and returns the HTTP request/response effect\n * that serves the non-websocket HTTP RPC protocol.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect(options);\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Starts an RPC server for a group and returns the HTTP effect that upgrades\n * requests to the websocket RPC protocol.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffectWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Creates a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * **Details**\n *\n * The protocol serves a single client with id `0`. When stdout ends, the\n * fiber that created the protocol is interrupted.\n *\n * `onStdinEnd` controls what happens when stdin ends. With `\"drain\"`, the\n * default, in-flight requests run to completion and their responses are\n * written before stdout ends. With `\"interrupt\"`, queued output is flushed\n * and stdout ends, stopping the server and interrupting in-flight requests.\n * Shutdown waits for their finalizers without sending further responses or\n * remote cancellation notifications. This stops the server rather than\n * reporting a client disconnect, so `onDisconnect` is not called.\n *\n * **Gotchas**\n *\n * With `\"drain\"`, a request that never completes, such as a long-running\n * tool call, keeps stdout open and the process alive after stdin ends.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolStdio = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const stdio = yield* Stdio;\n const fiber = Fiber.getCurrent();\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n return yield* Protocol.make(Effect.fnUntraced(function* (writeRequest) {\n const queue = yield* Queue.bounded(8);\n const errors = [];\n const parser = serialization.makeUnsafe({\n onDecodeError: error => errors.push(error)\n });\n const write = response => {\n const encoded = parser.encode(response);\n return encoded === undefined ? Effect.void : Queue.offer(queue, encoded);\n };\n yield* stdio.stdin.pipe(Stream.runForEach(data => {\n let decoded = [];\n try {\n decoded = parser.decode(data);\n } catch (cause) {\n errors.push(cause);\n }\n let i = 0;\n const requests = decoded.length === 0 ? Effect.void : Effect.whileLoop({\n while: () => i < decoded.length,\n body: () => writeRequest(0, decoded[i++]),\n step: constVoid\n });\n if (errors.length === 0) return requests;\n // Answer decode failures instead of failing, which would resubscribe to stdin and lose input.\n return Effect.andThen(Effect.forEach(errors.splice(0), error => write(ResponseDefectEncoded(encodeDefectUnsafe(error))), {\n discard: true\n }), requests);\n }), Effect.sandbox, Effect.tapError(Effect.logError), Effect.retry(Schedule.spaced(500)), Effect.andThen(() => options?.onStdinEnd === \"interrupt\" ? Queue.end(queue) : writeRequest(0, constEof)), Effect.forkScoped);\n yield* Stream.fromQueue(queue).pipe(Stream.run(stdio.stdout()), Effect.retry(Schedule.spaced(500)), Effect.onExit(exit => {\n if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return Effect.void;\n return Effect.forkDetach(Exit.isSuccess(exit) ? Fiber.interruptAs(fiber, undefined, Context.make(Runtime.InterruptExitCode, 0)) : Fiber.interrupt(fiber), {\n startImmediately: true\n });\n }), Effect.forkScoped);\n return {\n disconnects: yield* Queue.make(),\n send: (_clientId, response) => write(response),\n end(_clientId) {\n return Queue.end(queue);\n },\n clientIds: Effect.succeed(new Set([0])),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n codecFor: serialization.codecFor\n };\n }));\n});\n/**\n * Provides a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * **Details**\n *\n * `onStdinEnd` selects whether in-flight requests are drained (the default)\n * or interrupted when stdin ends. See {@link makeProtocolStdio} for the\n * shutdown sequence of each mode.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolStdio = options => Layer.effect(Protocol, makeProtocolStdio(options));\n/**\n * Creates a server `Protocol` backed by `WorkerRunnerPlatform`, routing worker\n * messages to the RPC server and server responses back to workers.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorkerRunner = /*#__PURE__*/Protocol.make(/*#__PURE__*/Effect.fnUntraced(function* (writeRequest) {\n const fiber = Fiber.getCurrent();\n const runner = yield* WorkerRunner.WorkerRunnerPlatform;\n const backing = yield* runner.start();\n const initialMessage = yield* Deferred.make();\n const clientIds = new Set();\n const disconnects = yield* Queue.make();\n yield* backing.run((clientId, message) => {\n clientIds.add(clientId);\n if (message._tag === \"InitialMessage\") {\n return Deferred.succeed(initialMessage, message.value);\n }\n return writeRequest(clientId, message);\n }).pipe(Effect.tapCause(Effect.logError), Effect.onExit(() => Effect.sync(() => {\n fiber.currentDispatcher.scheduleTask(() => fiber.interruptUnsafe(fiber.id), 0);\n })), Effect.forkScoped);\n if (backing.disconnects) {\n yield* Queue.take(backing.disconnects).pipe(Effect.tap(clientId => {\n clientIds.delete(clientId);\n return Queue.offer(disconnects, clientId);\n }), Effect.forever, Effect.forkScoped);\n }\n return {\n disconnects,\n send: backing.send,\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.asSome(Deferred.await(initialMessage)),\n supportsAck: true,\n supportsTransferables: true,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n // Worker protocols use structured clone, so they do not depend on\n // `RpcSerialization`. A binary worker protocol is a separate protocol.\n codecFor: Schema.toCodecJson\n };\n}));\n/**\n * Provides a server `Protocol` backed by the current `WorkerRunnerPlatform`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWorkerRunner = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolWorkerRunner);\n// internal\nconst makeSocketProtocol = /*#__PURE__*/Effect.gen(function* () {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n const disconnects = yield* Queue.make();\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n let writeRequest;\n const onSocket = Effect.fnUntraced(function* (socket, headers) {\n const scope = yield* Effect.scope;\n const parser = serialization.makeUnsafe();\n const id = clientId++;\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n return Queue.offer(disconnects, id);\n });\n const writer = yield* socket.writer;\n const write = response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) {\n return Effect.void;\n }\n return Effect.orDie(writer.write(encoded));\n } catch (cause) {\n return Effect.orDie(writer.write(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause)))));\n }\n };\n clients.set(id, {\n write\n });\n clientIds.add(id);\n const processData = data => {\n try {\n const decoded = parser.decode(data);\n if (decoded.length === 0) return Effect.void;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < decoded.length,\n body() {\n const message = decoded[i++];\n if (message._tag === \"Request\" && headers) {\n ;\n message.headers = headers.concat(message.headers);\n }\n return writeRequest(id, message);\n },\n step: constVoid\n });\n } catch (cause) {\n if (Predicate.isTagged(cause, \"MaxBufferSizeExceeded\")) {\n return writer.write(new Socket.CloseEvent(1009, String(cause)));\n }\n return writer.write(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause))));\n }\n };\n yield* Effect.gen(function* () {\n const {\n pull\n } = yield* socket.reader;\n while (true) {\n const frames = yield* pull;\n for (let i = 0; i < frames.length; i++) {\n yield* processData(frames[i]);\n }\n }\n }).pipe(Effect.catchReason(\"SocketError\", \"SocketCloseError\", _ => Effect.void), Effect.orDie);\n });\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send: (clientId, response) => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return Effect.orDie(client.write(response));\n },\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n codecFor: serialization.codecFor\n });\n });\n return {\n protocol,\n onSocket\n };\n});\n//# sourceMappingURL=RpcServer.js.map","/**\n * Node socket server adapters for Effect's unstable socket server API.\n *\n * This module turns `node:net` TCP or Unix-domain servers, `node:tls` servers,\n * and `ws` WebSocket servers into scoped `SocketServer.SocketServer` services.\n * Use the TCP and TLS constructors when handlers should receive a\n * `Socket.Socket` backed by a Node `net.Socket`; use the WebSocket\n * constructors when handlers should receive a `Socket.Socket` backed by `ws`\n * and have access to the per-connection WebSocket and `IncomingMessage`\n * services.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { pipe } from \"effect/Function\";\nimport * as Function from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as NetAddress from \"effect/net/NetAddress\";\nimport * as Scope from \"effect/Scope\";\nimport * as Socket from \"effect/socket/Socket\";\nimport * as SocketServer from \"effect/socket/SocketServer\";\nimport * as Net from \"node:net\";\nimport * as Tls from \"node:tls\";\nimport * as NodeSocket from \"./NodeSocket.js\";\nimport * as NodeWS from \"./NodeWS.js\";\nconst isDeno = \"Deno\" in globalThis;\nconst socketAddressFromNode = address => typeof address === \"string\" ? Effect.succeed(NetAddress.unixPathAddress(address)) : Effect.fromResult(NetAddress.inetAddressFromIpString(address.address, address.port)).pipe(Effect.mapError(cause => new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause\n })\n})));\n/**\n * Service tag for the Node `IncomingMessage` associated with the current\n * WebSocket server connection.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class IncomingMessage extends /*#__PURE__*/Context.Service()(\"@effect/platform-node-shared/NodeSocketServer/IncomingMessage\") {}\n/**\n * Creates a scoped TCP `SocketServer` from a Node `net.Server`, starts\n * listening with the supplied options, queues pending connections until `run`\n * is called, and closes the server when the scope ends.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => makeNetServer({\n listenOptions: options,\n connectionEvent: \"connection\",\n createServer: () => Net.createServer(options)\n});\n/**\n * Provides a TCP `SocketServer` by creating and managing a scoped Node\n * `net.Server` with the supplied server and listen options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Function.flow(make, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\n/**\n * Creates a scoped TLS `SocketServer` from a Node `tls.Server`, starts\n * listening with the supplied options, queues pending connections until `run`\n * is called, and closes the server when the scope ends.\n *\n * **Details**\n *\n * Connections reach `run` only once their handshake has completed, and the\n * handler receives a `Socket.Socket` backed by the `tls.TLSSocket`, which is\n * also provided as `NodeSocket.NetSocket`. Connections that fail the handshake\n * are destroyed and the server keeps listening.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeTls = options => makeNetServer({\n listenOptions: options,\n connectionEvent: \"secureConnection\",\n createServer: () => {\n const server = Tls.createServer(options);\n server.on(\"tlsClientError\", (_error, socket) => {\n socket.destroy();\n });\n return server;\n }\n});\n/**\n * Provides a TLS `SocketServer` by creating and managing a scoped Node\n * `tls.Server` with the supplied TLS and listen options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerTls = /*#__PURE__*/Function.flow(makeTls, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\n/**\n * Creates a scoped WebSocket `SocketServer` backed by the `ws` package,\n * providing the WebSocket and its Node `IncomingMessage` to connection\n * handlers and closing the server when the scope ends.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWebSocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const pendingConnections = new Map();\n const server = yield* Effect.acquireRelease(Effect.sync(() => new NodeWS.WebSocketServer(options)), server => Effect.callback(resume => {\n pendingConnections.forEach(([, remove], conn) => {\n remove();\n conn.terminate();\n });\n server.close(() => resume(Effect.void));\n }));\n function defaultHandler(conn, req) {\n const remove = () => {\n pendingConnections.delete(conn);\n conn.removeEventListener(\"close\", remove);\n };\n pendingConnections.set(conn, [req, remove]);\n conn.addEventListener(\"close\", remove);\n }\n let onConnection = defaultHandler;\n server.on(\"connection\", (conn, req) => {\n // pause immediately so nothing is dropped before a handler acquires the\n // socket's reader\n conn.pause();\n onConnection(conn, req);\n });\n yield* Effect.callback(resume => {\n server.once(\"error\", error => {\n resume(Effect.fail(new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause: error\n })\n })));\n });\n server.once(\"listening\", () => {\n resume(Effect.void);\n });\n });\n const run = Effect.fnUntraced(function* (handler) {\n const scope = yield* Scope.make();\n const services = Context.omit(Scope.Scope)(yield* Effect.context());\n const trackFiber = Fiber.runIn(scope);\n const prevOnConnection = onConnection;\n onConnection = function (conn, req) {\n let context = services;\n context = Context.add(context, IncomingMessage, req);\n context = Context.add(context, Socket.WebSocket, conn);\n pipe(Socket.fromWebSocket(Effect.acquireRelease(Effect.succeed(conn), conn => Effect.sync(() => {\n conn.close();\n })), {\n disableReconnects: true\n }), Effect.flatMap(handler), Effect.ignoreCause({\n log: \"Unhandled\",\n message: \"Unhandled error in SocketServer\"\n }), Effect.runForkWith(context), trackFiber);\n };\n pendingConnections.forEach(([req, remove], conn) => {\n remove();\n onConnection(conn, req);\n });\n return yield* Effect.callback(_resume => {\n return Effect.sync(() => {\n onConnection = prevOnConnection;\n });\n }).pipe(Effect.ensuring(Scope.close(scope, Exit.void)));\n });\n const boundAddress = yield* socketAddressFromNode(server.address());\n return SocketServer.SocketServer.of({\n address: boundAddress,\n run\n });\n});\n/**\n * Provides a WebSocket `SocketServer` backed by the `ws` package and managed\n * with the supplied server options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWebSocket = /*#__PURE__*/Function.flow(makeWebSocket, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\nconst makeNetServer = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const errorDeferred = Deferred.makeUnsafe();\n const pending = new Map();\n function defaultOnConnection(conn) {\n const remove = () => {\n pending.delete(conn);\n conn.off(\"close\", remove);\n conn.off(\"error\", remove);\n };\n pending.set(conn, remove);\n conn.on(\"close\", remove);\n conn.on(\"error\", remove);\n }\n let onConnection = defaultOnConnection;\n // oxlint-disable-next-line prefer-const\n let server;\n yield* Effect.addFinalizer(() => Effect.callback(resume => {\n pending.forEach((remove, conn) => {\n remove();\n conn.destroy();\n });\n server?.close(() => resume(Effect.void));\n }));\n server = options.createServer();\n server.on(options.connectionEvent, conn => {\n // pause immediately so nothing is dropped before a handler acquires the\n // socket's reader. Deno's node:net compatibility layer leaves the socket\n // non-flowing but breaks `readable` events after an explicit pause.\n if (!isDeno) conn.pause();\n onConnection(conn);\n });\n server.on(\"error\", err => Deferred.doneUnsafe(errorDeferred, Exit.fail(err)));\n yield* Effect.callback(resume => {\n server.listen(options.listenOptions, () => resume(Effect.void));\n }).pipe(Effect.raceFirst(Effect.mapError(Deferred.await(errorDeferred), err => new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause: err\n })\n }))));\n const run = Effect.fnUntraced(function* (handler) {\n const scope = yield* Scope.make();\n const services = Context.omit(Scope.Scope)(yield* Effect.context());\n const trackFiber = Fiber.runIn(scope);\n const prevOnConnection = onConnection;\n onConnection = function (conn) {\n let error;\n conn.on(\"error\", err => {\n error = err;\n });\n pipe(NodeSocket.fromDuplex(Effect.acquireRelease(Effect.suspend(() => {\n if (error) {\n return Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketOpenError({\n kind: \"Unknown\",\n cause: error\n })\n }));\n } else if (conn.closed) {\n return Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketCloseError({\n code: 1000\n })\n }));\n }\n return Effect.succeed(conn);\n }), conn => Effect.sync(() => {\n if (conn.closed === false) {\n conn.destroySoon();\n }\n })), {\n tlsServer: true,\n disableReconnects: true\n }), Effect.flatMap(handler), Effect.ignoreCause({\n log: \"Unhandled\",\n message: \"Unhandled error in SocketServer\"\n }), Effect.runForkWith(Context.add(services, NodeSocket.NetSocket, conn)), trackFiber);\n };\n pending.forEach((remove, conn) => {\n remove();\n onConnection(conn);\n });\n return yield* Effect.callback(_resume => {\n return Effect.suspend(() => {\n onConnection = prevOnConnection;\n return Scope.close(scope, Exit.void);\n });\n });\n });\n const boundAddress = yield* socketAddressFromNode(server.address());\n return SocketServer.SocketServer.of({\n address: boundAddress,\n run\n });\n});\n//# sourceMappingURL=NodeSocketServer.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n fiber,\n teardown\n}) => {\n let receivedSignal = false;\n fiber.addObserver(exit => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigint);\n teardown(exit, code => {\n if (receivedSignal || code !== 0) {\n process.exit(code);\n }\n });\n });\n function onSigint() {\n receivedSignal = true;\n fiber.interruptUnsafe(fiber.id);\n }\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","import { Context } from \"effect\";\nimport type { Effect } from \"effect\";\n\nimport type {\n EmbedPayload,\n ModelKey,\n ModelServerError,\n Vectors,\n} from \"#/shared/api/model-server/index.ts\";\n\nexport class Engine extends Context.Service<\n Engine,\n {\n readonly load: (key: ModelKey) => Effect.Effect<void, ModelServerError>;\n readonly embed: (payload: EmbedPayload) => Effect.Effect<Vectors, ModelServerError>;\n }\n>()(\"@r_masseater/masseater-utils/entities/model-engine/model/engine\") {}\n","","","import { Effect, FileSystem, Hash, Path, Schema } from \"effect\";\nimport type { PlatformError } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nimport runtimeLock from \"./runtime-lock.json\" with { type: \"json\" };\nimport runtimeManifest from \"./runtime-manifest.json\" with { type: \"json\" };\n\nconst READY_MARKER = \".ready\";\nconst SUCCESS = 0;\nconst HEX = 16;\n\n/** @internal */\nexport type Services = FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner;\n/** @internal */\nexport type Failure = ModelServerError | PlatformError.PlatformError | Schema.SchemaError;\n\nconst encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Json));\n\nconst npmCi = (directory: string): ChildProcess.Command =>\n ChildProcess.make(\"npm\", [\"ci\", \"--ignore-scripts\", \"--no-audit\", \"--no-fund\"], {\n cwd: directory,\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"inherit\",\n });\n\nconst writeManifests = Effect.fnUntraced(function* writeManifests(staging: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const manifest = yield* encodeJson(runtimeManifest);\n const lock = yield* encodeJson(runtimeLock);\n yield* fs.remove(staging, { recursive: true, force: true });\n yield* fs.makeDirectory(staging, { recursive: true });\n yield* fs.writeFileString(path.join(staging, \"package.json\"), manifest);\n yield* fs.writeFileString(path.join(staging, \"package-lock.json\"), lock);\n});\n\nconst install = Effect.fnUntraced(function* install(\n staging: string,\n): Effect.fn.Return<void, Failure, Services> {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n yield* writeManifests(staging);\n yield* spawner.exitCode(npmCi(staging)).pipe(\n Effect.filterOrFail(\n (code) => code === SUCCESS,\n (code) => ModelServerError.make({ message: `npm ci exited with ${code} in ${staging}` }),\n ),\n );\n yield* fs.writeFileString(path.join(staging, READY_MARKER), \"\");\n});\n\nconst runtimeDirectory = Effect.fnUntraced(function* runtimeDirectory(cache: string) {\n const path = yield* Path.Path;\n const lock = yield* encodeJson(runtimeLock);\n return path.join(cache, \"runtime\", Hash.string(lock).toString(HEX));\n});\n\nconst installInto = Effect.fnUntraced(function* installInto(directory: string) {\n const fs = yield* FileSystem.FileSystem;\n const staging = `${directory}.staging-${globalThis.process.pid}`;\n yield* install(staging);\n yield* fs.remove(directory, { recursive: true, force: true });\n yield* fs.rename(staging, directory);\n});\n\n/** @internal */\nexport const ensureRuntime = Effect.fnUntraced(function* ensureRuntime(\n cache: string,\n): Effect.fn.Return<string, Failure, Services> {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = yield* runtimeDirectory(cache);\n const ready = yield* fs.exists(path.join(directory, READY_MARKER));\n if (!ready) {\n yield* installInto(directory);\n }\n return directory;\n});\n","import { Cache, Duration, Effect, Exit, Layer, Path, Predicate, Schema } from \"effect\";\n\nimport { Engine } from \"#/entities/model-engine/index.ts\";\nimport { ModelServerError, VectorsSchema, modelName } from \"#/shared/api/model-server/index.ts\";\nimport type { EmbedPayload, ModelKey, Vectors } from \"#/shared/api/model-server/index.ts\";\n\nimport { ensureRuntime } from \"./runtime.ts\";\nimport type { Services } from \"./runtime.ts\";\n\nconst ENTRY = \"node_modules/@huggingface/transformers/dist/transformers.node.mjs\";\nconst MODEL_CAPACITY = 4;\nconst LIBRARY_CAPACITY = 1;\nconst LIBRARY_KEY = \"transformers\";\n\ninterface Tensor {\n readonly tolist: () => unknown;\n}\n\ninterface TokenizeOptions {\n readonly padding: boolean;\n readonly truncation: boolean;\n readonly max_length: number;\n}\n\ntype Tokenize = (texts: readonly string[], options: TokenizeOptions) => unknown;\n\ntype Run = (inputs: unknown) => Promise<{ readonly sentence_embedding?: Tensor }>;\n\ninterface ModelOptions {\n readonly config: object;\n readonly device: string;\n readonly dtype: string;\n}\n\ninterface Transformers {\n readonly env: object;\n readonly AutoConfig: { readonly from_pretrained: (model: string) => Promise<object> };\n readonly AutoModel: {\n readonly from_pretrained: (model: string, options: ModelOptions) => Promise<Run>;\n };\n readonly AutoTokenizer: { readonly from_pretrained: (model: string) => Promise<Tokenize> };\n}\n\ninterface Loaded {\n readonly run: Run;\n readonly tokenize: Tokenize;\n}\n\nconst isTransformers = (value: unknown): value is Transformers =>\n Predicate.hasProperty(value, \"env\") &&\n Predicate.hasProperty(value, \"AutoConfig\") &&\n Predicate.hasProperty(value, \"AutoModel\") &&\n Predicate.hasProperty(value, \"AutoTokenizer\");\n\nconst failure =\n (doing: string) =>\n (cause: unknown): ModelServerError =>\n ModelServerError.make({ message: `${doing} failed: ${String(cause)}` });\n\nconst attempt = <Value>(\n doing: string,\n run: () => Promise<Value>,\n): Effect.Effect<Value, ModelServerError> => Effect.tryPromise({ try: run, catch: failure(doing) });\n\nconst keepSuccess = (exit: Exit.Exit<unknown, unknown>): Duration.Duration =>\n Exit.match(exit, { onFailure: () => Duration.zero, onSuccess: () => Duration.infinity });\n\nconst importModule = (href: string): Promise<unknown> => import(href);\n\nconst importLibrary = Effect.fnUntraced(function* importLibrary(cache: string) {\n const path = yield* Path.Path;\n const directory = yield* ensureRuntime(cache).pipe(\n Effect.mapError(failure(\"installing the runtime\")),\n );\n const url = yield* path\n .toFileUrl(path.join(directory, ENTRY))\n .pipe(Effect.mapError(failure(\"locating the runtime\")));\n const loaded = yield* attempt(\"importing the runtime\", () => importModule(url.href));\n if (!isTransformers(loaded)) {\n return yield* ModelServerError.make({ message: `${ENTRY} is not transformers.js` });\n }\n Reflect.set(loaded.env, \"cacheDir\", path.join(cache, \"models\"));\n return loaded;\n});\n\nconst textOnly = (config: object): object => {\n Reflect.set(config, \"vision_config\", false);\n Reflect.set(config, \"audio_config\", false);\n return config;\n};\n\nconst loadModel = Effect.fnUntraced(function* loadModel(library: Transformers, key: ModelKey) {\n const config = yield* attempt(\"reading the config\", () =>\n library.AutoConfig.from_pretrained(key.model),\n );\n const options = { config: textOnly(config), device: \"cpu\", dtype: key.dtype };\n const [run, tokenize] = yield* Effect.all(\n [\n attempt(`loading ${modelName(key)}`, () =>\n library.AutoModel.from_pretrained(key.model, options),\n ),\n attempt(\"loading the tokenizer\", () => library.AutoTokenizer.from_pretrained(key.model)),\n ],\n { concurrency: \"unbounded\" },\n );\n return { run, tokenize } satisfies Loaded;\n});\n\nconst decodeVectors = Schema.decodeUnknownEffect(VectorsSchema);\n\nconst embedWith = Effect.fnUntraced(function* embedWith(\n loaded: Loaded,\n payload: EmbedPayload,\n): Effect.fn.Return<Vectors, ModelServerError> {\n const options = { padding: true, truncation: true, max_length: payload.maxTokens };\n const inputs = yield* Effect.try({\n try: () => loaded.tokenize(payload.texts, options),\n catch: failure(\"tokenizing\"),\n });\n const output = yield* attempt(\"embedding\", () => loaded.run(inputs));\n if (!Predicate.isNotUndefined(output.sentence_embedding)) {\n return yield* ModelServerError.make({\n message: `${payload.model} returns no sentence_embedding`,\n });\n }\n return yield* decodeVectors(output.sentence_embedding.tolist()).pipe(\n Effect.mapError(failure(\"reading the embeddings\")),\n );\n});\n\nconst makeEngine = Effect.fnUntraced(function* makeEngine(cache: string) {\n const libraries = yield* Cache.makeWith(\n (key: typeof LIBRARY_KEY) =>\n importLibrary(cache).pipe(Effect.withSpan(\"model-server.runtime\", { attributes: { key } })),\n { capacity: LIBRARY_CAPACITY, timeToLive: keepSuccess, requireServicesAt: \"construction\" },\n );\n const models = yield* Cache.makeWith(\n (key: ModelKey) =>\n Cache.get(libraries, LIBRARY_KEY).pipe(Effect.flatMap((library) => loadModel(library, key))),\n { capacity: MODEL_CAPACITY, timeToLive: keepSuccess },\n );\n const loaded = ({ model, dtype }: ModelKey): Effect.Effect<Loaded, ModelServerError> =>\n Cache.get(models, { model, dtype });\n return Engine.of({\n load: (key) => Effect.asVoid(loaded(key)),\n embed: (payload) => loaded(payload).pipe(Effect.flatMap((model) => embedWith(model, payload))),\n });\n});\n\n/** @internal */\nexport const transformersEngine = (cache: string): Layer.Layer<Engine, never, Services> =>\n Layer.effect(Engine, makeEngine(cache));\n","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Fetch-based implementation of the Effect HTTP client service.\n *\n * This module provides an `HttpClient` layer that executes requests through a\n * Web Fetch API implementation. It is the transport to use in browsers, edge\n * runtimes, and Node.js environments where `globalThis.fetch` is available, or\n * anywhere a compatible fetch function can be supplied.\n *\n * Requests with an `Upgrade` header fail with `TransportError` before anything\n * is sent because fetch cannot hand over the connection.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpClient from \"./HttpClient.js\";\nimport * as HttpClientError from \"./HttpClientError.js\";\nimport * as HttpClientResponse from \"./HttpClientResponse.js\";\n/**\n * Context reference for the `fetch` implementation used by the fetch-based HTTP client.\n *\n * **Details**\n *\n * Defaults to `globalThis.fetch`. When not explicitly provided in context,\n * `FetchHttpClient` uses the current `globalThis.fetch` on each request.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Fetch = /*#__PURE__*/Context.Reference(\"effect/http/FetchHttpClient/Fetch\", {\n defaultValue: () => globalThis.fetch\n});\n/**\n * Context reference controlling stream bodies when the runtime does not support streaming requests.\n *\n * **Details**\n *\n * Defaults to `\"error\"`, which fails with an `EncodeError` without sending the\n * request. Set to `\"buffer\"` to collect the entire stream in memory and send it\n * as a single body instead. Runtimes with streaming support always send the stream.\n *\n * **Gotchas**\n *\n * Buffering keeps the entire upload in memory and can exhaust memory for large\n * or unbounded uploads. Support is detected once, on the first stream body sent,\n * using the global `Request` implementation even when a custom `Fetch` is provided.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const StreamBodyFallback = /*#__PURE__*/Context.Reference(\"effect/http/FetchHttpClient/StreamBodyFallback\", {\n defaultValue: () => \"error\"\n});\n/**\n * Service that contains default fetch options for the fetch-based HTTP client.\n *\n * **When to use**\n *\n * Use to provide default credentials, cache, redirect, integrity, or other\n * fetch options for outgoing HTTP requests.\n *\n * **Details**\n *\n * Request-specific method, headers, body, and abort signal are supplied by the client when a request is executed.\n *\n * @see {@link HttpClient.followRedirects} for following redirects in the client, which needs `{ redirect: \"manual\" }` here\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class RequestInit extends /*#__PURE__*/Context.Service()(\"effect/http/FetchHttpClient/RequestInit\") {}\n// https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests\nlet supportsStreamBody;\nconst detectStreamBodySupport = () => {\n try {\n let duplexAccessed = false;\n const body = new ReadableStream();\n const request = new Request(\"https://example.com\", {\n method: \"POST\",\n body,\n get duplex() {\n duplexAccessed = true;\n return \"half\";\n }\n });\n // Bun and Deno preserve the stream without reading the duplex option.\n return (duplexAccessed || request.body === body) && !request.headers.has(\"Content-Type\");\n } catch {\n return false;\n }\n};\nconst fetch = /*#__PURE__*/HttpClient.make((request, url, signal, fiber) => {\n if (request.headers.upgrade !== undefined) {\n return Effect.fail(new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n description: \"fetch cannot send an HTTP upgrade request\"\n })\n }));\n }\n const fetch = Context.getOrUndefined(fiber.context, Fetch);\n const options = Context.getOrUndefined(fiber.context, RequestInit) ?? {};\n let headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;\n if (headers[\"content-length\"]) {\n headers = Headers.remove(headers, \"content-length\");\n }\n let uploadController;\n const stopUpload = Effect.sync(() => uploadController?.abort());\n const send = body => Effect.map(Effect.tryPromise({\n try: () => {\n const init = {\n ...options,\n method: request.method,\n headers,\n body,\n duplex: typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream ? \"half\" : undefined,\n signal: uploadController ? AbortSignal.any([signal, uploadController.signal]) : signal\n };\n return fetch ? fetch(url, init) : globalThis.fetch(url, init);\n },\n catch: cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n cause\n })\n })\n }), response => {\n const original = HttpClientResponse.fromWeb(request, response);\n if (!uploadController) return original;\n if (response.body === null) uploadController.abort();\n // Finishing or releasing either response reader ends the upload, not\n // merely receiving headers. Keep the original response and its caches,\n // and inherit its Web source so `toWeb` hands over the original body.\n return Object.create(original, {\n ...Object.fromEntries([\"arrayBuffer\", \"text\", \"json\", \"formData\", \"urlParamsBody\"].map(key => [key, {\n get: () => Effect.ensuring(original[key], stopUpload)\n }])),\n stream: {\n get: () => Stream.ensuring(original.stream, stopUpload)\n }\n });\n }).pipe(Effect.onError(() => stopUpload));\n switch (request.body._tag) {\n case \"Raw\":\n case \"Uint8Array\":\n return send(request.body.body);\n case \"FormData\":\n return send(request.body.formData);\n case \"Stream\":\n {\n supportsStreamBody ??= detectStreamBodySupport();\n if (supportsStreamBody) {\n uploadController = new AbortController();\n const uploadSignal = AbortSignal.any([signal, uploadController.signal]);\n const stopped = Effect.callback(resume => {\n const onAbort = () => resume(Effect.interrupt);\n if (uploadSignal.aborted) {\n onAbort();\n return;\n }\n uploadSignal.addEventListener(\"abort\", onAbort, {\n once: true\n });\n return Effect.sync(() => uploadSignal.removeEventListener(\"abort\", onAbort));\n });\n return Effect.flatMap(Stream.toReadableStreamEffect(Stream.interruptWhen(request.body.stream, stopped)), send);\n }\n if (fiber.getRef(StreamBodyFallback) === \"error\") {\n return Effect.fail(new HttpClientError.HttpClientError({\n reason: new HttpClientError.EncodeError({\n request,\n description: \"Streaming request bodies are not supported in this runtime\"\n })\n }));\n }\n return Stream.mkArrayBuffer(request.body.stream).pipe(Effect.mapError(cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.EncodeError({\n request,\n cause\n })\n })), Effect.flatMap(send));\n }\n }\n return send(undefined);\n});\n/**\n * Layer that provides an `HttpClient` implementation backed by the configured\n * `Fetch` function.\n *\n * **When to use**\n *\n * Use when an Effect program should execute `HttpClient` requests through the\n * platform `fetch` implementation, especially in browser, edge, or Node.js\n * runtimes with `globalThis.fetch`.\n *\n * **Details**\n *\n * The layer uses the current `Fetch` reference and optional `RequestInit`\n * service for each request. Request-specific method, headers, body, and abort\n * signal are supplied by the client and override matching `RequestInit` fields.\n *\n * **Gotchas**\n *\n * Fetch behavior comes from the runtime's implementation, so CORS, cookies,\n * redirects, abort handling, and streaming support can vary by platform.\n * `fetch` follows redirects itself by default, so `HttpClient.followRedirects`\n * has no effect unless `RequestInit` sets `redirect: \"manual\"`. Trace\n * propagation is on by default, and a browser preflight fails unless the\n * target allows `b3` and `traceparent`. Stream request bodies are sent as Web\n * streams with `duplex: \"half\"` when the runtime supports it; see\n * `StreamBodyFallback` for the unsupported case. Any `content-length` header is\n * removed before calling `fetch`. Chrome passes the support check but rejects\n * streaming uploads over HTTP/1.1, which surfaces as a `TransportError`, and\n * browsers only deliver the response after the entire request body has been sent.\n *\n * @see {@link Fetch} for supplying the fetch implementation used by this layer\n * @see {@link RequestInit} for default `RequestInit` options applied before request-specific fields\n * @see {@link StreamBodyFallback} for opting into buffering on unsupported runtimes\n * @see {@link HttpClient.TracerPropagationEnabled} for leaving `b3` and `traceparent` off a browser request\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/HttpClient.layerMergedContext(/*#__PURE__*/Effect.succeed(fetch));\n//# sourceMappingURL=FetchHttpClient.js.map","import * as Config from \"../../Config.js\";\nimport * as Schema from \"../../Schema.js\";\nconst exporterList = path => Config.Array(Schema.String, path).pipe(Config.map(_ => _.map(_ => _.toLowerCase().trim()).filter(_ => _ !== \"\")));\nconst headersRecord = path => Config.Record(Schema.String, Schema.StringFromUriComponent, path);\nexport const headers = signal => headersRecord(`OTEL_EXPORTER_OTLP_${signal}_HEADERS`).pipe(Config.orElse(() => headersRecord(\"OTEL_EXPORTER_OTLP_HEADERS\")), Config.withDefault(undefined));\nexport const endpoint = signal => Config.URL(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`).pipe(Config.orElse(() => Config.URL(\"OTEL_EXPORTER_OTLP_ENDPOINT\").pipe(Config.map(url => {\n const slash = url.pathname.endsWith(\"/\") ? \"\" : \"/\";\n url.pathname += `${slash}v1/${signal.toLowerCase()}`;\n return url;\n}))), Config.withDefault(undefined));\nexport const exporters = signal => exporterList(`OTEL_${signal}_EXPORTER`).pipe(Config.withDefault([]));\n//# sourceMappingURL=otlpEnv.js.map","/**\n * Shared batch exporter for OTLP/HTTP observability modules.\n *\n * Signal modules use this exporter to buffer already-encoded telemetry and post\n * it to a configured OTLP endpoint. It owns the scoped transport loop, batching,\n * retry behavior, temporary disabling after repeated failures, and final flush\n * during shutdown.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport { Clock } from \"../Clock.js\";\nimport * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport { identity } from \"../Function.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpClient from \"../http/HttpClient.js\";\nimport * as HttpClientError from \"../http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Count from \"../internal/count.js\";\nimport * as Latch from \"../Latch.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as MutableList from \"../MutableList.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Version from \"../Version.js\";\n// A missing or invalid Retry-After falls back to a fixed delay.\nconst retryAfterDelay = value => {\n const retryAfter = value === undefined ? undefined : Headers.parseRetryAfter(value);\n if (retryAfter === undefined || Result.isFailure(retryAfter)) {\n return Effect.succeed(Duration.seconds(5));\n }\n return Effect.map(Clock, clock => Headers.retryAfterDelay(retryAfter.success, clock.currentTimeMillisUnsafe()));\n};\nconst policy = /*#__PURE__*/Schedule.forever.pipe(Schedule.passthrough, /*#__PURE__*/Schedule.addDelay(({\n output: error\n}) => {\n if (HttpClientError.isHttpClientError(error) && error.reason._tag === \"StatusCodeError\" && error.reason.response.status === 429) {\n return retryAfterDelay(error.reason.response.headers[\"retry-after\"]);\n }\n return Effect.succeed(Duration.seconds(1));\n}));\n/**\n * Registry of exporter flush operations, used to manually drain buffered\n * telemetry before the surrounding scope closes.\n *\n * **Details**\n *\n * Every exporter created by `make` registers its flush operation here, so a\n * single `flush` drains all signals sharing the registry concurrently while\n * each exporter respects its own `concurrency` limit. For each exporter,\n * `flush` returns once every export already in flight when it was called has\n * settled and every item accepted before the call has been sent or discarded by\n * a failed export (or after one fresh snapshot settles when `exportEmpty` is\n * enabled). `flush` cannot fail and respects each exporter's temporary-disable\n * window. Wrap it with `Effect.timeoutOption` to bound its duration at the call\n * site.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class Flusher extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpExporter/Flusher\") {}\n/**\n * Provides a `Flusher` backed by a fresh registry.\n *\n * **Details**\n *\n * This is intentionally a single module-level constant rather than a factory:\n * layer memoization is keyed by layer instance, so every signal layer\n * referencing this same constant shares one registry per layer build, and one\n * `flush` drains traces, logs and metrics together. A factory returning a new\n * layer per call would silently create one registry per signal.\n *\n * Registration is scoped — an exporter is removed from the registry when its\n * own scope closes. Flushing with an empty registry is a no-op.\n *\n * For each registered exporter, `flush` awaits all exports already in flight\n * when it was called and drains every item accepted before the call (or sends\n * one fresh snapshot when `exportEmpty` is enabled). Interrupting `flush` only\n * stops waiting and does not cancel in-flight exports or drop queued items.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFlusher = /*#__PURE__*/Layer.sync(Flusher, () => {\n const registry = new Set();\n return {\n flush: Effect.suspend(() => {\n if (registry.size === 0) {\n return Effect.void;\n }\n return Effect.forEach(registry, identity, {\n concurrency: \"unbounded\",\n discard: true\n });\n }),\n register: run => Effect.flatMap(Scope.Scope, scope => {\n registry.add(run);\n return Scope.addFinalizer(scope, Effect.sync(() => registry.delete(run)));\n })\n };\n});\n/**\n * Creates a scoped OTLP batch exporter.\n *\n * **Details**\n *\n * The exporter buffers pending pushed items up to `maxQueueSize` (dropping new\n * arrivals on overflow and notifying `onDrop`), sends FIFO batches of at most\n * `maxBatchSize` with up to `concurrency` exports (including retries) in flight\n * at a time, temporarily disables exporting after unhandled failures, and\n * drains remaining items during scope finalization up to `shutdownTimeout`.\n * `maxQueueSize` bounds only pending queued items, not batches already in\n * flight.\n *\n * The export interval starts with the first push and stops once an export\n * empties the buffer, so an idle exporter keeps no timer pending. With\n * `exportEmpty` and batching disabled, it exports on every interval instead.\n *\n * Optional gzip compression uses `HttpClientRequest.compressBody` before the\n * retry loop, so retries reuse the compressed bytes. Bodies smaller than 1KB\n * remain uncompressed. Compression requires runtime `CompressionStream` support;\n * compression failures follow the same temporary-disable behavior as transport\n * failures and do not fail flushing or shutdown.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const services = yield* Effect.context();\n const clock = Context.get(services, Clock);\n const scope = Context.get(services, Scope.Scope);\n const exportInterval = Duration.max(Duration.fromInputUnsafe(options.exportInterval), Duration.zero);\n const batchLimit = options.maxBatchSize === \"disabled\" ? Infinity : Count.normalizeNonEmpty(options.maxBatchSize);\n const maxQueueSize = options.maxQueueSize === undefined || Number.isNaN(options.maxQueueSize) ? Number.isFinite(batchLimit) ? Math.max(2048, batchLimit) : 2048 : Count.normalize(options.maxQueueSize);\n const concurrency = options.concurrency === \"unbounded\" ? Infinity : options.concurrency === undefined || Number.isNaN(options.concurrency) ? 4 : Count.normalizeNonEmpty(options.concurrency);\n const client = Context.get(services, HttpClient.HttpClient).pipe(HttpClient.tap(response => Effect.ignore(response.arrayBuffer)), HttpClient.tapError(error => error.response ? Effect.ignore(error.response.arrayBuffer) : Effect.void), HttpClient.filterStatusOk, HttpClient.transformResponse(Effect.provideService(HttpClient.TracerPropagationEnabled, false)), HttpClient.retryTransient({\n schedule: policy,\n times: 3\n }));\n const exporterUserAgent = `OTel-OTLP-Exporter-JavaScript-Effect-${options.label}/${Version.getCurrentVersion()}`;\n const userHeaders = Headers.fromInput(options.headers);\n const userAgent = userHeaders[\"user-agent\"];\n const headers = Headers.set(userHeaders, \"user-agent\", userAgent ? `${userAgent} ${exporterUserAgent}` : exporterUserAgent);\n const request = HttpClientRequest.post(options.url, {\n headers\n });\n const exportsEmpty = options.maxBatchSize === \"disabled\" && options.exportEmpty === true;\n const queue = MutableList.make();\n let disabledUntil = undefined;\n let closed = false;\n const isDisabled = () => {\n if (disabledUntil === undefined) return false;\n if (clock.currentTimeMillisUnsafe() < disabledUntil) return true;\n disabledUntil = undefined;\n return false;\n };\n const isStopped = () => closed || isDisabled();\n // Progress is counted in items, or in snapshots when `exportsEmpty` is set:\n // `requested` is how far callers asked to drain and `started` is how far the\n // batches dequeued so far reach. `inFlight` maps each working fiber to the\n // offset its batch starts at. Offsets only grow and a `Map` keeps insertion\n // order, so its first entry is the earliest export in flight and everything\n // before it has settled, even when batches complete out of order.\n let requested = 0;\n let started = 0;\n const inFlight = new Map();\n const settled = () => closed ? Infinity : inFlight.values().next().value ?? started;\n const waiters = new Set();\n const notifyWaiters = () => {\n const reached = settled();\n for (const waiter of waiters) {\n if (reached >= waiter.target) {\n waiters.delete(waiter);\n waiter.resume(Effect.void);\n }\n }\n };\n const awaitSettled = target => Effect.callback(resume => {\n if (settled() >= target) return resume(Effect.void);\n const waiter = {\n target,\n resume\n };\n waiters.add(waiter);\n return Effect.sync(() => {\n waiters.delete(waiter);\n });\n });\n // `armed` is open while there is something to export. It changes in the\n // same synchronous step as the queue check, so a push is never stranded.\n const armed = yield* Latch.make(exportsEmpty);\n const wake = yield* Latch.make();\n const exportBatch = items => Effect.suspend(() => {\n const [body, onSuccess] = options.body(items);\n const batchRequest = HttpClientRequest.setBody(request, body);\n // Compress before client.execute so transient retries reuse the encoded bytes.\n const response = options.compression === \"gzip\" ? HttpClientRequest.compressBody(batchRequest, \"gzip\").pipe(Effect.flatMap(client.execute)) : client.execute(batchRequest);\n return response.pipe(Effect.andThen(onSuccess), Effect.withTracerEnabled(false));\n }).pipe(Effect.catchCause(cause => {\n MutableList.clear(queue);\n // Nothing queued or requested will start now. Count it as started so\n // waiters only wait for the exports still in flight.\n requested = started = Math.max(started, requested);\n if (isDisabled()) return Effect.void;\n disabledUntil = clock.currentTimeMillisUnsafe() + 60_000;\n return Effect.logWarning(\"Disabling exporter for 60 seconds\", cause);\n }), Effect.annotateLogs({\n package: \"@effect/opentelemetry\",\n module: options.label\n }));\n // Up to `concurrency` workers run on demand while there is work. The\n // exporter owns them, so interrupting a flush never cancels a request.\n const canStart = () => inFlight.size < concurrency && !isStopped() && (requested > started || queue.length >= batchLimit);\n const workerLoop = Effect.withFiber(fiber => {\n if (!canStart()) return Effect.void;\n const items = MutableList.takeN(queue, batchLimit);\n inFlight.set(fiber, started);\n started += exportsEmpty ? 1 : items.length;\n // `exit` keeps the worker alive if the failure handler itself dies, for\n // example when a logger throws.\n return Effect.exit(exportBatch(items)).pipe(Effect.ensuring(Effect.sync(() => {\n inFlight.delete(fiber);\n if (inFlight.size === 0 && !exportsEmpty && queue.length === 0 && armed.closeUnsafe()) {\n wake.openUnsafe();\n }\n notifyWaiters();\n })), Effect.andThen(workerLoop));\n });\n const runFork = Effect.runForkWith(services);\n // A worker normally claims its batch before `runFork` returns. Stop when it\n // has not, so a scheduler that yields first cannot make this loop spin.\n const startWorkers = () => {\n while (canStart() && inFlight.has(runFork(workerLoop))) {\n // keep starting workers\n }\n };\n // Exports everything accepted so far, or one fresh snapshot, and waits for\n // it to settle together with every export already in flight. During cooldown,\n // no new export starts, but any surviving in-flight export is still awaited.\n const drain = Effect.suspend(() => {\n if (isStopped()) return awaitSettled(started);\n const target = started + (exportsEmpty ? 1 : queue.length);\n requested = Math.max(requested, target);\n startWorkers();\n return awaitSettled(target);\n });\n const timer = Duration.isFinite(exportInterval) ? runFork(Effect.gen(function* () {\n while (true) {\n wake.closeUnsafe();\n yield* armed.await;\n const expired = yield* Effect.race(Effect.as(Effect.sleep(exportInterval), true), Effect.as(wake.await, false));\n if (expired) yield* drain;\n }\n })) : undefined;\n // A single finalizer stops the timer, drains, then stops active workers in\n // that order even in a parallel scope. Workers are interrupted without\n // waiting for them, so shutdown ends at `shutdownTimeout` even if the HTTP\n // client is uninterruptible.\n yield* Scope.addFinalizer(scope, Effect.suspend(() => {\n timer?.interruptUnsafe();\n return drain.pipe(Effect.interruptible, Effect.timeoutOption(options.shutdownTimeout), Effect.andThen(Effect.sync(() => {\n closed = true;\n MutableList.clear(queue);\n notifyWaiters();\n for (const fiber of inFlight.keys()) {\n fiber.interruptUnsafe();\n }\n })));\n }));\n const flusher = yield* Flusher;\n yield* flusher.register(drain);\n return {\n push(data) {\n // With no idle timer, the next push ends the disabled window.\n if (isStopped()) return;\n if (queue.length >= maxQueueSize) {\n options.onDrop?.(1);\n return;\n }\n MutableList.append(queue, data);\n if (queue.length >= batchLimit) {\n startWorkers();\n } else {\n armed.openUnsafe();\n }\n }\n };\n});\n//# sourceMappingURL=OtlpExporter.js.map","/**\n * Builds OTLP resource metadata shared by exported telemetry.\n *\n * An OTLP resource describes the service and other attributes attached to every\n * exported log, metric, or trace. This module builds resources from explicit\n * options or OpenTelemetry environment variables and converts JavaScript values\n * into OTLP attribute values.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Config from \"../Config.js\";\nimport * as Effect from \"../Effect.js\";\nimport { format } from \"../Formatter.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Version from \"../Version.js\";\nconst isBrowser = \"window\" in globalThis || \"importScripts\" in globalThis;\n/**\n * Creates an OTLP resource from service metadata and additional attributes.\n *\n * **Details**\n *\n * Adds `telemetry.sdk.*` defaults and converts custom attributes to OTLP values.\n * Custom attributes override SDK defaults; service options override matching\n * attributes. Omitted service options add no service attributes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n attributes: entriesToAttributes(Object.entries({\n \"telemetry.sdk.name\": \"effect\",\n \"telemetry.sdk.language\": isBrowser ? \"webjs\" : \"nodejs\",\n \"telemetry.sdk.version\": Version.getCurrentVersion(),\n ...options.attributes,\n ...(options.serviceName ? {\n \"service.name\": options.serviceName\n } : undefined),\n ...(options.serviceVersion ? {\n \"service.version\": options.serviceVersion\n } : undefined)\n })),\n droppedAttributesCount: 0\n});\n/**\n * Creates an OTLP resource from explicit options and OpenTelemetry\n * configuration.\n *\n * **When to use**\n *\n * Use when resource metadata may be configured in code or by the deployment\n * environment. To let operators set the service identity, omit `serviceName`,\n * `serviceVersion`, and their matching attributes, then use\n * `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`.\n *\n * **Details**\n *\n * Explicit `serviceName` and `serviceVersion` options take precedence over\n * matching explicit attributes. Explicit attributes take precedence over\n * environment variables. `OTEL_SERVICE_NAME` and `OTEL_SERVICE_VERSION` take\n * precedence over matching attributes in `OTEL_RESOURCE_ATTRIBUTES`. Missing\n * required configuration is converted to a defect.\n *\n * Keys and values in `OTEL_RESOURCE_ATTRIBUTES` are trimmed, then\n * percent-decoded. Entries with an empty value are kept as `\"\"`; entries\n * without `=` or with an empty key are skipped. When a key is repeated as\n * written, the last entry wins and the earlier ones are not decoded. Invalid\n * percent-encoding in the remaining entries is a `ConfigError` and is\n * converted to a defect.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromConfig = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const env = yield* Config.Record(Schema.StringFromUriComponent, Schema.StringFromUriComponent, \"OTEL_RESOURCE_ATTRIBUTES\", {\n trim: true,\n keepEmptyValues: true\n }).pipe(Config.withDefault(undefined));\n const serviceName = options?.serviceName ?? options?.attributes?.[\"service.name\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_NAME\")) ?? env?.[\"service.name\"] ?? (yield* Config.String(\"OTEL_SERVICE_NAME\"));\n const serviceVersion = options?.serviceVersion ?? options?.attributes?.[\"service.version\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_VERSION\")) ?? env?.[\"service.version\"];\n const attributes = {\n ...env,\n ...options?.attributes\n };\n delete attributes[\"service.name\"];\n delete attributes[\"service.version\"];\n return make({\n serviceName,\n serviceVersion,\n attributes\n });\n}, Effect.orDie);\n/**\n * Returns the `service.name` attribute from an OTLP resource.\n *\n * **When to use**\n *\n * Use when an OTLP resource is known to contain a string `service.name` and\n * throwing is acceptable if that invariant is broken.\n *\n * **Gotchas**\n *\n * Throws if the resource does not contain a string `service.name` attribute.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const serviceNameUnsafe = resource => {\n const serviceNameAttribute = resource.attributes.find(attr => attr.key === \"service.name\");\n if (!serviceNameAttribute || !serviceNameAttribute.value.stringValue) {\n throw new Error(\"Resource does not contain a service name\");\n }\n return serviceNameAttribute.value.stringValue;\n};\n/**\n * Converts key/value entries into OTLP `KeyValue` attributes.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const entriesToAttributes = entries => {\n const attributes = [];\n for (const [key, value] of entries) {\n attributes.push({\n key,\n value: unknownToAttributeValue(value)\n });\n }\n return attributes;\n};\n// OTLP `intValue` is a signed 64-bit integer\nconst int64Bound = 2 ** 63;\n/**\n * Converts an arbitrary JavaScript value into an OTLP `AnyValue`.\n *\n * **Details**\n *\n * Arrays are converted recursively, primitive values use their matching OTLP\n * fields, and unsupported values are formatted as strings. Integers outside the\n * signed 64-bit range fall back to `doubleValue` for numbers and `stringValue`\n * for bigints.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const unknownToAttributeValue = value => {\n if (Array.isArray(value)) {\n return {\n arrayValue: {\n values: value.map(unknownToAttributeValue)\n }\n };\n }\n switch (typeof value) {\n case \"string\":\n return {\n stringValue: value\n };\n case \"bigint\":\n return BigInt.asIntN(64, value) === value ? {\n intValue: String(value)\n } : {\n stringValue: String(value)\n };\n case \"number\":\n return Number.isInteger(value) && value >= -int64Bound && value < int64Bound ? {\n // Unsafe integers would be rounded when written as JSON numbers\n intValue: Number.isSafeInteger(value) ? value : String(BigInt(value))\n } : {\n doubleValue: value\n };\n case \"boolean\":\n return {\n boolValue: value\n };\n default:\n return {\n stringValue: format(value)\n };\n }\n};\n//# sourceMappingURL=OtlpResource.js.map","/**\n * Serializes OTLP payloads into HTTP request bodies.\n *\n * Signal exporters build trace, metric, and log data structures in memory. This\n * module provides the service that turns those structures into JSON or protobuf\n * HTTP bodies before they are posted to an OTLP collector.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Base64 from \"../encoding/Base64.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as otlpProtobuf from \"./internal/otlpProtobuf.js\";\n/**\n * Service for serializing OTLP traces, metrics, and logs into HTTP request\n * bodies.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class OtlpSerialization extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpSerialization\") {}\n// OTLP/JSON writes non-finite numbers as strings and bytes as base64.\n// The holder is read because Buffer#toJSON runs before the replacer.\nfunction jsonReplacer(key, value) {\n if (typeof value === \"number\" && !Number.isFinite(value)) return String(value);\n if (key === \"bytesValue\" && this[key] instanceof Uint8Array) return Base64.encode(this[key]);\n return value;\n}\nconst jsonBody = data => {\n const json = JSON.stringify(data);\n return HttpBody.text(json.includes(\"null\") || json.includes(\"\\\"bytesValue\\\":\") ? JSON.stringify(data, jsonReplacer) : json, \"application/json\");\n};\n/**\n * Provides `OtlpSerialization` using OTLP/HTTP JSON bodies.\n *\n * **Details**\n *\n * `NaN`, `Infinity` and `-Infinity` are written as the strings OTLP/JSON\n * expects, not as `null`. `bytesValue` data is written as a base64 string.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n traces: spans => jsonBody(spans),\n metrics: metrics => jsonBody(metrics),\n logs: logs => jsonBody(logs)\n});\n/**\n * Provides `OtlpSerialization` using protobuf-encoded OTLP bodies with the\n * `application/x-protobuf` content type.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtobuf = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n traces: spans => HttpBody.uint8Array(otlpProtobuf.encodeTracesData(spans), \"application/x-protobuf\"),\n metrics: metrics => HttpBody.uint8Array(otlpProtobuf.encodeMetricsData(metrics), \"application/x-protobuf\"),\n logs: logs => HttpBody.uint8Array(otlpProtobuf.encodeLogsData(logs), \"application/x-protobuf\")\n});\n//# sourceMappingURL=OtlpSerialization.js.map","/**\n * Exports Effect log entries over OTLP/HTTP.\n *\n * The logger turns Effect log entries into OTLP log records and sends them to a\n * logs endpoint, such as an OpenTelemetry Collector or vendor OTLP endpoint. It\n * includes log levels, messages, annotations, causes, fiber ids, optional log\n * spans, and current trace/span ids when they are present.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"../Array.js\";\nimport * as Cause from \"../Cause.js\";\nimport { Clock } from \"../Clock.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport { filterDisablePropagation } from \"../internal/effect.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Logger from \"../Logger.js\";\nimport * as Option from \"../Option.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"../References.js\";\nimport * as Version from \"../Version.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Creates an Effect `Logger` that exports log records through OTLP.\n *\n * **Details**\n *\n * The logger serializes records with the configured resource, sends them\n * through the OTLP exporter, and requires `Scope` so pending records can be\n * flushed on shutdown.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const serialization = yield* OtlpSerialization;\n const otelResource = yield* OtlpResource.fromConfig(options.resource);\n const scope = {\n name: \"effect\",\n version: Version.getCurrentVersion()\n };\n const exporter = yield* Exporter.make({\n label: \"OtlpLogger\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n maxBatchSize: options.maxBatchSize ?? 1000,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n exportInterval: options.exportInterval ?? Duration.seconds(1),\n body: data => [serialization.logs({\n resourceLogs: [{\n resource: otelResource,\n scopeLogs: [{\n scope,\n logRecords: data\n }]\n }]\n }), Effect.void],\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n const opts = {\n excludeLogSpans: options.excludeLogSpans ?? false,\n clock: yield* Clock\n };\n return Logger.make(options => {\n exporter.push(makeLogRecord(options, opts));\n });\n});\n/**\n * Layer that installs the OTLP logger created by `make`.\n *\n * **Details**\n *\n * By default the OTLP logger is merged with any existing loggers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Logger.layer([make(options)], {\n mergeWithExisting: options.mergeWithExisting ?? true\n}).pipe(Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP logs layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Logs are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_LOGS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_LOGS_EXPORTER` has no default, so leaving it unset\n * disables logs.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_LOGS_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"LOGS\"),\n exporters: OtlpEnv.exporters(\"LOGS\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n logsTimeout,\n exportTimeout,\n scheduleDelay,\n maxBatchSize,\n maxQueueSize\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_LOGS_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n logsTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_LOGS_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_BLRP_EXPORT_TIMEOUT\")),\n scheduleDelay: Config.option(Config.Int(\"OTEL_BLRP_SCHEDULE_DELAY\")),\n maxBatchSize: Config.option(Config.Int(\"OTEL_BLRP_MAX_EXPORT_BATCH_SIZE\")),\n maxQueueSize: Config.option(Config.Int(\"OTEL_BLRP_MAX_QUEUE_SIZE\"))\n });\n const shutdownTimeout = Option.firstSomeOf([logsTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n const exportInterval = Option.map(scheduleDelay, _ => Duration.millis(_));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"LOGS\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(exportInterval),\n maxBatchSize: Option.getOrUndefined(maxBatchSize),\n maxQueueSize: Option.getOrUndefined(maxQueueSize),\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n excludeLogSpans: options?.excludeLogSpans,\n mergeWithExisting: options?.mergeWithExisting\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\nconst nanosPerMilli = /*#__PURE__*/BigInt(1_000_000);\nconst makeLogRecord = (options, opts) => {\n const observedTime = opts.clock.currentTimeNanosUnsafe().toString();\n const eventMillis = options.date.getTime();\n const eventTime = (BigInt(eventMillis) * nanosPerMilli).toString();\n const attributes = {\n ...options.fiber.getRef(CurrentLogAnnotations)\n };\n attributes[\"effect.fiberId\"] = options.fiber.id;\n if (!opts.excludeLogSpans) {\n // Outermost spans win duplicate labels.\n for (const [label, startTime] of options.fiber.getRef(CurrentLogSpans)) {\n attributes[`effect.log_span.${label}`] = eventMillis - startTime;\n }\n }\n const errors = Cause.prettyErrors(options.cause, {\n includeCauseInStack: true\n });\n if (errors.length > 0) {\n attributes[\"exception.type\"] = errors[0].name;\n attributes[\"exception.message\"] = errors[0].message;\n attributes[\"exception.stacktrace\"] = errors.map(error => error.stack).join(\"\\n\");\n }\n const message = Arr.ensure(options.message);\n const logRecord = {\n severityNumber: logLevelToSeverityNumber(options.logLevel),\n severityText: options.logLevel,\n timeUnixNano: eventTime,\n observedTimeUnixNano: observedTime,\n attributes: OtlpResource.entriesToAttributes(Object.entries(attributes)),\n body: OtlpResource.unknownToAttributeValue(message.length === 1 ? message[0] : message),\n droppedAttributesCount: 0\n };\n const span = filterDisablePropagation(options.fiber.cache.span);\n if (Option.isSome(span)) {\n logRecord.traceId = span.value.traceId.padStart(32, \"0\");\n logRecord.spanId = span.value.spanId;\n }\n return logRecord;\n};\nconst logLevelToSeverityNumber = logLevel => {\n switch (logLevel) {\n case \"Trace\":\n return ESeverityNumber.SEVERITY_NUMBER_TRACE;\n case \"Debug\":\n return ESeverityNumber.SEVERITY_NUMBER_DEBUG;\n case \"Info\":\n return ESeverityNumber.SEVERITY_NUMBER_INFO;\n case \"Warn\":\n return ESeverityNumber.SEVERITY_NUMBER_WARN;\n case \"Error\":\n return ESeverityNumber.SEVERITY_NUMBER_ERROR;\n case \"Fatal\":\n return ESeverityNumber.SEVERITY_NUMBER_FATAL;\n default:\n return ESeverityNumber.SEVERITY_NUMBER_UNSPECIFIED;\n }\n};\n/**\n * Numerical value of the severity, normalized to values described in Log Data Model.\n */\nconst ESeverityNumber = {\n /** Unspecified. Do NOT use as default */\n SEVERITY_NUMBER_UNSPECIFIED: 0,\n SEVERITY_NUMBER_TRACE: 1,\n SEVERITY_NUMBER_TRACE2: 2,\n SEVERITY_NUMBER_TRACE3: 3,\n SEVERITY_NUMBER_TRACE4: 4,\n SEVERITY_NUMBER_DEBUG: 5,\n SEVERITY_NUMBER_DEBUG2: 6,\n SEVERITY_NUMBER_DEBUG3: 7,\n SEVERITY_NUMBER_DEBUG4: 8,\n SEVERITY_NUMBER_INFO: 9,\n SEVERITY_NUMBER_INFO2: 10,\n SEVERITY_NUMBER_INFO3: 11,\n SEVERITY_NUMBER_INFO4: 12,\n SEVERITY_NUMBER_WARN: 13,\n SEVERITY_NUMBER_WARN2: 14,\n SEVERITY_NUMBER_WARN3: 15,\n SEVERITY_NUMBER_WARN4: 16,\n SEVERITY_NUMBER_ERROR: 17,\n SEVERITY_NUMBER_ERROR2: 18,\n SEVERITY_NUMBER_ERROR3: 19,\n SEVERITY_NUMBER_ERROR4: 20,\n SEVERITY_NUMBER_FATAL: 21,\n SEVERITY_NUMBER_FATAL2: 22,\n SEVERITY_NUMBER_FATAL3: 23,\n SEVERITY_NUMBER_FATAL4: 24\n};\n//# sourceMappingURL=OtlpLogger.js.map","/**\n * Exports Effect metrics over OTLP/HTTP.\n *\n * This module periodically snapshots metrics from the current Effect context,\n * serializes them as OTLP resource metrics, and posts them to a metrics\n * endpoint such as an OpenTelemetry Collector or vendor intake. It is meant for\n * long-running services that already update `Metric` counters, gauges,\n * histograms, frequencies, or summaries. The exporter supports cumulative\n * reporting from a fixed start time and delta reporting from the previous\n * export.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport { Clock } from \"../Clock.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Metric from \"../Metric.js\";\nimport * as Option from \"../Option.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Starts a scoped OTLP metrics exporter.\n *\n * **Details**\n *\n * The exporter snapshots registered Effect metrics on the configured interval, serializes them with the selected aggregation temporality, and flushes during scope finalization up to `shutdownTimeout`.\n * Manual flushing also triggers a snapshot. With delta temporality, each\n * successful export advances the previous-export state, so frequent successful\n * flushes narrow the delta aggregation windows.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const clock = yield* Clock;\n const serialization = yield* OtlpSerialization;\n const startTimeNanos = yield* clock.currentTimeNanos;\n const startTime = String(startTimeNanos);\n const temporality = options.temporality ?? \"cumulative\";\n const resource = yield* OtlpResource.fromConfig(options.resource);\n const metricsScope = {\n name: OtlpResource.serviceNameUnsafe(resource)\n };\n const services = yield* Effect.context();\n // State for delta temporality tracking\n let previousExportTimeNanos = startTimeNanos;\n let previousCounterState = new Map();\n let previousHistogramState = new Map();\n let previousFrequencyState = new Map();\n let snapshotSequence = 0;\n let committedSnapshotSequence = -1;\n const snapshot = () => {\n const snapshot = Metric.snapshotUnsafe(services);\n const currentSnapshotSequence = snapshotSequence++;\n const nowNanos = clock.currentTimeNanosUnsafe();\n const nowTime = String(nowNanos);\n // Only series in this snapshot carry their delta state forward, so removed\n // series do not leak state or report a negative delta when recreated.\n const nextCounterState = new Map();\n const nextHistogramState = new Map();\n const nextFrequencyState = new Map();\n const metricData = [];\n const metricDataByName = new Map();\n const addMetricData = data => {\n metricData.push(data);\n metricDataByName.set(data.name, data);\n };\n const isDelta = temporality === \"delta\";\n const aggregationTemporalityEnum = isDelta ? EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA : EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;\n const intervalStartTime = isDelta ? String(previousExportTimeNanos) : startTime;\n for (let i = 0, len = snapshot.length; i < len; i++) {\n const state = snapshot[i];\n const unit = toUcumUnit(state.attributes?.unit ?? state.attributes?.time_unit);\n const attributes = state.attributes ? OtlpResource.entriesToAttributes(Object.entries(state.attributes)) : [];\n const metricKey = makeMetricKey(state.id, state.attributes);\n switch (state.type) {\n case \"Counter\":\n {\n const currentCount = state.state.count;\n let reportValue = currentCount;\n if (isDelta) {\n const previousCount = previousCounterState.get(metricKey);\n if (previousCount !== undefined) {\n if (typeof currentCount === \"bigint\" && typeof previousCount === \"bigint\") {\n reportValue = currentCount - previousCount;\n // Handle reset: if current < previous, report current value\n if (state.state.incremental && reportValue < BigInt(0)) {\n reportValue = currentCount;\n }\n } else {\n const curr = Number(currentCount);\n const prev = Number(previousCount);\n reportValue = curr - prev;\n // Handle reset\n if (state.state.incremental && reportValue < 0) {\n reportValue = curr;\n }\n }\n }\n nextCounterState.set(metricKey, currentCount);\n }\n const dataPoint = {\n attributes,\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime\n };\n if (typeof reportValue === \"bigint\") {\n dataPoint.asInt = bigintToInt64(reportValue);\n } else {\n dataPoint.asDouble = reportValue;\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).sum.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n sum: {\n aggregationTemporality: aggregationTemporalityEnum,\n isMonotonic: state.state.incremental,\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Gauge\":\n {\n // Gauges don't have temporality - they always report current value\n const dataPoint = {\n attributes,\n startTimeUnixNano: startTime,\n timeUnixNano: nowTime\n };\n if (typeof state.state.value === \"bigint\") {\n dataPoint.asInt = bigintToInt64(state.state.value);\n } else {\n dataPoint.asDouble = state.state.value;\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).gauge.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n gauge: {\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Histogram\":\n {\n const currentBuckets = {\n boundaries: [],\n counts: []\n };\n let prev = 0;\n for (const [boundary, value] of state.state.buckets) {\n if (boundary === Number.POSITIVE_INFINITY) break;\n currentBuckets.boundaries.push(boundary);\n currentBuckets.counts.push(value - prev);\n prev = value;\n }\n // Derive overflow from the total count, whether or not boundaries include Infinity.\n currentBuckets.counts.push(state.state.count - prev);\n let reportCount = state.state.count;\n let reportSum = state.state.sum;\n let reportBucketCounts = currentBuckets.counts;\n let reportExtrema = true;\n if (isDelta) {\n const previousState = previousHistogramState.get(metricKey);\n if (previousState !== undefined) {\n reportCount = state.state.count - previousState.count;\n reportSum = state.state.sum - previousState.sum;\n reportBucketCounts = currentBuckets.counts.map((c, i) => Math.max(0, c - (previousState.bucketCounts[i] ?? 0)));\n // Cumulative extrema cannot describe a later delta interval.\n reportExtrema = false;\n }\n nextHistogramState.set(metricKey, {\n count: state.state.count,\n sum: state.state.sum,\n bucketCounts: currentBuckets.counts.slice()\n });\n }\n const dataPoint = {\n attributes,\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime,\n count: reportCount,\n ...(reportExtrema ? {\n min: state.state.min,\n max: state.state.max\n } : undefined),\n sum: reportSum,\n bucketCounts: reportBucketCounts,\n explicitBounds: currentBuckets.boundaries\n };\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).histogram.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n histogram: {\n aggregationTemporality: aggregationTemporalityEnum,\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Frequency\":\n {\n const dataPoints = [];\n const currentOccurrences = new Map();\n for (const [freqKey, value] of state.state.occurrences) {\n currentOccurrences.set(freqKey, value);\n let reportValue = value;\n if (isDelta) {\n const previousOccurrences = previousFrequencyState.get(metricKey);\n if (previousOccurrences !== undefined) {\n const previousValue = previousOccurrences.get(freqKey) ?? 0;\n reportValue = Math.max(0, value - previousValue);\n }\n }\n dataPoints.push({\n attributes: [...attributes, {\n key: \"key\",\n value: {\n stringValue: freqKey\n }\n }],\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime,\n asInt: reportValue\n });\n }\n if (isDelta) {\n nextFrequencyState.set(metricKey, currentOccurrences);\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).sum.dataPoints.push(...dataPoints);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n sum: {\n aggregationTemporality: aggregationTemporalityEnum,\n isMonotonic: true,\n dataPoints\n }\n });\n }\n break;\n }\n case \"Summary\":\n {\n // Count and sum are lifetime totals, so summaries are always cumulative\n const dataPoint = {\n attributes,\n startTimeUnixNano: startTime,\n timeUnixNano: nowTime,\n count: state.state.count,\n sum: state.state.sum,\n quantileValues: state.state.quantiles.flatMap(([quantile, value]) => value === undefined ? [] : [{\n quantile,\n value\n }])\n };\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).summary.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n summary: {\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n }\n }\n const body = serialization.metrics({\n resourceMetrics: [{\n resource,\n scopeMetrics: [{\n scope: metricsScope,\n metrics: metricData\n }]\n }]\n });\n const onSuccess = isDelta ? Effect.sync(() => {\n if (currentSnapshotSequence < committedSnapshotSequence) return;\n previousCounterState = nextCounterState;\n previousHistogramState = nextHistogramState;\n previousFrequencyState = nextFrequencyState;\n previousExportTimeNanos = nowNanos;\n committedSnapshotSequence = currentSnapshotSequence;\n }) : Effect.void;\n return [body, onSuccess];\n };\n yield* Exporter.make({\n label: \"OtlpMetrics\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n maxBatchSize: \"disabled\",\n // Each snapshot builds on the last one committed, so they go out one at a time.\n concurrency: 1,\n exportEmpty: true,\n exportInterval: options.exportInterval ?? Duration.seconds(10),\n body: snapshot,\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n});\n/**\n * Layer that starts the OTLP metrics exporter created by `make`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.effectDiscard(make(options)).pipe(Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP metrics layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Metrics are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_METRICS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_METRICS_EXPORTER` has no default, so leaving it unset\n * disables metrics.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_METRICS_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"METRICS\"),\n exporters: OtlpEnv.exporters(\"METRICS\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n metricsTimeout,\n exportTimeout,\n exportInterval,\n temporalityPreference\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_METRICS_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n metricsTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_METRICS_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_METRIC_EXPORT_TIMEOUT\")),\n exportInterval: Config.option(Config.Int(\"OTEL_METRIC_EXPORT_INTERVAL\").pipe(Config.map(Duration.millis))),\n temporalityPreference: Config.option(Config.Literals([\"delta\", \"cumulative\"], \"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE\"))\n });\n const shutdownTimeout = Option.firstSomeOf([metricsTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"METRICS\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(exportInterval),\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n temporality: Option.getOrUndefined(temporalityPreference)\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\n/** Creates a unique key for a metric including its attributes */\nconst makeMetricKey = (id, attributes) => {\n if (attributes === undefined || Object.keys(attributes).length === 0) {\n return id;\n }\n const sortedEntries = Object.entries(attributes).sort((a, b) => a[0].localeCompare(b[0]));\n return `${id}:${JSON.stringify(sortedEntries)}`;\n};\nconst ucumUnits = /*#__PURE__*/new Map([[\"nanoseconds\", \"ns\"], [\"microseconds\", \"us\"], [\"milliseconds\", \"ms\"], [\"seconds\", \"s\"], [\"bytes\", \"By\"]]);\nconst toUcumUnit = (unit = \"\") => ucumUnits.get(unit) ?? unit;\n/** OTLP/JSON accepts int64 as a decimal string, which keeps values beyond 2^53 exact */\nconst bigintToInt64 = value => Number.isSafeInteger(Number(value)) ? Number(value) : value.toString();\n/**\n * AggregationTemporality defines how a metric aggregator reports aggregated\n * values. It describes how those values relate to the time interval over\n * which they are aggregated.\n */\nconst EAggregationTemporality = {\n AGGREGATION_TEMPORALITY_UNSPECIFIED: 0,\n /** DELTA is an AggregationTemporality for a metric aggregator which reports\n changes since last report time. Successive metrics contain aggregation of\n values from continuous and non-overlapping intervals.\n The values for a DELTA metric are based only on the time interval\n associated with one measurement cycle. There is no dependency on\n previous measurements like is the case for CUMULATIVE metrics.\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n DELTA metric:\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0+1 to\n t_0+2 with a value of 2. */\n AGGREGATION_TEMPORALITY_DELTA: 1,\n /** CUMULATIVE is an AggregationTemporality for a metric aggregator which\n reports changes since a fixed start time. This means that current values\n of a CUMULATIVE metric depend on all previous measurements since the\n start time. Because of this, the sender is required to retain this state\n in some form. If this state is lost or invalidated, the CUMULATIVE metric\n values MUST be reset and a new fixed start time following the last\n reported measurement time sent MUST be used.\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n CUMULATIVE metric:\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+2 with a value of 5.\n 9. The system experiences a fault and loses state.\n 10. The system recovers and resumes receiving at time=t_1.\n 11. A request is received, the system measures 1 request.\n 12. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_1 to\n t_0+1 with a value of 1.\n Note: Even though, when reporting changes since last report time, using\n CUMULATIVE is valid, it is not recommended. This may cause problems for\n systems that do not use start_time to determine when the aggregation\n value was reset (e.g. Prometheus). */\n AGGREGATION_TEMPORALITY_CUMULATIVE: 2\n};\n//# sourceMappingURL=OtlpMetrics.js.map","/**\n * Exports Effect tracing spans over OTLP/HTTP.\n *\n * This module creates a `Tracer.Tracer` backed by the shared OTLP batch\n * exporter, so spans created by Effect tracing APIs can be sent to an\n * OpenTelemetry Collector, vendor endpoint, or local collector. Exported spans\n * include identifiers, parent links, attributes, events, timing, kind, and\n * status information. Use the constructor directly or install it through the\n * provided layer.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Cause from \"../Cause.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Hex from \"../encoding/Hex.js\";\nimport { flow } from \"../Function.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Version from \"../Version.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport { entriesToAttributes } from \"./OtlpResource.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Creates a `Tracer` that exports ended sampled spans to an OTLP traces endpoint.\n *\n * **Details**\n *\n * Spans are batched using the configured interval and batch size, serialized\n * with `OtlpSerialization`, and flushed when the surrounding `Scope` closes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const otelResource = yield* OtlpResource.fromConfig(options.resource);\n const serialization = yield* OtlpSerialization;\n const scope = {\n name: \"effect\",\n version: Version.getCurrentVersion()\n };\n const exporter = yield* Exporter.make({\n label: \"OtlpTracer\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.exportInterval ?? Duration.seconds(5),\n maxBatchSize: options.maxBatchSize ?? 1000,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n body(spans) {\n const data = {\n resourceSpans: [{\n resource: otelResource,\n scopeSpans: [{\n scope,\n spans\n }]\n }]\n };\n return [serialization.traces(data), Effect.void];\n },\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n function exportFn(span) {\n if (!span.sampled) return;\n exporter.push(makeOtlpSpan(span));\n }\n const sampler = options.sampler;\n const parentBased = sampler?.parentBased ?? true;\n const isSampled = sampler === undefined ? undefined : span => {\n if (parentBased && Option.isSome(span.parent)) {\n return span.parent.value.sampled;\n }\n if (sampler.ratio >= 1) return true;\n if (sampler.ratio <= 0) return false;\n // Like the OpenTelemetry probability sampler, a trace is kept when the last\n // 56 bits of its ID reach `(1 - ratio) * 2^56`, so every span of a trace\n // gets the same decision. Only the top 52 of those bits are compared, which\n // a double holds exactly. A trace ID without hex digits there is kept.\n const randomness = Number(`0x${span.traceId.slice(-14, -1)}`);\n return Number.isNaN(randomness) || randomness >= (1 - sampler.ratio) * 2 ** 52;\n };\n return Tracer.make({\n span(options) {\n return new SpanImpl(options, exportFn, isSampled);\n },\n context: options.context ? function (primitive, fiber) {\n if (fiber.cache.span === undefined) {\n return primitive[\"~effect/Effect/evaluate\"](fiber);\n }\n return options.context(primitive, fiber.cache.span);\n } : undefined\n });\n});\n/**\n * Provides `Tracer.Tracer` using the OTLP tracer created by `make`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/flow(make, /*#__PURE__*/Layer.effect(Tracer.Tracer), /*#__PURE__*/Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP traces layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Traces are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_TRACES_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_TRACES_EXPORTER` has no default, so leaving it unset\n * disables traces.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * `OTEL_TRACES_SAMPLER` accepts \"always_on\", \"always_off\", \"traceidratio\",\n * \"parentbased_always_on\", \"parentbased_always_off\" and\n * \"parentbased_traceidratio\", and sets the `sampler` option of `make`. The\n * `traceidratio` samplers keep the share of traces set by\n * `OTEL_TRACES_SAMPLER_ARG`, from 0 to 1, defaulting to 1. Other values, such\n * as \"jaeger_remote\", fail the layer. When `OTEL_TRACES_SAMPLER` is unset, no\n * sampler is used.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"TRACES\"),\n exporters: OtlpEnv.exporters(\"TRACES\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n tracesTimeout,\n exportTimeout,\n scheduleDelay,\n maxBatchSize,\n maxQueueSize,\n samplerName\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_TRACES_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n tracesTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TRACES_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_BSP_EXPORT_TIMEOUT\")),\n scheduleDelay: Config.option(Config.Int(\"OTEL_BSP_SCHEDULE_DELAY\").pipe(Config.map(Duration.millis))),\n maxBatchSize: Config.option(Config.Int(\"OTEL_BSP_MAX_EXPORT_BATCH_SIZE\")),\n maxQueueSize: Config.option(Config.Int(\"OTEL_BSP_MAX_QUEUE_SIZE\")),\n samplerName: Config.option(Config.Literals([\"always_on\", \"always_off\", \"traceidratio\", \"parentbased_always_on\", \"parentbased_always_off\", \"parentbased_traceidratio\"], \"OTEL_TRACES_SAMPLER\"))\n });\n const sampler = Option.isNone(samplerName) ? undefined : {\n ratio: samplerName.value.endsWith(\"traceidratio\") ? yield* Config.schema(Schema.Finite.check(Schema.isBetween({\n minimum: 0,\n maximum: 1\n })), \"OTEL_TRACES_SAMPLER_ARG\").pipe(Config.withDefault(1)) : samplerName.value.endsWith(\"always_on\") ? 1 : 0,\n parentBased: samplerName.value.startsWith(\"parentbased_\")\n };\n const shutdownTimeout = Option.firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"TRACES\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(scheduleDelay),\n maxBatchSize: Option.getOrUndefined(maxBatchSize),\n maxQueueSize: Option.getOrUndefined(maxQueueSize),\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n context: options?.context,\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n sampler\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\nclass SpanImpl {\n _tag = \"Span\";\n name;\n parent;\n annotations;\n links;\n kind;\n sampled;\n export;\n status;\n _traceId = undefined;\n _spanId = undefined;\n _attributes = undefined;\n _events = undefined;\n constructor(options, exportFn, isSampled) {\n this.name = options.name;\n this.parent = options.parent;\n this.annotations = options.annotations;\n this.links = options.links;\n this.kind = options.kind;\n this.export = exportFn;\n this.sampled = options.sampled && (isSampled === undefined || isSampled(this));\n this.status = {\n _tag: \"Started\",\n startTime: options.startTime\n };\n }\n get traceId() {\n return this._traceId ??= Option.isSome(this.parent) ? this.parent.value.traceId : Hex.random(32);\n }\n get spanId() {\n return this._spanId ??= Hex.random(16);\n }\n get attributes() {\n return this._attributes ??= new Map();\n }\n get events() {\n return this._events ??= [];\n }\n end(endTime, exit) {\n if (this.status._tag === \"Ended\") return;\n this.status = {\n _tag: \"Ended\",\n startTime: this.status.startTime,\n endTime,\n exit\n };\n this.export(this);\n }\n attribute(key, value) {\n if (this.status._tag === \"Ended\") return;\n this.attributes.set(key, value);\n }\n event(name, startTime, attributes) {\n if (this.status._tag === \"Ended\") return;\n this.events.push([name, startTime, attributes]);\n }\n addLinks(links) {\n if (this.status._tag === \"Ended\") return;\n // oxlint-disable-next-line no-restricted-syntax\n this.links.push(...links);\n }\n}\nconst makeOtlpSpan = self => {\n const status = self.status;\n const attributes = self._attributes === undefined ? [] : entriesToAttributes(self._attributes);\n const events = [];\n if (self._events !== undefined) {\n for (let i = 0; i < self._events.length; i++) {\n const [name, startTime, attributes] = self._events[i];\n events.push({\n name,\n timeUnixNano: String(startTime),\n attributes: attributes ? entriesToAttributes(Object.entries(attributes)) : [],\n droppedAttributesCount: 0\n });\n }\n }\n let otelStatus;\n if (status.exit._tag === \"Success\") {\n otelStatus = {\n code: StatusCode.Unset\n };\n } else if (Cause.hasInterruptsOnly(status.exit.cause)) {\n otelStatus = {\n code: StatusCode.Unset\n };\n attributes.push({\n key: \"effect.fiber.interrupted\",\n value: {\n boolValue: true\n }\n });\n } else {\n const errors = Cause.prettyErrors(status.exit.cause, {\n includeCauseInStack: true\n });\n otelStatus = errors.length > 0 ? {\n code: StatusCode.Error,\n message: errors[0].message\n } : {\n code: StatusCode.Unset\n };\n for (const error of errors) {\n events.push({\n name: \"exception\",\n timeUnixNano: String(status.endTime),\n droppedAttributesCount: 0,\n attributes: [{\n \"key\": \"exception.type\",\n \"value\": {\n \"stringValue\": error.name\n }\n }, {\n \"key\": \"exception.message\",\n \"value\": {\n \"stringValue\": error.message\n }\n }, {\n \"key\": \"exception.stacktrace\",\n \"value\": {\n \"stringValue\": error.stack ?? \"No stack trace available\"\n }\n }]\n });\n }\n }\n const links = [];\n for (let i = 0; i < self.links.length; i++) {\n const link = self.links[i];\n links.push({\n traceId: link.span.traceId.padStart(32, \"0\"),\n spanId: link.span.spanId,\n attributes: entriesToAttributes(Object.entries(link.attributes)),\n droppedAttributesCount: 0\n });\n }\n return {\n traceId: self.traceId.padStart(32, \"0\"),\n spanId: self.spanId,\n parentSpanId: Option.isSome(self.parent) ? self.parent.value.spanId : undefined,\n name: self.name,\n kind: SpanKind[self.kind],\n startTimeUnixNano: String(status.startTime),\n endTimeUnixNano: String(status.endTime),\n attributes,\n droppedAttributesCount: 0,\n events,\n droppedEventsCount: 0,\n status: otelStatus,\n links,\n droppedLinksCount: 0\n };\n};\nconst StatusCode = {\n Unset: 0,\n Ok: 1,\n Error: 2\n};\nconst SpanKind = {\n unspecified: 0,\n internal: 1,\n server: 2,\n client: 3,\n producer: 4,\n consumer: 5\n};\n//# sourceMappingURL=OtlpTracer.js.map","import { flow } from \"../Function.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as OtlpLogger from \"./OtlpLogger.js\";\nimport * as OtlpMetrics from \"./OtlpMetrics.js\";\nimport * as OtlpSerialization from \"./OtlpSerialization.js\";\nimport * as OtlpTracer from \"./OtlpTracer.js\";\n/**\n * Creates a combined OTLP layer for logs, metrics, and traces.\n *\n * **Details**\n *\n * The layer sends data to `/v1/logs`, `/v1/metrics`, and `/v1/traces` below\n * `baseUrl` and requires an `OtlpSerialization` implementation.\n *\n * The layer provides the `OtlpExporter.Flusher` shared by all three signals,\n * so one `flush` exports their buffered telemetry, for example before a\n * serverless instance is suspended.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => {\n const base = HttpClientRequest.get(options.baseUrl);\n const url = path => HttpClientRequest.appendUrl(base, path).url;\n return Layer.mergeAll(OtlpLogger.layer({\n url: url(\"/v1/logs\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.loggerExportInterval,\n maxBatchSize: options.maxBatchSize,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n shutdownTimeout: options.shutdownTimeout,\n excludeLogSpans: options.loggerExcludeLogSpans,\n mergeWithExisting: options.loggerMergeWithExisting\n }), OtlpMetrics.layer({\n url: url(\"/v1/metrics\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.metricsExportInterval,\n shutdownTimeout: options.shutdownTimeout,\n temporality: options.metricsTemporality\n }), OtlpTracer.layer({\n url: url(\"/v1/traces\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.tracerExportInterval,\n maxBatchSize: options.maxBatchSize,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n context: options.tracerContext,\n shutdownTimeout: options.shutdownTimeout,\n sampler: options.tracerSampler\n }));\n};\n/**\n * Creates a combined OTLP layer for logs, metrics, and traces from\n * OpenTelemetry configuration.\n *\n * **Details**\n *\n * Each signal is exported only when an endpoint is set and its own exporter\n * variable includes `otlp`. Unlike the OpenTelemetry SDK specification, the\n * exporter variables have no default, so an endpoint alone exports nothing.\n * To export all three signals:\n *\n * ```sh\n * export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318\n * export OTEL_TRACES_EXPORTER=otlp\n * export OTEL_METRICS_EXPORTER=otlp\n * export OTEL_LOGS_EXPORTER=otlp\n * ```\n *\n * The layer provides the `OtlpExporter.Flusher` shared by all enabled signals.\n * It is provided even when configuration disables every signal, in which case\n * `flush` is a no-op.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Layer.mergeAll(OtlpLogger.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers,\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n excludeLogSpans: options?.loggerExcludeLogSpans,\n mergeWithExisting: options?.loggerMergeWithExisting\n}), OtlpMetrics.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers\n}), OtlpTracer.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers,\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n context: options?.tracerContext\n}));\n/**\n * Creates the combined OTLP logs, metrics, and traces layer using JSON\n * serialization.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/flow(layer, /*#__PURE__*/Layer.provide(OtlpSerialization.layerJson));\n/**\n * Creates the combined OTLP logs, metrics, and traces layer using protobuf\n * serialization.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtobuf = /*#__PURE__*/flow(layer, /*#__PURE__*/Layer.provide(OtlpSerialization.layerProtobuf));\n//# sourceMappingURL=Otlp.js.map","import { Schema } from \"effect\";\n\nconst TallyFields = Schema.Struct({\n library: Schema.String,\n version: Schema.String,\n kind: Schema.String,\n name: Schema.String,\n calls: Schema.Finite,\n});\n\nexport type Tally = typeof TallyFields.Type;\n\nexport const TallyList = Schema.Array(TallyFields);\n\nexport const SPOOL_ENV = \"USAGE_METER_SPOOL\";\n\nexport const CALLS_METRIC = \"code.usage.calls\";\n\nexport const NO_CALLS = 0;\n","import {\n Array as Arr,\n Effect,\n FileSystem,\n Layer,\n Option,\n Path,\n Random,\n Schema,\n pipe,\n} from \"effect\";\nimport type { Context } from \"effect\";\n\nimport { TallyList } from \"./usage-tally.ts\";\nimport type { Tally } from \"./usage-tally.ts\";\n\nexport interface Seen {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n readonly calls: number;\n}\n\nconst ManifestFields = Schema.Struct({ name: Schema.String, version: Schema.String });\n\ntype Manifest = typeof ManifestFields.Type;\n\ntype Services = FileSystem.FileSystem | Path.Path;\n\nconst MANIFEST = \"package.json\";\n\nconst decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(ManifestFields));\n\nconst encodeTallies = Schema.encodeEffect(Schema.fromJsonString(TallyList));\n\nconst manifestAbove = (\n directory: string,\n): Effect.Effect<Option.Option<Manifest>, never, Services> =>\n Effect.gen(function* manifestAboveDirectory() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(path.join(directory, MANIFEST)).pipe(Effect.option);\n const found = pipe(text, Option.flatMap(decodeManifest));\n const parent = path.dirname(directory);\n if (Option.isSome(found) || parent === directory) {\n return found;\n }\n return yield* manifestAbove(parent);\n });\n\nconst tallyOf = ({\n moduleUrl,\n kind,\n name,\n calls,\n}: Seen): Effect.Effect<Option.Option<Tally>, never, Services> =>\n Effect.gen(function* tallyOfSeen() {\n const path = yield* Path.Path;\n const file = yield* path.fromFileUrl(new URL(moduleUrl)).pipe(Effect.option);\n if (Option.isNone(file)) {\n return Option.none<Tally>();\n }\n const manifest = yield* manifestAbove(path.dirname(file.value));\n return pipe(\n manifest,\n Option.map(({ name: library, version }): Tally => ({ library, version, kind, name, calls })),\n );\n });\n\nconst written = (spool: string, seen: readonly Seen[]): Effect.Effect<void, never, Services> =>\n Effect.gen(function* writeSpool() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const tallies = yield* Effect.forEach(seen, tallyOf, { concurrency: \"unbounded\" }).pipe(\n Effect.map(Arr.getSomes),\n );\n const text = yield* encodeTallies(tallies);\n const suffix = yield* Random.nextInt;\n yield* fs.makeDirectory(spool, { recursive: true });\n yield* fs.writeFileString(\n path.join(spool, `${String(process.pid)}-${String(suffix)}.json`),\n text,\n );\n }).pipe(Effect.ignore);\n\nconst taggedError = Schema.TaggedError;\n\nclass NodeServicesMissing extends taggedError<\n NodeServicesMissing,\n { readonly brand: unique symbol }\n>()(\"NodeServicesMissing\", { message: Schema.String }) {}\n\nconst nodeServices = Effect.tryPromise({\n try: () => import(\"@effect/platform-node/NodeServices\"),\n catch: () => NodeServicesMissing.make({ message: \"@effect/platform-node could not be loaded\" }),\n}).pipe(Effect.flatMap(({ layer }) => Layer.build(layer)));\n\nexport const spoolWritten =\n (spool: string) =>\n (seen: readonly Seen[]): Effect.Effect<void> =>\n nodeServices.pipe(\n Effect.flatMap((services: Context.Context<Services>) =>\n Effect.provideContext(written(spool, seen), services),\n ),\n Effect.scoped,\n Effect.ignore,\n );\n","import {\n Array as Arr,\n Config,\n Effect,\n Exit,\n Option,\n Predicate,\n Record as Rec,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { spoolWritten } from \"./usage-spool.ts\";\nimport type { Seen } from \"./usage-spool.ts\";\nimport { NO_CALLS, SPOOL_ENV } from \"./usage-tally.ts\";\n\nexport interface UsageMeter {\n readonly rules: <Name extends string, Rule>(\n rules: Readonly<Record<Name, Rule>>,\n ) => Readonly<Record<Name, Rule>>;\n readonly functions: <Name extends string, Value>(\n functions: Readonly<Record<Name, Value>>,\n ) => Readonly<Record<Name, Value>>;\n readonly plugins: <Plugin extends RulePlugin>(\n plugins: Readonly<Record<string, Plugin>>,\n ) => Readonly<Record<string, Plugin>>;\n readonly within: (prefix: string) => UsageMeter;\n}\n\nexport interface RulePlugin {\n readonly rules?: Readonly<Record<string, unknown>> | undefined;\n}\n\ninterface Declared {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n}\n\ntype Callable = (...args: readonly unknown[]) => unknown;\n\nconst RULE_ENTRIES = [\"create\", \"createOnce\", \"check\", \"linter\", \"fixer\"] as const;\n\nconst RULE = \"rule\";\n\nconst FUNCTION = \"function\";\n\nconst ONE_CALL = 1;\n\nconst PREFIX_SEPARATOR = \"/\";\n\nconst KEY_SEPARATOR = \"\\u0000\";\n\nconst idle: UsageMeter = {\n rules: (rules) => rules,\n functions: (functions) => functions,\n plugins: (plugins) => plugins,\n within: () => idle,\n};\n\nconst declared = new Map<string, Declared>();\n\nconst calls = new Map<string, number>();\n\nconst state = { flushed: false, scheduled: false };\n\nconst spoolSetting = Exit.match(\n Effect.runSyncExit(Config.NonEmptyString(SPOOL_ENV).pipe(Config.option)),\n {\n onSuccess: (value) => value,\n onFailure: () => Option.none<string>(),\n },\n);\n\nconst isCallable = (value: unknown): value is Callable => Predicate.isFunction(value);\n\nconst keyOf = ({ moduleUrl, kind, name }: Declared): string =>\n Arr.join([moduleUrl, kind, name], KEY_SEPARATOR);\n\nconst countCall = (key: string): void => {\n const next = (calls.get(key) ?? NO_CALLS) + ONE_CALL;\n calls.set(key, next);\n};\n\nconst counted = <Value extends Callable>(key: string, callable: Value): Value =>\n Object.assign(function countedCall(this: unknown, ...args: readonly unknown[]): unknown {\n countCall(key);\n return callable.call(this, ...args);\n }, callable);\n\nconst ruleCounted = <Rule>(key: string, rule: Rule): Rule => {\n if (isCallable(rule)) {\n return counted(key, rule);\n }\n if (!Predicate.isObject(rule)) {\n return rule;\n }\n const entries = pipe(\n RULE_ENTRIES,\n Arr.flatMap((entry) =>\n pipe(\n Option.liftPredicate(Rec.get({ ...rule }, entry), Option.isSome),\n Option.flatMap((found) => Option.liftPredicate(found.value, isCallable)),\n Option.map((callable) => [entry, counted(key, callable)] as const),\n Option.toArray,\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(entries)) {\n return rule;\n }\n return { ...rule, ...Rec.fromEntries(entries) };\n};\n\nconst functionCounted = <Value>(key: string, value: Value): Value => {\n if (isCallable(value)) {\n return counted(key, value);\n }\n return value;\n};\n\nexport const flushUsage: Effect.Effect<void> = Effect.suspend(() => {\n if (state.flushed || Option.isNone(spoolSetting)) {\n return Effect.void;\n }\n state.flushed = true;\n const seen = pipe(\n [...declared],\n Arr.map(([key, exported]): Seen => ({ ...exported, calls: calls.get(key) ?? NO_CALLS })),\n );\n return spoolWritten(spoolSetting.value)(seen);\n});\n\nconst flushOnExit = (): void => {\n if (state.scheduled) {\n return;\n }\n state.scheduled = true;\n process.once(\"beforeExit\", () => {\n Effect.runFork(flushUsage);\n });\n};\n\nconst qualified = (prefix: string, name: string): string =>\n pipe([prefix, name], Arr.filter(Str.isNonEmpty), Arr.join(PREFIX_SEPARATOR));\n\nconst wrapped =\n (moduleUrl: string, prefix: string, kind: string) =>\n <Name extends string, Value>(\n wrap: (key: string, value: Value) => Value,\n ): ((names: Readonly<Record<Name, Value>>) => Readonly<Record<Name, Value>>) =>\n (names) => {\n flushOnExit();\n return pipe(\n names,\n Rec.map((value: Value, name: Name) => {\n const exported: Declared = { moduleUrl, kind, name: qualified(prefix, name) };\n declared.set(keyOf(exported), exported);\n return wrap(keyOf(exported), value);\n }),\n );\n };\n\nconst meterOf = (moduleUrl: string, prefix: string): UsageMeter => {\n const rules: UsageMeter[\"rules\"] = (named) =>\n wrapped(moduleUrl, prefix, RULE)(ruleCounted)(named);\n const plugins: UsageMeter[\"plugins\"] = (named) =>\n pipe(\n named,\n Rec.map((plugin, name) =>\n pipe(\n Option.fromUndefinedOr(plugin.rules),\n Option.match({\n onNone: () => plugin,\n onSome: (pluginRules) => ({\n ...plugin,\n rules: meterOf(moduleUrl, qualified(prefix, name)).rules(pluginRules),\n }),\n }),\n ),\n ),\n );\n return {\n rules,\n functions: (named) => wrapped(moduleUrl, prefix, FUNCTION)(functionCounted)(named),\n plugins,\n within: (inner) => meterOf(moduleUrl, qualified(prefix, inner)),\n };\n};\n\nexport const usageMeter = (moduleUrl: string): UsageMeter =>\n pipe(\n spoolSetting,\n Option.match({\n onNone: () => idle,\n onSome: () => meterOf(moduleUrl, \"\"),\n }),\n );\n","import {\n Array as Arr,\n Cause,\n Option,\n Predicate,\n Record as Rec,\n Runtime,\n String as Str,\n pipe,\n} from \"effect\";\n\nconst TAG = \"_tag\";\n\nconst fieldsOf = (failure: unknown): string =>\n pipe(\n Option.liftPredicate(failure, Predicate.isObject),\n Option.map((object): readonly (readonly [string, unknown])[] => Rec.toEntries({ ...object })),\n Option.getOrElse((): readonly (readonly [string, unknown])[] => []),\n Arr.flatMap(([key, value]) =>\n pipe(\n Option.liftPredicate(value, Predicate.isString),\n Option.filter(() => key !== TAG),\n Option.map((text) => `${key}: ${text}`),\n Option.toArray,\n ),\n ),\n Arr.join(\", \"),\n );\n\nconst describedOf = <Failure>(reason: Cause.Reason<Failure>, name: string): string =>\n pipe(\n Option.liftPredicate(reason, Cause.isFailReason),\n Option.map((failed) => fieldsOf(failed.error)),\n Option.filter(Str.isNonEmpty),\n Option.match({ onNone: () => name, onSome: (fields) => `${name} (${fields})` }),\n );\n\nconst linesOf =\n (serviceName: string) =>\n <Failure>(reason: Cause.Reason<Failure>): readonly string[] =>\n pipe(\n Cause.prettyErrors(Cause.fromReasons([reason])),\n Arr.map((error) => {\n if (Str.isEmpty(error.message)) {\n return `${serviceName}: ${describedOf(reason, error.name)}`;\n }\n if (Cause.isDieReason(reason)) {\n return `${serviceName}: ${error.name}: ${error.message}`;\n }\n return `${serviceName}: ${error.message}`;\n }),\n );\n\n/** @internal */\nexport const reportOf =\n (serviceName: string) =>\n <Failure>(cause: Cause.Cause<Failure>): readonly string[] => {\n if (Cause.hasInterruptsOnly(cause) || !cause.pipe(Cause.squash, Runtime.getErrorReported)) {\n return [];\n }\n return pipe(\n cause.reasons,\n Arr.filter((reason) => !Cause.isInterruptReason(reason)),\n Arr.flatMap(linesOf(serviceName)),\n );\n };\n","import { runMain as nodeRuntimeRunMain } from \"@effect/platform-node/NodeRuntime\";\nimport { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport type { NodeServices } from \"@effect/platform-node/NodeServices\";\nimport { Console, Effect, Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport type { HttpClient } from \"effect/http\";\nimport { Otlp, OtlpSerialization } from \"effect/observability\";\n\nimport { flushUsage } from \"#/shared/lib/usage-meter.ts\";\n\nimport { reportOf } from \"./report.ts\";\n\n/** @internal */\nexport type Platform = NodeServices | HttpClient.HttpClient;\n\n/** @internal */\nexport type Run<Provided> = <Success, Failure>(\n program: Effect.Effect<Success, Failure, Platform | Provided>,\n) => void;\n\nconst platform = Layer.mergeAll(nodeServices, FetchHttpClient.layer);\n\nconst runWithTracingAnd =\n <Provided, LayerFailure>({\n serviceName,\n services,\n }: Readonly<{\n serviceName: string;\n services: Layer.Layer<Provided, LayerFailure, Platform>;\n }>): Run<Provided> =>\n (program) => {\n const tracing = Otlp.layerFromConfig({ resource: { serviceName } }).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n const provided = Layer.provideMerge(services, platform);\n const report = reportOf(serviceName);\n nodeRuntimeRunMain(\n Layer.mergeAll(tracing, provided).pipe(\n Layer.build,\n Effect.flatMap((context) => Effect.provideContext(program, context)),\n Effect.scoped,\n Effect.ensuring(flushUsage),\n Effect.tapCause((cause) =>\n Effect.forEach(report(cause), (line) => Console.error(line), {\n concurrency: 1,\n discard: true,\n }),\n ),\n ),\n { disableErrorReporting: true },\n );\n };\n\nconst runWithTracing = (serviceName: string): Run<never> =>\n runWithTracingAnd({ serviceName, services: Layer.empty });\n\n/** @internal */\nexport const runMainWith = runWithTracingAnd;\n\n/** @internal */\nexport const runMain = runWithTracing;\n","import { Clock, Duration, Effect, Ref, Schedule } from \"effect\";\n\nimport { modelName } from \"#/shared/api/model-server/index.ts\";\nimport type { ModelKey } from \"#/shared/api/model-server/index.ts\";\n\nconst IDLE_CHECK_MILLIS = 100;\nconst IDLE_CHECK = Duration.millis(IDLE_CHECK_MILLIS);\nconst STEP = 1;\nconst NONE = 0;\n\n/** @internal */\nexport interface Activity {\n readonly active: Ref.Ref<number>;\n readonly last: Ref.Ref<number>;\n readonly models: Ref.Ref<ReadonlySet<string>>;\n}\n\n/** @internal */\nexport const makeActivity = Effect.fnUntraced(function* makeActivity() {\n const now = yield* Clock.currentTimeMillis;\n const active = yield* Ref.make(NONE);\n const last = yield* Ref.make(now);\n const models = yield* Ref.make<ReadonlySet<string>>(new Set());\n return { active, last, models } satisfies Activity;\n});\n\nconst touch = (activity: Activity): Effect.Effect<void> =>\n Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => Ref.set(activity.last, now)),\n Effect.andThen(Ref.update(activity.active, (count) => count - STEP)),\n );\n\n/** @internal */\nexport const tracked =\n (activity: Activity) =>\n <Value, Failure>(effect: Effect.Effect<Value, Failure>): Effect.Effect<Value, Failure> =>\n Effect.acquireUseRelease(\n Ref.update(activity.active, (count) => count + STEP),\n () => effect,\n () => touch(activity),\n );\n\n/** @internal */\nexport const remember =\n (activity: Activity) =>\n (key: ModelKey): Effect.Effect<void> =>\n Ref.update(activity.models, (models) => new Set([...models, modelName(key)]));\n\nconst isIdle = (activity: Activity, idle: Duration.Duration): Effect.Effect<boolean> =>\n Effect.all([Ref.get(activity.active), Ref.get(activity.last), Clock.currentTimeMillis], {\n concurrency: 1,\n }).pipe(\n Effect.map(([active, last, now]) => active === NONE && now - last >= Duration.toMillis(idle)),\n );\n\n/** @internal */\nexport const untilIdle =\n (idle: Duration.Duration) =>\n (activity: Activity): Effect.Effect<void> =>\n isIdle(activity, idle).pipe(\n Effect.repeat({ schedule: Schedule.spaced(IDLE_CHECK), until: (done) => done }),\n Effect.asVoid,\n );\n","import { Duration, Effect, FileSystem, Option, Schedule, Schema, pipe } from \"effect\";\nimport type { Scope } from \"effect\";\n\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nconst RETRY_MILLIS = 50;\nconst RETRY = Duration.millis(RETRY_MILLIS);\nconst SIGNAL_PROBE = 0;\nconst UNKNOWN_HOLDER = \"unknown\";\n\nconst isAlive = (pid: number): boolean => {\n try {\n return globalThis.process.kill(pid, SIGNAL_PROBE);\n } catch {\n return false;\n }\n};\n\nconst decodePid = Schema.decodeUnknownOption(\n Schema.FiniteFromString.pipe(Schema.decodeTo(Schema.Int)),\n);\n\nconst holderOf = (\n path: string,\n): Effect.Effect<Option.Option<number>, never, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.readFileString(path)),\n Effect.map(decodePid),\n Effect.orElseSucceed(Option.none),\n );\n\nconst heldBy = (path: string, holder: Option.Option<number>): ModelServerError =>\n ModelServerError.make({\n message: `lock ${path} is held by ${pipe(\n holder,\n Option.map(String),\n Option.getOrElse(() => UNKNOWN_HOLDER),\n )}`,\n });\n\nconst clearStale = Effect.fnUntraced(function* clearStale(path: string) {\n const fs = yield* FileSystem.FileSystem;\n const holder = yield* holderOf(path);\n if (Option.exists(holder, (pid) => !isAlive(pid))) {\n yield* fs.remove(path, { force: true }).pipe(Effect.ignore);\n }\n return yield* heldBy(path, holder);\n});\n\nconst tryAcquire = (path: string): Effect.Effect<void, ModelServerError, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.writeFileString(path, `${globalThis.process.pid}`, { flag: \"wx\" })),\n Effect.catchTag(\"PlatformError\", () => clearStale(path)),\n );\n\nconst release = (path: string): Effect.Effect<void, never, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.remove(path, { force: true })),\n Effect.ignore,\n );\n\nconst acquireWithin = (\n path: string,\n timeout: Duration.Input,\n): Effect.Effect<void, ModelServerError, FileSystem.FileSystem> =>\n tryAcquire(path).pipe(\n Effect.retry(Schedule.spaced(RETRY)),\n Effect.timeoutOrElse({ duration: timeout, orElse: () => tryAcquire(path) }),\n );\n\n/** @internal */\nexport const acquireLock =\n (timeout: Duration.Input) =>\n (path: string): Effect.Effect<void, ModelServerError, FileSystem.FileSystem | Scope.Scope> =>\n Effect.acquireRelease(acquireWithin(path, timeout), () => release(path));\n","import { NodeSocketServer } from \"@effect/platform-node-shared\";\nimport {\n Duration,\n Effect,\n FiberSet,\n FileSystem,\n Layer,\n Option,\n Path,\n Ref,\n Semaphore,\n} from \"effect\";\nimport type { Scope } from \"effect\";\nimport { RpcSerialization, RpcServer } from \"effect/rpc\";\nimport type { SocketServer } from \"effect/socket\";\n\nimport { Engine } from \"#/entities/model-engine/index.ts\";\nimport { probe, ModelRpcs } from \"#/shared/api/model-server/index.ts\";\nimport type {\n EmbedPayload,\n ModelKey,\n ModelServerError,\n Status,\n Vectors,\n Location,\n} from \"#/shared/api/model-server/index.ts\";\n\nimport { makeActivity, remember, tracked, untilIdle } from \"./activity.ts\";\nimport type { Activity } from \"./activity.ts\";\nimport { acquireLock } from \"./lock.ts\";\n\nconst LOCK_TIMEOUT_SECONDS = 10;\nconst LOCK_TIMEOUT = Duration.seconds(LOCK_TIMEOUT_SECONDS);\nconst PRIVATE_DIRECTORY = 0o700;\nconst SINGLE = 1;\n\n/** @internal */\nexport interface ServeOptions {\n readonly location: Location;\n readonly idle: Duration.Duration;\n}\n\nconst statusOf = (activity: Activity): Effect.Effect<Status> =>\n Ref.get(activity.models).pipe(\n Effect.map((models) => ({ pid: globalThis.process.pid, models: [...models] })),\n );\n\nconst makeHandlers = Effect.fnUntraced(function* makeHandlers(activity: Activity) {\n const engine = yield* Engine;\n const serial = yield* Semaphore.make(SINGLE);\n const background = yield* FiberSet.make();\n const exclusive = <Value>(\n effect: Effect.Effect<Value, ModelServerError>,\n ): Effect.Effect<Value, ModelServerError> =>\n effect.pipe(Semaphore.withPermits(serial, SINGLE), tracked(activity));\n const load = (key: ModelKey): Effect.Effect<void, ModelServerError> =>\n exclusive(engine.load(key)).pipe(Effect.andThen(remember(activity)(key)));\n const warm = (key: ModelKey): Effect.Effect<void> =>\n FiberSet.run(background, Effect.ignore(load(key))).pipe(Effect.asVoid);\n const remembered = remember(activity);\n const embed = (payload: EmbedPayload): Effect.Effect<Vectors, ModelServerError> => {\n const vectors = exclusive(engine.embed(payload));\n return vectors.pipe(Effect.tap(() => remembered(payload)));\n };\n return ModelRpcs.of({\n Embed: embed,\n Load: load,\n Warm: warm,\n Status: () => statusOf(activity),\n });\n});\n\nconst serverLayer = (\n socket: string,\n activity: Activity,\n): Layer.Layer<never, SocketServer.SocketServerError, Engine> => {\n const handlers = ModelRpcs.toLayer(makeHandlers(activity));\n return RpcServer.layer(ModelRpcs).pipe(\n Layer.provide(handlers),\n Layer.provide(RpcServer.layerProtocolSocketServer),\n Layer.provide(NodeSocketServer.layer({ path: socket })),\n Layer.provide(RpcSerialization.layerNdjson),\n );\n};\n\nconst listen = Effect.fnUntraced(function* listen(\n location: Location,\n activity: Activity,\n scope: Scope.Scope,\n) {\n const fs = yield* FileSystem.FileSystem;\n yield* acquireLock(LOCK_TIMEOUT)(`${location.socket}.lock`);\n const running = yield* probe(location.socket);\n if (Option.isSome(running)) {\n return false;\n }\n yield* fs.remove(location.socket, { force: true });\n yield* Layer.buildWithScope(serverLayer(location.socket, activity), scope);\n return true;\n}, Effect.scoped);\n\n/** @internal */\nexport const serve = Effect.fnUntraced(function* serve({ location, idle }: ServeOptions) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const scope = yield* Effect.scope;\n yield* fs.makeDirectory(path.dirname(location.socket), {\n recursive: true,\n mode: PRIVATE_DIRECTORY,\n });\n const activity = yield* makeActivity();\n const started = yield* listen(location, activity, scope);\n if (started) {\n yield* untilIdle(idle)(activity);\n }\n return started;\n});\n","import { Duration, Effect, Layer, Option, Predicate, Schema } from \"effect\";\nimport type { FileSystem, Path } from \"effect\";\nimport type { ChildProcessSpawner } from \"effect/process\";\n\nimport type { Engine } from \"#/entities/model-engine/index.ts\";\nimport { transformersEngine } from \"#/features/load-transformers/index.ts\";\nimport { runMainWith } from \"#/features/run-main/index.ts\";\nimport { serve } from \"#/features/serve-models/index.ts\";\nimport { ServerArguments } from \"#/features/start-server/index.ts\";\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nconst ARGUMENT_INDEX = 2;\n\nconst options = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerArguments))(\n globalThis.process.argv[ARGUMENT_INDEX],\n);\n\nconst isEngineModule = (value: unknown): value is { readonly layer: Layer.Layer<Engine> } =>\n Predicate.hasProperty(value, \"layer\") && Layer.isLayer(value.layer);\n\nconst importModule = (path: string): Promise<unknown> => import(path);\n\nconst importFailed =\n (path: string) =>\n (cause: unknown): ModelServerError =>\n ModelServerError.make({ message: `importing ${path} failed: ${String(cause)}` });\n\nconst engineModule = (path: string): Layer.Layer<Engine, ModelServerError> =>\n Layer.unwrap(\n Effect.tryPromise({ try: () => importModule(path), catch: importFailed(path) }).pipe(\n Effect.filterOrFail(isEngineModule, () =>\n ModelServerError.make({ message: `${path} exports no engine layer` }),\n ),\n Effect.map((found) => found.layer),\n ),\n );\n\nconst engineOf = ({\n cache,\n engine: module,\n}: typeof ServerArguments.Type): Layer.Layer<\n Engine,\n ModelServerError,\n FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner\n> =>\n Option.match(Option.fromNullishOr(module), {\n onNone: () => transformersEngine(cache),\n onSome: engineModule,\n });\n\nconst engine = Layer.unwrap(options.pipe(Effect.map(engineOf)));\n\nconst program = options.pipe(\n Effect.flatMap(({ socket, cache, idleMillis }) =>\n serve({ location: { socket, cache }, idle: Duration.millis(idleMillis) }),\n ),\n Effect.scoped,\n);\n\nrunMainWith({ serviceName: \"model-server\", services: engine })(program);\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,34,35,36,37,38,39,40,41,42,43],"mappings":";;;AA0xCA,MAAM,aAAa,EACjB,CAAC,OAAO,YAAY;CAClB,OAAO;AACT,EACF;AACA,MAAM,qBAAqB,EACzB,OAAO;CACL,OAAO;EACL,MAAM;EACN,OAAO,KAAA;CACT;AACF,EACF;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAaA,gBAAc;;;ACzzC3B,MA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C,cAAc,mBAAmB,KAAK;CACtC,QAAQ;AACV,CAAC;AAEH,MAAM,SAASL,SAAa,QAAQ,KAAKG,IAAW,QAAQ,CAAC,CAAC;AAE9D,MAAM,UAAU,QAAQ,KACtBG,SAAgB,EAAE,QAAQ,OAAO,iBAC/B,MAAM;CAAE,UAAU;EAAE;EAAQ;CAAM;CAAG,MAAMC,OAAgB,UAAU;AAAE,CAAC,CAC1E,GACAC,MACF;AAEA,YAAY;CAAE,aAAa;CAAgB,UAAU;AAAO,CAAC,CAAC,CAAC,OAAO"}
1
+ {"version":3,"file":"process.mjs","names":["empty","Random","Context.Reference","TypeId","empty","make","set","get","Option.some","Option.none","hash","Hash.hash","Equal.equals","Context.Reference","Context.get","random.Random","Effect.withFiber","Effect.succeed","TypeId","makeWith","effect.contextWith","Proto","effect.updateContext","Context.merge","MutableHashMap.make","Duration.fromInputUnsafe","effect.succeed","Duration.infinity","get","core.withFiber","MutableHashMap.get","Option.isSome","MutableHashMap.remove","MutableHashMap.set","effect.ClockRef","effect.exitHasInterrupts","Duration.isZero","Duration.isFinite","Duration.toMillis","effect.forkUnsafe","effect.onExitUnsafe","effect.void","effect.fiberInterrupt","effect.fiberJoin","MutableHashMap.size","effect.ConsoleRef","core.withFiber","effect.sync","TypeId","Predicate.hasProperty","Proto","Iterable.empty","makeUnsafe","make","Effect.acquireRelease","Effect.sync","Deferred.makeUnsafe","Effect.suspend","Effect.void","Fiber.interruptAll","Deferred.into","Filter.toPredicate","Filter.compose","Cause.filterInterruptors","Filter.has","Exit.isFailure","Cause.hasInterruptsOnly","Deferred.doneUnsafe","Effect.runFork","Effect.interrupt","Effect.isEffect","Effect.withFiber","internalEffect.forkUnsafe","Effect.succeed","effect.CurrentLoggers","make","effect.loggerMake","layer","Layer.effect","withFiber","effect.fnUntraced","isEffect","MutableRef.make","make","Effect.sync","MutableRef.set","Context.Service","Exit.isSuccess","Cause.hasInterruptsOnly","Context.getOrUndefined","Cause.reasonAnnotations","Cause.squash","Effect.isEffect","Effect.tapCause","Effect.void","Effect.logError","Effect.runFork","Effect.withFiber","TypeId","Proto","Inspectable.NodeInspectSymbol","empty","Uint8Array","compressBody","Effect.succeed","Effect.map","Effect.promise","HttpBody.uint8Array","HttpBody.stream","Stream.fromReadableStream","Stream.toReadableStream","Headers.remove","Headers.set","Data.TaggedError","make","Result.try","internal.unwrap","TypeId","Proto","Inspectable.BaseProto","UrlParams.redactUrl","makeWith","UrlParams.empty","Option.none","Headers.empty","HttpBody.empty","make","Headers.set","Headers.setAll","UrlParams.fromInput","Option.fromNullishOr","UrlParams.setAll","Option.some","bodyInternal.updateHeaders","Effect.succeed","Effect.map","compression.compressBody","bodyInternal.updateContentLength","Url.make","Option.getOrUndefined","Result.isSuccess","TypeId","TypeId","filterStatusOk","Effect.succeed","Effect.fail","Error.HttpClientError","Error.StatusCodeError","Inspectable.Class","HttpIncomingMessage.TypeId","HttpIncomingMessage.inspect","HttpClientRequest.toUrl","Option.isNone","Headers.fromInput","Cookies.fromSetCookie","Option.none","Stream.fromReadableStream","Error.DecodeError","Stream.fail","Error.EmptyBodyError","Effect.flatMap","Effect.try","Effect.map","UrlParams.fromInput","internalUrlParams.fromBody","Effect.tryPromise","Effect.cached","Effect.runSync","Headers.fromRecordUnsafe","Option.match","UrlParams.redactUrl","Headers.isRedactedName","Context.Service","Effect.flatMap","HttpClientResponse.filterStatusOk","Inspectable.BaseProto","HttpClientRequest.make","make","Effect.withFiber","UrlParams.CurrentRedactedNames","Url.make","Option.getOrUndefined","Result.isFailure","Cause.fail","Error.HttpClientError","Error.InvalidUrlError","Error.addFailureRedactedNames","Effect.failCause","Scope.addFinalizer","Effect.sync","Effect.uninterruptibleMask","Effect.matchCauseEffect","Effect.succeed","Cause.hasInterrupts","References.TracerEnabled","Tracer.DisablePropagation","Effect.useSpan","Headers.CurrentRedactedNames","tracing.addUrlAttributes","tracing.redactedNames","tracing.addHeaderAttributes","HttpClientRequest.setHeaders","TraceContext.toHeaders","Effect.withParentSpan","Exit.fail","Error.StatusCodeError","References.TracerTimingEnabled","Schedule.isSchedule","Schedule.forever","Effect.repeat","Effect.retry","Predicate.or","retryAfterDelay","Headers.parseRetryAfter","Result.isSuccess","Headers.retryAfterDelay","Duration.max","Duration.millis","Effect.tap","Effect.tapError","Context.Reference","effect","Layer.effect","Effect.contextWith","Effect.map","Effect.updateContext","Context.merge","Error.addResponseRedactedNames","HttpClientResponse.TypeId","HttpIncomingMessage.TypeId","Effect.suspend","Effect.onInterrupt","Stream.suspend","Stream.ensuring","Inspectable.NodeInspectSymbol","Cause.isTimeoutError","Error.isHttpClientError","Predicate.hasProperty","Schedule.fromStep","Schedule.toStep","Context.Service","Data.TaggedError","Effect.fnUntraced","Effect.context","Context.get","Scope.Scope","Fiber.runIn","Scope.forkUnsafe","Semaphore.make","Latch.makeUnsafe","Scope.addFinalizer","Effect.withFiber","Effect.runForkWith","Effect.void","Effect.catchDefect","Effect.interrupt","Rpc.ServerClient","Effect.asVoid","Exit.interrupt","Effect.andThen","Context.getOrUndefinedUnsafe","Exit.die","Effect.ensuring","RpcSchema.isStreamSchema","Tracer.externalSpan","Effect.die","isWrapper","Rpc.isWrapper","Effect.suspend","Exit.void","Effect.flatMap","Effect.exit","Effect.failCause","Scope.makeUnsafe","Effect.onExit","Deferred.isDeferred","Scope.closeUnsafe","Cause.hasDies","Cause.hasInterrupts","Cause.squash","Fiber.getCurrent","Rpc.TracingEnabled","Context.getOrUndefined","Tracer.ParentSpan","Effect.withSpan","RpcTracing.spanName","RpcTracing.spanAttributes","Context.add","onExit","Deferred.await","Effect.onError","Cause.hasInterruptsOnly","Effect.isEffect","Effect.whileLoop","Queue.takeAll","Pull.catchDone","Effect.scoped","Stream.runForEachArray","RpcSchema.getStreamSchemas","Rpc.ParseOptions","Schema.decodeUnknownEffect","Schema.encodeUnknownEffect","Schema.NonEmptyArray","Option.isSome","Schema.Any","Rpc.exitSchema","Schema.encodeSync","Schema.Defect","Schema.Exit","Schema.Never","Context.merge","Context.getUnsafe","make","Scope.make","Scope.provide","Effect.ignoreCause","Effect.forkIn","Effect.forkChild","Queue.take","exitSchema","Schema.Void","Exit.isExit","Exit.isSuccess","Effect.catch","Effect.provideContext","Effect.provideService","Transferable.Collector","Cause.die","SchemaIssue.defaultFormatter","Effect.catchCause","Effect.annotateLogs","Effect.logDebug","Headers.fromInput","Transferable.makeCollectorUnsafe","Effect.matchEffect","Effect.tapCause","Effect.logFatal","Scope.close","layer","Layer.effectDiscard","Effect.forkScoped","Context.Service","Effect.gen","SocketServer.SocketServer","Layer.effect","RpcSerialization.RpcSerialization","Queue.make","scope","Effect.scope","Scope.addFinalizerExit","Queue.offer","Effect.orDie","Predicate.isTagged","Socket.CloseEvent","Effect.catchReason","Effect.succeed","Effect.sync","Effect.succeedNone","Effect.succeed","NetAddress.unixPathAddress","Effect.fromResult","NetAddress.inetAddressFromIpString","Effect.mapError","SocketServer.SocketServerError","SocketServer.SocketServerOpenError","make","layer","Function.flow","Layer.effect","SocketServer.SocketServer","Effect.fnUntraced","Deferred.makeUnsafe","Effect.addFinalizer","Effect.callback","Effect.void","Deferred.doneUnsafe","Exit.fail","Effect.raceFirst","Deferred.await","Scope.make","Context.omit","Scope.Scope","Effect.context","Fiber.runIn","NodeSocket.fromDuplex","Effect.acquireRelease","Effect.suspend","Effect.fail","Socket.SocketError","Socket.SocketOpenError","Socket.SocketCloseError","Effect.sync","Effect.flatMap","Effect.ignoreCause","Effect.runForkWith","Context.add","NodeSocket.NetSocket","Scope.close","Exit.void","runMain","Runtime.makeRunMain","Context.Service","Schema.encodeEffect","Schema.fromJsonString","Schema.Json","ChildProcess.make","Effect.fnUntraced","FileSystem.FileSystem","Path.Path","runtimeManifest","runtimeLock","ChildProcessSpawner.ChildProcessSpawner","Effect.filterOrFail","Hash.string","Predicate.hasProperty","Effect.tryPromise","Exit.match","Duration.zero","Duration.infinity","importModule","Effect.fnUntraced","Path.Path","Effect.mapError","Effect.all","Schema.decodeUnknownEffect","Effect.try","Predicate.isNotUndefined","Cache.makeWith","Effect.withSpan","Cache.get","Effect.flatMap","Effect.asVoid","Layer.effect","NodeRuntime.runMain","Context.Reference","Context.Service","HttpClient.make","Effect.fail","HttpClientError.HttpClientError","HttpClientError.TransportError","Context.getOrUndefined","Headers.merge","Headers.fromInput","Headers.remove","Effect.sync","Effect.map","Effect.tryPromise","HttpClientResponse.fromWeb","Effect.ensuring","Stream.ensuring","Effect.onError","Effect.callback","Effect.interrupt","Effect.flatMap","Stream.toReadableStreamEffect","Stream.interruptWhen","HttpClientError.EncodeError","Stream.mkArrayBuffer","Effect.mapError","layer","HttpClient.layerMergedContext","Effect.succeed","Config.Array","Schema.String","Config.map","Config.Record","Schema.StringFromUriComponent","Config.orElse","Config.withDefault","Config.URL","Headers.parseRetryAfter","Result.isFailure","Effect.succeed","Duration.seconds","Effect.map","Headers.retryAfterDelay","Schedule.passthrough","Schedule.addDelay","HttpClientError.isHttpClientError","Context.Service","Layer.sync","Effect.suspend","Effect.void","Effect.forEach","Effect.flatMap","Scope.Scope","Scope.addFinalizer","Effect.sync","make","Effect.fnUntraced","Effect.context","Context.get","Duration.max","Duration.fromInputUnsafe","Duration.zero","Count.normalizeNonEmpty","Count.normalize","HttpClient.HttpClient","HttpClient.tap","Effect.ignore","HttpClient.tapError","HttpClient.filterStatusOk","HttpClient.transformResponse","Effect.provideService","HttpClient.TracerPropagationEnabled","HttpClient.retryTransient","Version.getCurrentVersion","Headers.fromInput","Headers.set","HttpClientRequest.post","MutableList.make","Effect.callback","Latch.make","HttpClientRequest.setBody","HttpClientRequest.compressBody","Effect.andThen","Effect.withTracerEnabled","Effect.catchCause","MutableList.clear","Effect.logWarning","Effect.annotateLogs","Effect.withFiber","MutableList.takeN","Effect.exit","Effect.ensuring","Effect.runForkWith","Duration.isFinite","Effect.gen","Effect.race","Effect.as","Effect.sleep","Effect.interruptible","Effect.timeoutOption","MutableList.append","make","Version.getCurrentVersion","Effect.fnUntraced","Config.Record","Schema.StringFromUriComponent","Config.withDefault","Config.schema","Schema.UndefinedOr","Schema.String","Config.String","Effect.orDie","Context.Service","Base64.encode","HttpBody.text","Layer.succeed","make","Effect.fnUntraced","OtlpResource.fromConfig","Version.getCurrentVersion","Exporter.make","Duration.seconds","Effect.void","Logger.make","layer","Logger.layer","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Option.firstSomeOf","Option.map","Duration.millis","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Cause.prettyErrors","Arr.ensure","OtlpResource.entriesToAttributes","OtlpResource.unknownToAttributeValue","Option.isSome","make","Effect.fnUntraced","OtlpResource.fromConfig","OtlpResource.serviceNameUnsafe","Effect.context","Metric.snapshotUnsafe","OtlpResource.entriesToAttributes","Effect.sync","Effect.void","Exporter.make","Duration.seconds","layer","Layer.effectDiscard","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Config.map","Duration.millis","Option.firstSomeOf","Option.map","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Effect.fnUntraced","OtlpResource.fromConfig","Version.getCurrentVersion","Exporter.make","Duration.seconds","Effect.void","Option.isSome","Tracer.make","Layer.effect","Tracer.Tracer","Layer.provideMerge","Exporter.layerFlusher","layerFromConfig","Effect.gen","endpoint","exporters","Config.all","Config.Boolean","Config.withDefault","OtlpEnv.endpoint","OtlpEnv.exporters","Config.option","Config.Literals","Config.Int","Config.map","Duration.millis","Option.isNone","Config.schema","Schema.isBetween","Option.firstSomeOf","Option.map","OtlpEnv.headers","Option.getOrElse","Option.getOrUndefined","Effect.orDie","Layer.unwrap","Hex.random","Cause.hasInterruptsOnly","Cause.prettyErrors","Layer.mergeAll","OtlpLogger.layerFromConfig","OtlpMetrics.layerFromConfig","OtlpTracer.layerFromConfig","Schema.Struct","Schema.String","Schema.Finite","Schema.Array","Schema.Struct","Schema.String","Schema.decodeUnknownOption","Schema.fromJsonString","Schema.encodeEffect","Effect.gen","FileSystem.FileSystem","Path.Path","Effect.option","Option.flatMap","Option.isSome","Option.isNone","Option.none","Option.map","Effect.forEach","Effect.map","Arr.getSomes","Random.nextInt","Effect.ignore","Schema.TaggedError","Effect.tryPromise","Effect.flatMap","Layer.build","Effect.provideContext","Effect.scoped","Config.NonEmptyString","Config.option","Effect.runSyncExit","Exit.match","Option.none","Effect.suspend","Option.isNone","Effect.void","Arr.map","Option.liftPredicate","Predicate.isObject","Option.map","Rec.toEntries","Option.getOrElse","Arr.flatMap","Predicate.isString","Option.filter","Option.toArray","Arr.join","Cause.isFailReason","Str.isNonEmpty","Option.match","Cause.prettyErrors","Cause.fromReasons","Arr.map","Str.isEmpty","Cause.isDieReason","Cause.hasInterruptsOnly","Cause.squash","Runtime.getErrorReported","Arr.filter","Cause.isInterruptReason","Layer.mergeAll","nodeServices","FetchHttpClient.layer","Otlp.layerFromConfig","Layer.provide","OtlpSerialization.layerJson","Layer.provideMerge","nodeRuntimeRunMain","Layer.build","Effect.flatMap","Effect.provideContext","Effect.scoped","Effect.ensuring","Effect.tapCause","Effect.forEach","Console.error","Duration.millis","Effect.fnUntraced","Clock.currentTimeMillis","Ref.make","Effect.flatMap","Ref.set","Effect.andThen","Ref.update","Effect.acquireUseRelease","Effect.all","Ref.get","Effect.map","Duration.toMillis","Effect.repeat","Schedule.spaced","Effect.asVoid","Duration.millis","Schema.decodeUnknownOption","Schema.decodeTo","Schema.Int","Effect.flatMap","Effect.map","Effect.orElseSucceed","Option.none","Option.map","Option.getOrElse","Effect.fnUntraced","FileSystem.FileSystem","Option.exists","Effect.ignore","Effect.catchTag","Effect.retry","Schedule.spaced","Effect.timeoutOrElse","Effect.acquireRelease","Duration.seconds","Ref.get","Effect.map","Effect.fnUntraced","Semaphore.make","FiberSet.make","Semaphore.withPermits","Effect.andThen","Effect.ignore","FiberSet.run","Effect.asVoid","Effect.tap","RpcServer.layer","Layer.provide","RpcServer.layerProtocolSocketServer","NodeSocketServer.layer","RpcSerialization.layerNdjson","FileSystem.FileSystem","Option.isSome","Layer.buildWithScope","Effect.scoped","Path.Path","scope","Effect.scope","Schema.decodeUnknownEffect","Schema.fromJsonString","Predicate.hasProperty","Layer.isLayer","Layer.unwrap","Effect.tryPromise","Effect.filterOrFail","Effect.map","Option.match","Option.fromNullishOr","Effect.flatMap","Duration.millis","Effect.scoped"],"sources":["../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Iterable.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/internal/random.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/MutableHashMap.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Metric.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Random.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Cache.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Console.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/FiberSet.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Logger.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Ref.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Runtime.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/internal/version.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/Version.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpMethod.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/compressionBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/httpBody.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/Url.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClientRequest.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpIncomingMessage.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/webResponse.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClientResponse.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpTraceContext.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/internal/tracing.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/HttpClient.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/socket/SocketServer.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/rpc/RpcServer.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.2.0_effect@4.2.0/node_modules/@effect/platform-node-shared/dist/NodeSocketServer.js","../../../../node_modules/.pnpm/@effect+platform-node-shared@4.2.0_effect@4.2.0/node_modules/@effect/platform-node-shared/dist/NodeRuntime.js","../../src/entities/model-engine/model/engine.ts","../../src/features/load-transformers/model/runtime-lock.json","../../src/features/load-transformers/model/runtime-manifest.json","../../src/features/load-transformers/model/runtime.ts","../../src/features/load-transformers/model/transformers.ts","../../../../node_modules/.pnpm/@effect+platform-node@4.2.0_effect@4.2.0_redis@6.2.1_@opentelemetry+api@1.10.0_/node_modules/@effect/platform-node/dist/NodeRuntime.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/http/FetchHttpClient.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/internal/otlpEnv.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpExporter.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpResource.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpSerialization.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpLogger.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpMetrics.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/OtlpTracer.js","../../../../node_modules/.pnpm/effect@4.2.0/node_modules/effect/dist/observability/Otlp.js","../../src/shared/lib/usage-tally.ts","../../src/shared/lib/usage-spool.ts","../../src/shared/lib/usage-meter.ts","../../src/features/run-main/model/report.ts","../../src/features/run-main/model/run-main.ts","../../src/features/serve-models/model/activity.ts","../../src/features/serve-models/model/lock.ts","../../src/features/serve-models/model/serve.ts","../../src/app/model-server-process.ts"],"sourcesContent":["/**\n * Works with JavaScript values that implement `[Symbol.iterator]`.\n *\n * Iterables include arrays, strings, generators, sets, and custom lazy\n * sequences. The helpers in this module let code transform, search, group, and\n * fold iterable values while preserving the input as an iterable instead of\n * forcing an array first.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Equal from \"./Equal.js\";\nimport { dual } from \"./Function.js\";\nimport * as Count from \"./internal/count.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as O from \"./Option.js\";\nimport { isBoolean } from \"./Predicate.js\";\nimport * as R from \"./Result.js\";\nimport * as Tuple from \"./Tuple.js\";\n/**\n * Creates an iterable by applying a function to consecutive integers.\n *\n * **Details**\n *\n * The function is called with each index starting from `0`. If a length is\n * provided, it is rounded down and normalized to at least `1`, with `NaN`\n * treated as `1`. If no length is specified, the iterable is infinite.\n *\n * **Example** (Generating values by index)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Generate first 5 even numbers\n * const evens = Iterable.makeBy((n) => n * 2, { length: 5 })\n * Array.from(evens) // => [0, 2, 4, 6, 8]\n *\n * // Generate squares\n * const squares = Iterable.makeBy((n) => n * n, { length: 4 })\n * Array.from(squares) // => [0, 1, 4, 9]\n *\n * // Infinite sequence (be careful when consuming!)\n * const naturals = Iterable.makeBy((n) => n)\n * const first10 = Iterable.take(naturals, 10)\n * Array.from(first10) // => [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeBy = (f, options) => {\n const max = options?.length !== undefined ? Count.normalizeNonEmpty(options.length) : Infinity;\n return {\n [Symbol.iterator]() {\n let i = 0;\n return {\n next() {\n if (i < max) {\n return {\n value: f(i++),\n done: false\n };\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns an iterable of integers starting at `start` and increasing by `1`.\n *\n * **Details**\n *\n * When `end` is provided and `start <= end`, both endpoints are included. When\n * `end` is omitted, the iterable is unbounded. When `start > end`, the\n * iterable contains only `start`.\n *\n * **Example** (Creating a range)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.range(1, 3)) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const range = (start, end) => {\n if (end === undefined) {\n return makeBy(i => start + i);\n }\n return makeBy(i => start + i, {\n length: start <= end ? end - start + 1 : 1\n });\n};\n/**\n * Returns a `Iterable` containing a value repeated the specified number of times.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to an integer greater than or equal to\n * `1`. `NaN` is treated as `1`.\n *\n * **Example** (Repeating a value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.replicate(\"a\", 3)) // => [\"a\", \"a\", \"a\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const replicate = /*#__PURE__*/dual(2, (a, n) => makeBy(() => a, {\n length: n\n}));\n/**\n * Repeats an iterable `n` times, yielding the full contents of `self` for each\n * repetition.\n *\n * **When to use**\n *\n * Use to repeat an iterable's contents a specific number of times.\n *\n * **Details**\n *\n * The result is lazy. `n` is rounded down and normalized to at least `1`, with\n * `NaN` treated as `1`. Each repetition obtains a new iterator from `self`.\n *\n * @see {@link forever} for repeating without an upper bound\n * @see {@link replicate} for repeating a single value\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const repeat = /*#__PURE__*/dual(2, (self, n) => flatten(makeBy(() => self, {\n length: n\n})));\n/**\n * Repeats an iterable without an upper bound.\n *\n * **When to use**\n *\n * Use to cycle a reusable iterable without an upper bound when a downstream\n * consumer controls how many values are taken.\n *\n * **Gotchas**\n *\n * The returned iterable is lazy and should usually be bounded with `take` or\n * another terminating consumer before materializing it.\n *\n * @see {@link repeat} for repeating an iterable a specific number of times\n * @see {@link take} for bounding the unbounded result before materializing it\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const forever = self => repeat(self, Infinity);\n/**\n * Takes a record and returns an Iterable of tuples containing its keys and values.\n *\n * **Example** (Converting a record to entries)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const x = { a: 1, b: 2, c: 3 }\n * Array.from(Iterable.fromRecord(x)) // => [[\"a\", 1], [\"b\", 2], [\"c\", 3]]\n * ```\n *\n * @stability stable\n * @category converting\n * @since 2.0.0\n */\nexport const fromRecord = self => ({\n *[Symbol.iterator]() {\n for (const key in self) {\n if (Object.hasOwn(self, key)) {\n yield [key, self[key]];\n }\n }\n }\n});\n/**\n * Prepends an element to the front of an `Iterable`, creating a new `Iterable`.\n *\n * **Example** (Prepending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 3, 4]\n * const withOne = Iterable.prepend(numbers, 1)\n * Array.from(withOne) // => [1, 2, 3, 4]\n *\n * // Works with any iterable\n * const letters = \"abc\"\n * const withZ = Iterable.prepend(letters, \"z\")\n * Array.from(withZ) // => [\"z\", \"a\", \"b\", \"c\"]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const prepend = /*#__PURE__*/dual(2, (self, head) => prependAll(self, [head]));\n/**\n * Prepends the specified prefix iterable to the beginning of the specified iterable.\n *\n * **Example** (Prepending another iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.prependAll([1, 2], [\"a\", \"b\"])) // => [\"a\", \"b\", 1, 2]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const prependAll = /*#__PURE__*/dual(2, (self, that) => appendAll(that, self));\n/**\n * Appends an element to the end of an `Iterable`, creating a new `Iterable`.\n *\n * **When to use**\n *\n * Use to add one element after all elements of an iterable while keeping the\n * result as a lazy `Iterable`.\n *\n * **Details**\n *\n * The result yields every element from `self` first, then yields `last` after\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, the appended element is never\n * reached.\n *\n * **Example** (Appending an element)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Array.from(Iterable.append(numbers, 4)) // => [1, 2, 3, 4]\n * ```\n *\n * @see {@link prepend} for adding one element before the existing elements\n * @see {@link appendAll} for appending all elements from another iterable\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const append = /*#__PURE__*/dual(2, (self, last) => appendAll(self, [last]));\n/**\n * Concatenates two iterables, combining their elements.\n *\n * **When to use**\n *\n * Use to lazily concatenate two iterables while preserving order, yielding all\n * elements from `self` before `that`.\n *\n * **Details**\n *\n * The result is lazy. The iterator for `that` is not created or read until\n * `self` is exhausted.\n *\n * **Gotchas**\n *\n * If `self` is infinite or never completes, `that` is never reached.\n *\n * **Example** (Concatenating iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.appendAll([1, 2, 3], [4, 5, 6])) // => [1, 2, 3, 4, 5, 6]\n *\n * // Works with different iterable types\n * const numbers = [1, 2]\n * const letters = \"abc\"\n * const mixed = Iterable.appendAll(numbers, letters)\n * Array.from(mixed) // => [1, 2, \"a\", \"b\", \"c\"]\n *\n * // Lazy evaluation - only consumes what's needed\n * const infinite = Iterable.range(1)\n * const finite = [0, -1, -2]\n * Array.from(Iterable.take(Iterable.appendAll(finite, infinite), 5)) // => [0, -1, -2, 1, 2]\n * ```\n *\n * @see {@link append} for appending one value instead of another iterable\n * @see {@link prependAll} for yielding another iterable before `self`\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const appendAll = /*#__PURE__*/dual(2, (self, that) => ({\n [Symbol.iterator]() {\n const iterA = self[Symbol.iterator]();\n let doneA = false;\n let iterB;\n return {\n next() {\n if (!doneA) {\n const r = iterA.next();\n if (r.done) {\n doneA = true;\n iterB = that[Symbol.iterator]();\n return iterB.next();\n }\n return r;\n }\n return iterB.next();\n }\n };\n }\n}));\n/**\n * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result.\n *\n * **Example** (Tracking running results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Running sum of numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const runningSum = Iterable.scan(numbers, 0, (acc, n) => acc + n)\n * Array.from(runningSum) // => [0, 1, 3, 6, 10, 15]\n *\n * // Build strings progressively\n * const letters = [\"a\", \"b\", \"c\"]\n * const progressive = Iterable.scan(letters, \"\", (acc, letter) => acc + letter)\n * Array.from(progressive) // => [\"\", \"a\", \"ab\", \"abc\"]\n *\n * // Track maximum values seen so far\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * const runningMax = Iterable.scan(values, -Infinity, Math.max)\n * Array.from(runningMax) // => [-Infinity, 3, 3, 4, 4, 5, 9, 9]\n * ```\n *\n * @stability stable\n * @category folding\n * @since 2.0.0\n */\nexport const scan = /*#__PURE__*/dual(3, (self, b, f) => ({\n [Symbol.iterator]() {\n let acc = b;\n let iterator;\n function next() {\n if (iterator === undefined) {\n iterator = self[Symbol.iterator]();\n return {\n done: false,\n value: acc\n };\n }\n const result = iterator.next();\n if (result.done) {\n return result;\n }\n acc = f(acc, result.value);\n return {\n done: false,\n value: acc\n };\n }\n return {\n next\n };\n }\n}));\n/**\n * Checks whether an `Iterable` is empty.\n *\n * **Example** (Checking for emptiness)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.isEmpty([]) // => true\n * Iterable.isEmpty([1, 2, 3]) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 2.0.0\n */\nexport const isEmpty = self => {\n const iterator = self[Symbol.iterator]();\n return iterator.next().done === true;\n};\n/**\n * Returns the number of elements in a `Iterable`.\n *\n * **Example** (Counting iterable elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.size(numbers) // => 5\n *\n * const empty = Iterable.empty<number>()\n * Iterable.size(empty) // => 0\n *\n * // Works with any iterable\n * const letters = \"hello\"\n * Iterable.size(letters) // => 5\n *\n * // Note: This consumes the entire iterable\n * const range = Iterable.range(1, 100)\n * Iterable.size(range) // => 100\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => {\n const iterator = self[Symbol.iterator]();\n let count = 0;\n while (!iterator.next().done) {\n count++;\n }\n return count;\n};\n/**\n * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty.\n *\n * **Example** (Getting the first element)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.head(numbers) // => Option.some(1)\n *\n * const empty = Iterable.empty<number>()\n * Iterable.head(empty) // => Option.none()\n *\n * // Safe way to get first element\n * const firstEven = Iterable.head(\n * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0)\n * )\n * firstEven // => Option.some(4)\n *\n * // Use with Option methods\n * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2)\n * doubled // => Option.some(10)\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const head = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n return result.done ? O.none() : O.some(result.value);\n};\n/**\n * Gets the first element of an `Iterable` without returning an `Option`.\n *\n * **When to use**\n *\n * Use when the `Iterable` is known to be non-empty and direct access to the\n * first element is preferred over handling `Option.none`.\n *\n * **Gotchas**\n *\n * Throws if the `Iterable` is empty.\n *\n * **Example** (Getting the first element unsafely)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * Iterable.headUnsafe(numbers) // => 1\n *\n * const letters = \"hello\"\n * Iterable.headUnsafe(letters) // => \"h\"\n *\n * // Iterable.headUnsafe(Iterable.empty<number>())\n * // throws Error: \"headUnsafe: empty iterable\"\n *\n * // Use only when you're certain the iterable is non-empty\n * const nonEmpty = Iterable.range(1, 10)\n * Iterable.headUnsafe(nonEmpty) // => 1\n * ```\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const headUnsafe = self => {\n const iterator = self[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) throw new Error(\"headUnsafe: empty iterable\");\n return result.value;\n};\n/**\n * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`.\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Taking from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const firstThree = Iterable.take(numbers, 3)\n * Array.from(firstThree) // => [1, 2, 3]\n *\n * // Taking more than available returns all elements\n * const firstTen = Iterable.take(numbers, 10)\n * Array.from(firstTen) // => [1, 2, 3, 4, 5]\n *\n * // Taking 0 or negative returns empty\n * const none = Iterable.take(numbers, 0)\n * Array.from(none) // => []\n *\n * // Useful with infinite iterables\n * const naturals = Iterable.range(1)\n * const firstFive = Iterable.take(naturals, 5)\n * Array.from(firstFive) // => [1, 2, 3, 4, 5]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const take = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n let i = 0;\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n if (i < count) {\n i++;\n return iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n});\n/**\n * Takes the longest initial `Iterable` prefix for which all elements satisfy the\n * specified predicate.\n *\n * **Example** (Taking while a predicate holds)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [2, 4, 6, 8, 3, 10, 12]\n * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0)\n * Array.from(evenPrefix) // => [2, 4, 6, 8]\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const firstThreeByIndex = Iterable.takeWhile(letters, (_, i) => i < 3)\n * Array.from(firstThreeByIndex) // => [\"a\", \"b\", \"c\"]\n *\n * // Stops at first non-matching element\n * const mixed = [1, 3, 5, 4, 7, 9]\n * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1)\n * Array.from(oddPrefix) // => [1, 3, 5]\n *\n * // Type refinement\n * const values: Array<string | number> = [\"a\", \"b\", \"c\", 1, \"d\"]\n * const stringPrefix = Iterable.takeWhile(\n * values,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(stringPrefix) // => [\"a\", \"b\", \"c\"]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const takeWhile = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n if (iterator !== undefined) {\n const result = iterator.next();\n if (!result.done && predicate(result.value, i++)) {\n return result;\n }\n iterator = undefined;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Drops a max number of elements from the start of an `Iterable`\n *\n * **Details**\n *\n * `n` is rounded down and normalized to a non-negative integer. `NaN` is\n * treated as `0`.\n *\n * **Example** (Dropping from the start)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * const withoutFirstTwo = Iterable.drop(numbers, 2)\n * Array.from(withoutFirstTwo) // => [3, 4, 5]\n *\n * // Dropping more than available returns empty\n * const withoutFirstTen = Iterable.drop(numbers, 10)\n * Array.from(withoutFirstTen) // => []\n *\n * // Dropping 0 or negative returns all elements\n * const all = Iterable.drop(numbers, 0)\n * Array.from(all) // => [1, 2, 3, 4, 5]\n *\n * // Combine with take for slicing\n * const slice = Iterable.take(Iterable.drop(numbers, 1), 3)\n * Array.from(slice) // => [2, 3, 4]\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const drop = /*#__PURE__*/dual(2, (self, n) => {\n const count = Count.normalize(n);\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n while (i < count) {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n i++;\n }\n return iterator.next();\n }\n };\n }\n };\n});\n/**\n * Returns the first element that satisfies the specified\n * predicate, or `None` if no such element exists.\n *\n * **Example** (Finding the first match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8]\n * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0)\n * firstEven // => Option.some(4)\n *\n * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10)\n * firstGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\"]\n * const atEvenIndex = Iterable.findFirst(letters, (_, i) => i % 2 === 0)\n * atEvenIndex // => Option.some(\"a\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\"]\n * const firstString = Iterable.findFirst(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * firstString // => Option.some(\"hello\")\n *\n * // Transform during search\n * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => {\n * const sqrt = Math.sqrt(x)\n * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none()\n * })\n * findSquareRoot // => Option.some(1)\n * ```\n *\n * @stability stable\n * @category searching\n * @since 2.0.0\n */\nexport const findFirst = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n return O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n return o;\n }\n }\n i++;\n }\n return O.none();\n});\n/**\n * Finds the last element for which a predicate holds.\n *\n * **Example** (Finding the last match)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * const numbers = [1, 3, 4, 6, 8, 2]\n * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0)\n * lastEven // => Option.some(2)\n *\n * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10)\n * lastGreaterThan10 // => Option.none()\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const lastAtEvenIndex = Iterable.findLast(letters, (_, i) => i % 2 === 0)\n * lastAtEvenIndex // => Option.some(\"e\")\n *\n * // Type refinement\n * const mixed: Array<string | number> = [1, \"hello\", 2, \"world\", 3]\n * const lastString = Iterable.findLast(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * lastString // => Option.some(\"world\")\n * ```\n *\n * @stability stable\n * @category searching\n * @since 2.0.0\n */\nexport const findLast = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n let last = O.none();\n for (const a of self) {\n const o = f(a, i);\n if (isBoolean(o)) {\n if (o) {\n last = O.some(a);\n }\n } else {\n if (O.isSome(o)) {\n last = o;\n }\n }\n i++;\n }\n return last;\n});\n/**\n * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs.\n *\n * **Example** (Zipping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\", \"c\"]\n * const zipped = Iterable.zip(numbers, letters)\n * Array.from(zipped) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Different lengths - shorter one determines result length\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const partial = Iterable.zip(short, long)\n * Array.from(partial) // => [[1, \"a\"], [2, \"b\"]]\n *\n * // Works with any iterables\n * const range = Iterable.range(1, 3)\n * const word = \"abc\"\n * const mixed = Iterable.zip(range, word)\n * Array.from(mixed) // => [[1, \"a\"], [2, \"b\"], [3, \"c\"]]\n *\n * // Create indexed pairs\n * const values = [\"apple\", \"banana\", \"cherry\"]\n * const indices = Iterable.range(0, 2)\n * const indexed = Iterable.zip(indices, values)\n * Array.from(indexed) // => [[0, \"apple\"], [1, \"banana\"], [2, \"cherry\"]]\n * ```\n *\n * @stability stable\n * @category zipping\n * @since 2.0.0\n */\nexport const zip = /*#__PURE__*/dual(2, (self, that) => zipWith(self, that, Tuple.make));\n/**\n * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one\n * input `Iterable` is short, excess elements of the longer `Iterable` are discarded.\n *\n * **Example** (Zipping with a combining function)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Add corresponding elements\n * const a = [1, 2, 3, 4]\n * const b = [10, 20, 30, 40]\n * const sums = Iterable.zipWith(a, b, (x, y) => x + y)\n * Array.from(sums) // => [11, 22, 33, 44]\n *\n * // Combine strings\n * const firstNames = [\"John\", \"Jane\", \"Bob\"]\n * const lastNames = [\"Doe\", \"Smith\", \"Johnson\"]\n * const fullNames = Iterable.zipWith(\n * firstNames,\n * lastNames,\n * (first, last) => `${first} ${last}`\n * )\n * Array.from(fullNames) // => [\"John Doe\", \"Jane Smith\", \"Bob Johnson\"]\n *\n * // Different lengths - stops at shorter\n * const short = [1, 2]\n * const long = [\"a\", \"b\", \"c\", \"d\"]\n * const combined = Iterable.zipWith(\n * short,\n * long,\n * (num, letter) => `${num}${letter}`\n * )\n * Array.from(combined) // => [\"1a\", \"2b\"]\n *\n * // Complex transformations\n * const prices = [10.99, 25.50, 5.00]\n * const quantities = [2, 1, 3]\n * const totals = Iterable.zipWith(prices, quantities, (price, qty) => {\n * return Math.round(price * qty * 100) / 100 // round to 2 decimal places\n * })\n * Array.from(totals) // => [21.98, 25.5, 15]\n * ```\n *\n * @stability stable\n * @category zipping\n * @since 2.0.0\n */\nexport const zipWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const selfIterator = self[Symbol.iterator]();\n const thatIterator = that[Symbol.iterator]();\n return {\n next() {\n const selfResult = selfIterator.next();\n const thatResult = thatIterator.next();\n if (selfResult.done || thatResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(selfResult.value, thatResult.value)\n };\n }\n };\n }\n}));\n/**\n * Places a separator between members of an `Iterable`.\n *\n * **When to use**\n *\n * Use to lazily insert a separator between adjacent values.\n *\n * **Details**\n *\n * If the input is a non-empty array, the result is also a non-empty array.\n *\n * **Example** (Interspersing separators)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Join numbers with separator\n * const numbers = [1, 2, 3, 4]\n * const withCommas = Iterable.intersperse(numbers, \",\")\n * Array.from(withCommas) // => [1, \",\", 2, \",\", 3, \",\", 4]\n *\n * // Join words with spaces\n * const words = [\"hello\", \"world\", \"from\", \"effect\"]\n * const sentence = Iterable.intersperse(words, \" \")\n * Array.from(sentence).join(\"\") // => \"hello world from effect\"\n *\n * // Empty iterable remains empty\n * const empty = Iterable.empty<string>()\n * const stillEmpty = Iterable.intersperse(empty, \"-\")\n * Array.from(stillEmpty) // => []\n *\n * // Single element has no separators added\n * const single = [42]\n * const noSeparator = Iterable.intersperse(single, \"|\")\n * Array.from(noSeparator) // => [42]\n *\n * // Build CSS-like strings\n * const styles = [\"color: red\", \"font-size: 14px\", \"margin: 10px\"]\n * const css = Iterable.intersperse(styles, \"; \")\n * Array.from(css).join(\"\") // => \"color: red; font-size: 14px; margin: 10px\"\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const intersperse = /*#__PURE__*/dual(2, (self, middle) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let next = iterator.next();\n let emitted = false;\n return {\n next() {\n if (next.done) {\n return next;\n } else if (emitted) {\n emitted = false;\n return {\n done: false,\n value: middle\n };\n }\n emitted = true;\n const result = next;\n next = iterator.next();\n return result;\n }\n };\n }\n}));\n/**\n * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function.\n *\n * **Example** (Checking membership with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Custom equivalence for objects\n * const byId = (a: { id: number }, b: { id: number }) => a.id === b.id\n * const containsById = Iterable.containsWith(byId)\n *\n * const users = [{ id: 1 }, { id: 2 }]\n * const hasUser1 = containsById(users, { id: 1 })\n * hasUser1 // => true\n *\n * // Case-insensitive string comparison\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive)\n *\n * const words = [\"Hello\", \"World\"]\n * const hasHello = containsCaseInsensitive(words, \"hello\")\n * hasHello // => true\n *\n * // Approximate number comparison\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const containsApprox = Iterable.containsWith(approxEqual)\n *\n * const values = [1.0, 2.0, 3.0]\n * const hasAlmostTwo = containsApprox(values, 2.05)\n * hasAlmostTwo // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const containsWith = isEquivalent => dual(2, (self, a) => {\n for (const i of self) {\n if (isEquivalent(a, i)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Checks whether an iterable contains a value using Effect's default `Equal`\n * equivalence.\n *\n * **Details**\n *\n * Can be called as `contains(self, value)` or curried as\n * `contains(value)(self)`.\n *\n * **Example** (Checking membership)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5]\n * Iterable.contains(numbers, 3) // => true\n * Iterable.contains(numbers, 6) // => false\n *\n * const letters = \"hello\"\n * Iterable.contains(letters, \"l\") // => true\n * Iterable.contains(letters, \"x\") // => false\n *\n * // Works with any iterable\n * const range = Iterable.range(1, 100)\n * Iterable.contains(range, 50) // => true\n * Iterable.contains(range, 150) // => false\n *\n * // Curried version\n * const containsThree = Iterable.contains(3)\n * containsThree([1, 2, 3]) // => true\n * containsThree([4, 5, 6]) // => false\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const contains = /*#__PURE__*/containsWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of\n * the `Iterable`.\n * `n` is rounded down and normalized to at least `1`; `NaN` and non-positive\n * values therefore produce singleton pieces.\n *\n * **Example** (Chunking an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]\n * const chunks = Iterable.chunksOf(numbers, 3)\n * Array.from(chunks) // => [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n *\n * // Last chunk can be shorter\n * const uneven = [1, 2, 3, 4, 5, 6, 7]\n * const chunks2 = Iterable.chunksOf(uneven, 3)\n * Array.from(chunks2) // => [[1, 2, 3], [4, 5, 6], [7]]\n *\n * // Chunk size larger than iterable\n * const small = [1, 2]\n * const chunks3 = Iterable.chunksOf(small, 5)\n * Array.from(chunks3) // => [[1, 2]]\n *\n * // Process data in batches\n * const data = Iterable.range(1, 100)\n * const batches = Iterable.chunksOf(data, 10)\n * const batchSums = Iterable.map(\n * batches,\n * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n)\n * )\n * Array.from(Iterable.take(batchSums, 3)) // => [55, 155, 255]\n * ```\n *\n * @stability stable\n * @category splitting\n * @since 2.0.0\n */\nexport const chunksOf = /*#__PURE__*/dual(2, (self, n) => {\n const safeN = Count.normalizeNonEmpty(n);\n return {\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n return {\n next() {\n if (iterator === undefined) {\n return {\n done: true,\n value: undefined\n };\n }\n const chunk = [];\n for (let i = 0; i < safeN; i++) {\n const result = iterator.next();\n if (result.done) {\n iterator = undefined;\n return chunk.length === 0 ? {\n done: true,\n value: undefined\n } : {\n done: false,\n value: chunk\n };\n }\n chunk.push(result.value);\n }\n return {\n done: false,\n value: chunk\n };\n }\n };\n }\n };\n});\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function.\n *\n * **Example** (Grouping consecutive elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group consecutive equal numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.groupWith(numbers, (a, b) => a === b)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * // Case-insensitive grouping of strings\n * const words = [\"Apple\", \"APPLE\", \"banana\", \"Banana\", \"cherry\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const groupedWords = Iterable.groupWith(words, caseInsensitive)\n * Array.from(groupedWords) // => [[\"Apple\", \"APPLE\"], [\"banana\", \"Banana\"], [\"cherry\"]]\n *\n * // Group by approximate equality\n * const floats = [1.1, 1.12, 1.9, 2.01, 2.05, 3.5]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.2\n * const groupedFloats = Iterable.groupWith(floats, approxEqual)\n * Array.from(groupedFloats) // => [[1.1, 1.12], [1.9, 2.01, 2.05], [3.5]]\n *\n * // Only groups consecutive elements\n * const scattered = [1, 2, 1, 2, 1]\n * const scatteredGroups = Iterable.groupWith(scattered, (a, b) => a === b)\n * Array.from(scatteredGroups) // => [[1], [2], [1], [2], [1]]\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const groupWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let nextResult;\n return {\n next() {\n let result;\n if (nextResult !== undefined) {\n if (nextResult.done) {\n return {\n done: true,\n value: undefined\n };\n }\n result = nextResult;\n nextResult = undefined;\n } else {\n result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n }\n const chunk = [result.value];\n while (true) {\n const next = iterator.next();\n if (next.done || !isEquivalent(result.value, next.value)) {\n nextResult = next;\n return {\n done: false,\n value: chunk\n };\n }\n chunk.push(next.value);\n }\n }\n };\n }\n}));\n/**\n * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s.\n *\n * **Example** (Grouping consecutive elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const grouped = Iterable.group(numbers)\n * Array.from(grouped) // => [[1, 1], [2, 2, 2], [3], [1, 1]]\n *\n * const letters = \"aabbccaa\"\n * const groupedLetters = Iterable.group(letters)\n * Array.from(groupedLetters) // => [[\"a\", \"a\"], [\"b\", \"b\"], [\"c\", \"c\"], [\"a\", \"a\"]]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\", value: 1 },\n * { type: \"A\", value: 1 },\n * { type: \"B\", value: 2 },\n * { type: \"A\", value: 1 }\n * ]\n * const groupedObjects = Iterable.group(objects)\n * Array.from(groupedObjects).length // => 3\n * // Note: Only consecutive equal objects are grouped together\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const group = /*#__PURE__*/groupWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Groups all elements by the string or symbol key returned by `f`.\n *\n * **Details**\n *\n * Each property in the returned record contains a non-empty array of elements\n * that produced that key. Unlike `group`, matching elements do not need to be\n * consecutive.\n *\n * **Gotchas**\n *\n * When the key function returns a finite union of string literals or unique\n * symbols, the result preserves those keys as optional properties because the\n * input may not produce every key. Open `string` and `symbol` key types retain\n * their record index signatures.\n *\n * **Example** (Grouping by a key)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Group by string length\n * const words = [\"a\", \"bb\", \"ccc\", \"dd\", \"eee\", \"f\"]\n * const byLength = Iterable.groupBy(words, (word) => word.length.toString())\n * byLength // => { \"1\": [\"a\", \"f\"], \"2\": [\"bb\", \"dd\"], \"3\": [\"ccc\", \"eee\"] }\n *\n * // Group by first letter\n * const names = [\"Alice\", \"Bob\", \"Charlie\", \"David\", \"Anna\", \"Betty\"]\n * const byFirstLetter = Iterable.groupBy(names, (name) => name[0])\n * byFirstLetter // => { A: [\"Alice\", \"Anna\"], B: [\"Bob\", \"Betty\"], C: [\"Charlie\"], D: [\"David\"] }\n *\n * // Group by category\n * const items = [\n * { name: \"apple\", category: \"fruit\" },\n * { name: \"carrot\", category: \"vegetable\" },\n * { name: \"banana\", category: \"fruit\" },\n * { name: \"broccoli\", category: \"vegetable\" }\n * ]\n * const byCategory = Iterable.groupBy(items, (item) => item.category)\n * Object.keys(byCategory) // => [\"fruit\", \"vegetable\"]\n *\n * // Group numbers by even/odd\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? \"even\" : \"odd\")\n * evenOdd // => { odd: [1, 3, 5], even: [2, 4, 6] }\n * ```\n *\n * @stability stable\n * @category grouping\n * @since 2.0.0\n */\nexport const groupBy = /*#__PURE__*/dual(2, (self, f) => {\n const out = {};\n for (const a of self) {\n const k = f(a);\n if (Object.hasOwn(out, k)) {\n out[k].push(a);\n } else {\n InternalRecord.assignProperty(out, k, [a]);\n }\n }\n return out;\n});\nconst constEmpty = {\n [Symbol.iterator]() {\n return constEmptyIterator;\n }\n};\nconst constEmptyIterator = {\n next() {\n return {\n done: true,\n value: undefined\n };\n }\n};\n/**\n * Creates an empty iterable that yields no elements.\n *\n * **When to use**\n *\n * Use when you need an empty iterable as a typed \"no data\" value or a base\n * case for iterable operations.\n *\n * **Example** (Creating an empty iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Array.from(Iterable.empty<string>()) // => []\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => constEmpty;\n/**\n * Creates an iterable containing a single element.\n *\n * **When to use**\n *\n * Use to wrap a single value in an iterable context so it can be combined\n * with other iterable operations.\n *\n * **Example** (Wrapping a single value)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const single = Iterable.of(42)\n * Array.from(single) // => [42]\n *\n * // Useful for creating homogeneous sequences\n * const sequences = [\n * Iterable.of(\"hello\"),\n * Iterable.range(1, 3),\n * Iterable.empty<string>()\n * ]\n *\n * // Can be used with flatMap for conditional inclusion\n * const numbers = [1, 2, 3, 4, 5]\n * const evensOnly = Iterable.flatMap(\n * numbers,\n * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty()\n * )\n * Array.from(evensOnly) // => [2, 4]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const of = a => [a];\n/**\n * Transforms each element of an iterable using a function.\n *\n * **Details**\n *\n * This is one of the most fundamental operations for working with iterables.\n * It applies a transformation function to each element, creating a new iterable\n * with the transformed values. The operation is lazy, so elements are only\n * transformed when the iterable is consumed.\n *\n * **Example** (Mapping elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Transform numbers to their squares\n * const numbers = [1, 2, 3, 4, 5]\n * const squares = Iterable.map(numbers, (x) => x * x)\n * Array.from(squares) // => [1, 4, 9, 16, 25]\n *\n * // Use index in transformation\n * const indexed = Iterable.map([\"a\", \"b\", \"c\"], (char, i) => `${i}: ${char}`)\n * Array.from(indexed) // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * Array.from(Iterable.map(\n * Iterable.map([1, 2, 3], (x) => x * 2),\n * (x) => x + 1\n * )) // => [3, 5, 7]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n return {\n done: false,\n value: f(result.value, i++)\n };\n }\n };\n }\n}));\n/**\n * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements.\n *\n * **Example** (Flat mapping iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Expand each number to a range\n * const numbers = [1, 2, 3]\n * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n))\n * Array.from(expanded) // => [1, 1, 2, 1, 2, 3]\n *\n * // Split strings into characters\n * const words = [\"hi\", \"bye\"]\n * const chars = Iterable.flatMap(words, (word) => word)\n * Array.from(chars) // => [\"h\", \"i\", \"b\", \"y\", \"e\"]\n *\n * // Conditional expansion with empty iterables\n * const values = [1, 2, 3, 4, 5]\n * const evenMultiples = Iterable.flatMap(\n * values,\n * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : []\n * )\n * Array.from(evenMultiples) // => [2, 4, 6, 4, 8, 12]\n *\n * // Use index in transformation\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.flatMap(\n * letters,\n * (letter, i) => Iterable.replicate(letter, i + 1)\n * )\n * Array.from(indexed) // => [\"a\", \"b\", \"b\", \"c\", \"c\", \"c\"]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatMap = /*#__PURE__*/dual(2, (self, f) => flatten(map(self, f)));\n/**\n * Flattens an Iterable of Iterables into a single Iterable\n *\n * **Example** (Flattening nested iterables)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Flatten nested arrays\n * const nested = [[1, 2], [3, 4], [5, 6]]\n * const flat = Iterable.flatten(nested)\n * Array.from(flat) // => [1, 2, 3, 4, 5, 6]\n *\n * // Flatten different iterable types\n * const mixed: Array<Iterable<string>> = [\"ab\", \"cd\"]\n * const flatMixed = Iterable.flatten(mixed)\n * Array.from(flatMixed) // => [\"a\", \"b\", \"c\", \"d\"]\n *\n * // Flatten deeply nested (only one level)\n * const deepNested = [[[1, 2]], [[3, 4]]]\n * const oneLevelFlat = Iterable.flatten(deepNested)\n * Array.from(oneLevelFlat) // => [[1, 2], [3, 4]]\n * // [[1, 2], [3, 4]] (still contains arrays)\n *\n * // Empty iterables are handled correctly\n * const withEmpty = [[1, 2], [], [3, 4], []]\n * const flatWithEmpty = Iterable.flatten(withEmpty)\n * Array.from(flatWithEmpty) // => [1, 2, 3, 4]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 2.0.0\n */\nexport const flatten = self => ({\n [Symbol.iterator]() {\n const outerIterator = self[Symbol.iterator]();\n let innerIterator;\n function next() {\n while (true) {\n if (innerIterator === undefined) {\n const next = outerIterator.next();\n if (next.done) {\n return next;\n }\n innerIterator = next.value[Symbol.iterator]();\n }\n const result = innerIterator.next();\n if (!result.done) {\n return result;\n }\n innerIterator = undefined;\n }\n }\n return {\n next\n };\n }\n});\n/**\n * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values.\n *\n * **Details**\n *\n * This combines mapping and filtering in a single operation. The function is\n * applied to each element, and only elements that result in `Result.succeed`\n * are included in the result.\n *\n * **Example** (Filtering and transforming Result values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse strings to numbers, keeping only valid ones\n * const strings = [\"1\", \"2\", \"invalid\", \"4\", \"not-a-number\"]\n * const numbers = Iterable.filterMap(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 4]\n *\n * // Extract specific properties from objects\n * const users = [\n * { name: \"Alice\", age: 25, email: \"alice@example.com\" },\n * { name: \"Bob\", age: 17, email: undefined },\n * { name: \"Charlie\", age: 30, email: \"charlie@example.com\" },\n * { name: \"David\", age: 16, email: undefined }\n * ]\n * const adultEmails = Iterable.filterMap(\n * users,\n * (user) =>\n * user.age >= 18 && user.email ? Result.succeed(user.email) : Result.failVoid\n * )\n * Array.from(adultEmails) // => [\"alice@example.com\", \"charlie@example.com\"]\n *\n * // Use index in transformation\n * const items = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const evenIndexItems = Iterable.filterMap(\n * items,\n * (item, i) => i % 2 === 0 ? Result.succeed(`${i}: ${item}`) : Result.failVoid\n * )\n * Array.from(evenIndexItems) // => [\"0: a\", \"2: c\", \"4: e\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMap = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms all elements of the `Iterable` for as long as the specified function succeeds.\n *\n * **Example** (Filtering and transforming until failure)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * // Parse numbers until we hit an invalid one\n * const strings = [\"1\", \"2\", \"3\", \"invalid\", \"4\", \"5\"]\n * const numbers = Iterable.filterMapWhile(strings, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? Result.failVoid : Result.succeed(num)\n * })\n * Array.from(numbers) // => [1, 2, 3]\n *\n * // Take elements while they meet a condition and transform them\n * const values = [2, 4, 6, 7, 8, 10]\n * const doubledEvens = Iterable.filterMapWhile(\n * values,\n * (n) => n % 2 === 0 ? Result.succeed(n * 2) : Result.failVoid\n * )\n * Array.from(doubledEvens) // => [4, 8, 12]\n *\n * // Process with index until condition fails\n * const letters = [\"a\", \"b\", \"c\", \"d\", \"e\"]\n * const indexedUntilC = Iterable.filterMapWhile(\n * letters,\n * (letter, i) => letter !== \"c\" ? Result.succeed(`${i}: ${letter}`) : Result.failVoid\n * )\n * Array.from(indexedUntilC) // => [\"0: a\", \"1: b\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filterMapWhile = /*#__PURE__*/dual(2, (self, f) => ({\n [Symbol.iterator]() {\n let iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n if (iterator !== undefined) {\n const result = iterator.next();\n if (!result.done) {\n const next = f(result.value, i++);\n if (R.isSuccess(next)) {\n return {\n done: false,\n value: next.success\n };\n }\n }\n iterator = undefined;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Retrieves the `Some` values from an `Iterable` of `Option`s.\n *\n * **Example** (Extracting Some values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])) // => [1, 2]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const getSomes = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (O.isSome(result.value)) {\n return {\n done: false,\n value: result.value.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the failure values from an iterable of\n * `Result`s, skipping successful results.\n *\n * **Example** (Extracting failures)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getFailures([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [\"err\"]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 4.0.0\n */\nexport const getFailures = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isFailure(result.value)) {\n return {\n done: false,\n value: result.value.failure\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Returns a lazy iterable containing the success values from an iterable of\n * `Result`s, skipping failed results.\n *\n * **Example** (Extracting successes)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Result } from \"effect\"\n *\n * Array.from(Iterable.getSuccesses([\n * Result.succeed(1),\n * Result.fail(\"err\"),\n * Result.succeed(2)\n * ])) // => [1, 2]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 4.0.0\n */\nexport const getSuccesses = self => {\n return {\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (R.isSuccess(result.value)) {\n return {\n done: false,\n value: result.value.success\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n };\n};\n/**\n * Filters an iterable to only include elements that match a predicate.\n *\n * **Details**\n *\n * This function creates a new iterable containing only the elements for which\n * the predicate function returns true. Like map, this operation is lazy and\n * elements are only tested when the iterable is consumed.\n *\n * **Example** (Filtering elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Filter even numbers\n * const numbers = [1, 2, 3, 4, 5, 6]\n * const evens = Iterable.filter(numbers, (x) => x % 2 === 0)\n * Array.from(evens) // => [2, 4, 6]\n *\n * // Filter with index\n * const items = [\"a\", \"b\", \"c\", \"d\"]\n * const oddPositions = Iterable.filter(items, (_, i) => i % 2 === 1)\n * Array.from(oddPositions) // => [\"b\", \"d\"]\n *\n * // Type refinement\n * const mixed: Array<string | number> = [\"hello\", 42, \"world\", 100]\n * const onlyStrings = Iterable.filter(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * Array.from(onlyStrings) // => [\"hello\", \"world\"]\n *\n * // Combine with map\n * const processed = Iterable.map(\n * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2),\n * (x) => x * 10\n * )\n * Array.from(processed) // => [30, 40, 50]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const filter = /*#__PURE__*/dual(2, (self, predicate) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let i = 0;\n return {\n next() {\n let result = iterator.next();\n while (!result.done) {\n if (predicate(result.value, i++)) {\n return {\n done: false,\n value: result.value\n };\n }\n result = iterator.next();\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n}));\n/**\n * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results.\n *\n * **When to use**\n *\n * Use when working with APIs or functions that return nullable values,\n * providing a clean way to filter out null or undefined while transforming.\n *\n * **Example** (Flat mapping nullable results)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Extract valid elements from nullable function results\n * const data = [\"1\", \"2\", \"invalid\", \"4\"]\n * const parsed = Iterable.flatMapNullishOr(data, (s) => {\n * const num = parseInt(s)\n * return isNaN(num) ? null : num * 2\n * })\n * Array.from(parsed) // => [2, 4, 8]\n *\n * // Safe property access\n * const objects = [\n * { nested: { value: 10 } },\n * { nested: null },\n * { nested: { value: 20 } },\n * {}\n * ]\n * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value)\n * Array.from(values) // => [10, 20]\n *\n * // Working with Map.get (returns undefined for missing keys)\n * const map = new Map([\n * [\"a\", 1],\n * [\"b\", 2],\n * [\"c\", 3]\n * ])\n * const keys = [\"a\", \"x\", \"b\", \"y\", \"c\"]\n * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key))\n * Array.from(foundValues) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category sequencing\n * @since 4.0.0\n */\nexport const flatMapNullishOr = /*#__PURE__*/dual(2, (self, f) => filterMap(self, a => {\n const b = f(a);\n return b == null ? R.failVoid : R.succeed(b);\n}));\n/**\n * Checks whether a predicate holds true for some `Iterable` element.\n *\n * **Example** (Checking whether some element matches)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * const numbers = [1, 3, 5, 7, 8]\n * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0)\n * hasEven // => true\n *\n * const allOdd = [1, 3, 5, 7]\n * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0)\n * hasEvenInAllOdd // => false\n *\n * // With index\n * const letters = [\"a\", \"b\", \"c\"]\n * const hasElementAtIndex2 = Iterable.some(letters, (_, i) => i === 2)\n * hasElementAtIndex2 // => true\n *\n * // Early termination - stops at first match\n * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1)\n * const hasEvenInInfiniteOdds = Iterable.some(\n * Iterable.take(infiniteOdds, 1000),\n * (x) => x % 2 === 0\n * )\n * hasEvenInInfiniteOdds // => false\n *\n * // Type guard usage\n * const mixed: Array<string | number> = [1, 2, \"hello\"]\n * const hasString = Iterable.some(\n * mixed,\n * (x): x is string => typeof x === \"string\"\n * )\n * hasString // => true\n * ```\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const some = /*#__PURE__*/dual(2, (self, predicate) => {\n let i = 0;\n for (const a of self) {\n if (predicate(a, i++)) {\n return true;\n }\n }\n return false;\n});\n/**\n * Generates an iterable by repeatedly applying a function that produces the\n * next element and state.\n *\n * **Details**\n *\n * This is useful for creating iterables from a generating function that\n * maintains state. The function should return `Option.some([value, nextState])`\n * to continue or `Option.none()` to stop.\n *\n * **Example** (Unfolding state into values)\n *\n * ```ts import.meta.vitest\n * import { Iterable, Option } from \"effect\"\n *\n * // Generate Fibonacci sequence\n * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]]))\n * const first10Fib = Iterable.take(fibonacci, 10)\n * Array.from(first10Fib) // => [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]\n *\n * // Generate powers of 2 up to a limit\n * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? Option.some([n, n * 2]) : Option.none())\n * Array.from(powersOf2) // => [1, 2, 4, 8, 16, 32, 64, 128, 256, 512]\n *\n * // Generate countdown\n * const countdown = Iterable.unfold(5, (n) => n > 0 ? Option.some([n, n - 1]) : Option.none())\n * Array.from(countdown) // => [5, 4, 3, 2, 1]\n *\n * // Generate collatz sequence\n * const collatz = Iterable.unfold(7, (n) => {\n * if (n === 1) return Option.none()\n * const next = n % 2 === 0 ? n / 2 : n * 3 + 1\n * return Option.some([n, next])\n * })\n * Array.from(collatz) // => [7, 22, 11, 34, 17, 52, 26, 13, 40, 20, 10, 5, 16, 8, 4, 2]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const unfold = (b, f) => ({\n [Symbol.iterator]() {\n let next = b;\n let done = false;\n return {\n next() {\n if (!done) {\n const ab = f(next);\n if (O.isSome(ab)) {\n const [a, b] = ab.value;\n next = b;\n return {\n done: false,\n value: a\n };\n }\n done = true;\n }\n return {\n done: true,\n value: undefined\n };\n }\n };\n }\n});\n/**\n * Iterates over the `Iterable`, applying `f` to each element.\n *\n * **Example** (Iterating with side effects)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Collect each visited element\n * const numbers = [1, 2, 3, 4, 5]\n * const visited: Array<number> = []\n * Iterable.forEach(numbers, (n) => visited.push(n))\n * visited // => [1, 2, 3, 4, 5]\n *\n * // Use index in the callback\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed: Array<string> = []\n * Iterable.forEach(letters, (letter, i) => {\n * indexed.push(`${i}: ${letter}`)\n * })\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n *\n * // Side effects with any iterable\n * const results: Array<number> = []\n * Iterable.forEach(Iterable.range(1, 5), (n) => {\n * results.push(n * n)\n * })\n * results // => [1, 4, 9, 16, 25]\n *\n * // Process in chunks\n * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2)\n * const processed: Array<Array<number>> = []\n * Iterable.forEach(data, (chunk) => {\n * processed.push(Array.from(chunk))\n * })\n * processed // => [[1, 2], [3, 4], [5, 6]]\n * ```\n *\n * @stability stable\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => {\n let i = 0;\n for (const a of self) {\n f(a, i++);\n }\n});\n/**\n * Reduces an iterable to a single value by applying a function to each element and accumulating the result.\n *\n * **Details**\n *\n * This function applies a reducing function against an accumulator and each element\n * of the iterable (from left to right) to reduce it to a single value.\n *\n * **Example** (Reducing an iterable)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Sum all numbers\n * const numbers = [1, 2, 3, 4, 5]\n * const sum = Iterable.reduce(numbers, 0, (acc, n) => acc + n)\n * sum // => 15\n *\n * // Find maximum value\n * const values = [3, 1, 4, 1, 5, 9, 2]\n * Iterable.reduce(values, -Infinity, (max, value) => Math.max(max, value)) // => 9\n *\n * // Build an object from key-value pairs\n * const pairs = [[\"a\", 1], [\"b\", 2], [\"c\", 3]] as const\n * const obj = Iterable.reduce(\n * pairs,\n * {} as Record<string, number>,\n * (acc, [key, value]) => {\n * acc[key] = value\n * return acc\n * }\n * )\n * obj // => { a: 1, b: 2, c: 3 }\n *\n * // Use index in the reducer\n * const letters = [\"a\", \"b\", \"c\"]\n * const indexed = Iterable.reduce(\n * letters,\n * [] as Array<string>,\n * (acc, letter, i) => {\n * acc.push(`${i}: ${letter}`)\n * return acc\n * }\n * )\n * indexed // => [\"0: a\", \"1: b\", \"2: c\"]\n * ```\n *\n * @stability stable\n * @category folding\n * @since 2.0.0\n */\nexport const reduce = /*#__PURE__*/dual(3, (self, b, f) => {\n if (Array.isArray(self)) {\n return self.reduce(f, b);\n }\n let i = 0;\n let result = b;\n for (const n of self) {\n result = f(result, n, i++);\n }\n return result;\n});\n/**\n * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function.\n *\n * **Example** (Deduplicating adjacent elements with custom equivalence)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicates with custom equality\n * const numbers = [1, 1, 2, 2, 3, 1, 1]\n * const dedupedNumbers = Iterable.dedupeAdjacentWith(numbers, (a, b) => a === b)\n * Array.from(dedupedNumbers) // => [1, 2, 3, 1]\n *\n * // Case-insensitive deduplication\n * const words = [\"Hello\", \"HELLO\", \"world\", \"World\", \"test\"]\n * const caseInsensitive = (a: string, b: string) =>\n * a.toLowerCase() === b.toLowerCase()\n * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive)\n * Array.from(dedupedWords) // => [\"Hello\", \"world\", \"test\"]\n *\n * // Deduplication by object property\n * const users = [\n * { id: 1, name: \"Alice\" },\n * { id: 1, name: \"Alice Updated\" }, // different name, same id\n * { id: 2, name: \"Bob\" },\n * { id: 2, name: \"Bob\" },\n * { id: 3, name: \"Charlie\" }\n * ]\n * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id\n * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId)\n * Array.from(dedupedUsers, (user) => user.id) // => [1, 2, 3]\n *\n * // Approximate numeric equality\n * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0]\n * const approxEqual = (a: number, b: number) => Math.abs(a - b) < 0.1\n * const dedupedFloats = Iterable.dedupeAdjacentWith(floats, approxEqual)\n * Array.from(dedupedFloats) // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacentWith = /*#__PURE__*/dual(2, (self, isEquivalent) => ({\n [Symbol.iterator]() {\n const iterator = self[Symbol.iterator]();\n let first = true;\n let last;\n function next() {\n while (true) {\n const result = iterator.next();\n if (result.done) {\n return {\n done: true,\n value: undefined\n };\n }\n if (first) {\n first = false;\n last = result.value;\n return result;\n }\n const current = result.value;\n if (!isEquivalent(last, current)) {\n last = current;\n return result;\n }\n }\n }\n return {\n next\n };\n }\n}));\n/**\n * Deduplicates adjacent elements that are identical.\n *\n * **Example** (Deduplicating adjacent elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Remove adjacent duplicate numbers\n * const numbers = [1, 1, 2, 2, 2, 3, 1, 1]\n * const deduped = Iterable.dedupeAdjacent(numbers)\n * Array.from(deduped) // => [1, 2, 3, 1]\n *\n * // Remove adjacent duplicate characters\n * const letters = \"aabbccaa\"\n * const dedupedLetters = Iterable.dedupeAdjacent(letters)\n * Array.from(dedupedLetters) // => [\"a\", \"b\", \"c\", \"a\"]\n *\n * // Works with objects using deep equality\n * const objects = [\n * { type: \"A\" },\n * { type: \"A\" },\n * { type: \"B\" },\n * { type: \"B\" },\n * { type: \"A\" }\n * ]\n * const dedupedObjects = Iterable.dedupeAdjacent(objects)\n * Array.from(dedupedObjects, (object) => object.type) // => [\"A\", \"B\", \"A\"]\n *\n * // Clean up streaming data\n * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100]\n * const cleanedData = Iterable.dedupeAdjacent(sensorData)\n * Array.from(cleanedData) // => [100, 101, 102, 100]\n * ```\n *\n * @stability stable\n * @category filtering\n * @since 2.0.0\n */\nexport const dedupeAdjacent = /*#__PURE__*/dedupeAdjacentWith(/*#__PURE__*/Equal.asEquivalence());\n/**\n * Zips this Iterable crosswise with the specified Iterable using the specified combiner.\n *\n * **Example** (Combining cartesian products)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // Create coordinate pairs\n * const xs = [1, 2]\n * const ys = [\"a\", \"b\", \"c\"]\n * const coordinates = Iterable.cartesianWith(xs, ys, (x, y) => `(${x},${y})`)\n * Array.from(coordinates) // => [\"(1,a)\", \"(1,b)\", \"(1,c)\", \"(2,a)\", \"(2,b)\", \"(2,c)\"]\n *\n * // Generate all combinations of options\n * const sizes = [\"S\", \"M\", \"L\"]\n * const colors = [\"red\", \"blue\"]\n * const products = Iterable.cartesianWith(\n * sizes,\n * colors,\n * (size, color) => ({ size, color })\n * )\n * Array.from(products, ({ color, size }) => `${size}:${color}`) // => [\"S:red\", \"S:blue\", \"M:red\", \"M:blue\", \"L:red\", \"L:blue\"]\n *\n * // Mathematical operations on all pairs\n * const a = [1, 2, 3]\n * const b = [10, 20]\n * const mathProducts = Iterable.cartesianWith(a, b, (x, y) => x * y)\n * Array.from(mathProducts) // => [10, 20, 20, 40, 30, 60]\n *\n * // Create test data combinations\n * const userTypes = [\"admin\", \"user\"]\n * const features = [\"read\", \"write\", \"delete\"]\n * const testCases = Iterable.cartesianWith(\n * userTypes,\n * features,\n * (user, feature) => `${user}_can_${feature}`\n * )\n * Array.from(testCases) // => [\"admin_can_read\", \"admin_can_write\", \"admin_can_delete\", \"user_can_read\", \"user_can_write\", \"user_can_delete\"]\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const cartesianWith = /*#__PURE__*/dual(3, (self, that, f) => ({\n [Symbol.iterator]() {\n const cache = [];\n let iterator;\n let done = false;\n const replay = {\n [Symbol.iterator]() {\n let index = 0;\n return {\n next() {\n if (index < cache.length) {\n return {\n done: false,\n value: cache[index++]\n };\n }\n if (done) {\n return {\n done: true,\n value: undefined\n };\n }\n iterator ??= that[Symbol.iterator]();\n const result = iterator.next();\n if (result.done) {\n done = true;\n return {\n done: true,\n value: undefined\n };\n }\n cache.push(result.value);\n index++;\n return result;\n }\n };\n }\n };\n return flatMap(self, a => map(replay, b => f(a, b)))[Symbol.iterator]();\n }\n}));\n/**\n * Zips this Iterable crosswise with the specified Iterable.\n *\n * **Example** (Generating cartesian pairs)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * // All pairs of numbers and letters\n * const numbers = [1, 2, 3]\n * const letters = [\"a\", \"b\"]\n * const pairs = Iterable.cartesian(numbers, letters)\n * Array.from(pairs) // => [[1, \"a\"], [1, \"b\"], [2, \"a\"], [2, \"b\"], [3, \"a\"], [3, \"b\"]]\n *\n * // Generate coordinate grid\n * const x = [0, 1, 2]\n * const y = [0, 1]\n * const grid = Iterable.cartesian(x, y)\n * Array.from(grid) // => [[0, 0], [0, 1], [1, 0], [1, 1], [2, 0], [2, 1]]\n *\n * // All combinations for testing\n * const browsers = [\"chrome\", \"firefox\"]\n * const devices = [\"desktop\", \"mobile\", \"tablet\"]\n * const testMatrix = Iterable.cartesian(browsers, devices)\n * Array.from(testMatrix, ([browser, device]) => `${browser}:${device}`) // => [\"chrome:desktop\", \"chrome:mobile\", \"chrome:tablet\", \"firefox:desktop\", \"firefox:mobile\", \"firefox:tablet\"]\n *\n * // Empty iterable results in empty cartesian product\n * const empty = Iterable.empty<number>()\n * const withEmpty = Iterable.cartesian([1, 2], empty)\n * Array.from(withEmpty) // => []\n * ```\n *\n * @stability stable\n * @category combining\n * @since 2.0.0\n */\nexport const cartesian = /*#__PURE__*/dual(2, (self, that) => cartesianWith(self, that, (a, b) => [a, b]));\n/**\n * Computes how many elements of the iterable pass the given predicate.\n *\n * **Example** (Counting matching elements)\n *\n * ```ts import.meta.vitest\n * import { Iterable } from \"effect\"\n *\n * Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) // => 2\n * ```\n *\n * @stability stable\n * @category folding\n * @since 3.16.0\n */\nexport const countBy = /*#__PURE__*/dual(2, (self, f) => {\n let count = 0;\n let i = 0;\n for (const a of self) {\n if (f(a, i)) {\n count++;\n }\n i++;\n }\n return count;\n});\n//# sourceMappingURL=Iterable.js.map","import * as Context from \"../Context.js\";\n/** @internal */\nexport const Random = /*#__PURE__*/Context.Reference(\"effect/Random\", {\n defaultValue: () => ({\n nextIntUnsafe() {\n return Math.floor(Math.random() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;\n },\n nextDoubleUnsafe() {\n return Math.random();\n }\n })\n});\n/** @internal */\nexport const nextBetween = (min, max, draw) => {\n const value = draw * (max - min) + min;\n if (value !== max || min >= max || !Number.isFinite(max)) {\n return value;\n }\n // Rounding can reach the excluded endpoint even for a draw below 1.\n // Return its immediate predecessor, which is at least min for finite min < max.\n if (max === 0) {\n return -Number.MIN_VALUE;\n }\n const view = new DataView(new ArrayBuffer(8));\n view.setFloat64(0, max);\n const bits = view.getBigUint64(0);\n view.setBigUint64(0, max > 0 ? bits - BigInt(1) : bits + BigInt(1));\n return view.getFloat64(0);\n};\n//# sourceMappingURL=random.js.map","import * as Equal from \"./Equal.js\";\nimport { format } from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport * as Hash from \"./Hash.js\";\nimport { NodeInspectSymbol, toJson } from \"./Inspectable.js\";\nimport * as Option from \"./Option.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport { hasProperty } from \"./Predicate.js\";\nconst TypeId = \"~effect/MutableHashMap\";\n/**\n * Checks whether the specified value is a `MutableHashMap`, `false` otherwise.\n *\n * **When to use**\n *\n * Use to narrow an unknown value before treating it as a mutable hash map.\n *\n * **Details**\n *\n * The check looks for the `MutableHashMap` runtime marker.\n *\n * **Gotchas**\n *\n * The check does not validate the key or value types carried by the map.\n *\n * @see {@link MutableHashMap} for the mutable hash map interface\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isMutableHashMap = value => hasProperty(value, TypeId);\nconst MutableHashMapProto = {\n [TypeId]: TypeId,\n [Symbol.iterator]() {\n return this.backing[Symbol.iterator]();\n },\n toString() {\n return `MutableHashMap(${format(Array.from(this))})`;\n },\n toJSON() {\n return {\n _id: \"MutableHashMap\",\n values: toJson(Array.from(this))\n };\n },\n [NodeInspectSymbol]() {\n return this.toJSON();\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Creates an empty MutableHashMap.\n *\n * **When to use**\n *\n * Use to create a fresh mutable map before adding entries over time.\n *\n * **Details**\n *\n * Each call returns a new empty map instance.\n *\n * **Example** (Creating an empty map)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n *\n * // Add some entries\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n *\n * MutableHashMap.size(map) // => 2\n * ```\n *\n * @see {@link make} for creating a map from explicit entries\n * @see {@link fromIterable} for creating a map from an iterable of entries\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const empty = () => {\n const self = Object.create(MutableHashMapProto);\n self.backing = new Map();\n self.buckets = new Map();\n return self;\n};\n/**\n * Creates a MutableHashMap from a variable number of key-value pairs.\n *\n * **When to use**\n *\n * Use to create a mutable hash map from explicit entries known at the call site.\n *\n * **Example** (Creating a map from entries)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.size(map) // => 3\n * ```\n *\n * @see {@link empty} for creating an empty map\n * @see {@link fromIterable} for creating a map from an iterable of entries\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = (...entries) => fromIterable(entries);\n/**\n * Creates a MutableHashMap from an iterable collection of key-value pairs.\n *\n * **When to use**\n *\n * Use to create a mutable hash map from an existing iterable of entries.\n *\n * **Example** (Creating a map from an iterable)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const entries = [\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * ] as const\n *\n * const map = MutableHashMap.fromIterable(entries)\n *\n * MutableHashMap.get(map, \"banana\") // => Option.some(2)\n * MutableHashMap.size(map) // => 3\n *\n * // Works with any iterable\n * const fromMap = MutableHashMap.fromIterable(new Map([[\"x\", 10], [\"y\", 20]]))\n * MutableHashMap.get(fromMap, \"x\") // => Option.some(10)\n * ```\n *\n * @see {@link make} for creating a map from explicit entries\n * @see {@link empty} for creating an empty map\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const fromIterable = entries => {\n const self = empty();\n for (const [key, value] of entries) {\n set(self, key, value);\n }\n return self;\n};\n/**\n * Looks up a key in the `MutableHashMap` safely.\n *\n * **When to use**\n *\n * Use to safely read a `MutableHashMap` value for a key as an `Option`.\n *\n * **Details**\n *\n * Returns `Some(value)` when an equal key is present and `None` when the key is\n * absent.\n *\n * **Example** (Getting a value)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"key1\", 42], [\"key2\", 100])\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.get(map, \"key3\") // => Option.none()\n *\n * // Pipe-able version\n * MutableHashMap.get(\"key1\")(map) // => Option.some(42)\n * ```\n *\n * @see {@link has} for checking only whether a key is present\n * @see {@link set} for inserting or replacing a value by key\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => {\n if (self.backing.has(key)) {\n return Option.some(self.backing.get(key));\n } else if (isSimpleKey(key)) {\n return Option.none();\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return Option.none();\n }\n return getFromBucket(self, bucket, key);\n});\nconst isSimpleKey = u => typeof u !== \"object\" && typeof u !== \"function\";\n/**\n * Returns an iterable over the keys in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to iterate over the keys currently stored in a mutable hash map.\n *\n * **Example** (Reading keys)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * )\n *\n * Array.from(MutableHashMap.keys(map)) // => [\"apple\", \"banana\", \"cherry\"]\n * ```\n *\n * @see {@link values} for iterating over stored values\n * @see {@link has} for checking one key without iterating\n *\n * @stability stable\n * @category getters\n * @since 3.8.0\n */\nexport const keys = self => self.backing.keys();\n/**\n * Returns an iterable over the values in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to iterate over the values currently stored in a mutable hash map.\n *\n * **Example** (Reading values)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"apple\", 1],\n * [\"banana\", 2],\n * [\"cherry\", 3]\n * )\n *\n * const allValues = Array.from(MutableHashMap.values(map)) // => [1, 2, 3]\n *\n * // Useful for calculations\n * allValues.reduce((sum, value) => sum + value, 0) // => 6\n *\n * // Filter values\n * allValues.filter((value) => value > 1) // => [2, 3]\n * ```\n *\n * @see {@link keys} for iterating over stored keys\n *\n * @stability stable\n * @category getters\n * @since 3.8.0\n */\nexport const values = self => self.backing.values();\nconst getFromBucket = (self, bucket, key) => {\n for (let i = 0, len = bucket.length; i < len; i++) {\n if (Equal.equals(key, bucket[i])) {\n const refKey = bucket[i];\n return Option.some(self.backing.get(refKey));\n }\n }\n return Option.none();\n};\n/**\n * Checks whether the MutableHashMap contains the specified key.\n *\n * **When to use**\n *\n * Use to test whether a key is present in a `MutableHashMap` without reading\n * its value.\n *\n * **Example** (Checking for a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make([\"key1\", 42], [\"key2\", 100])\n *\n * MutableHashMap.has(map, \"key1\") // => true\n * MutableHashMap.has(map, \"key3\") // => false\n *\n * // Pipe-able version\n * MutableHashMap.has(\"key1\")(map) // => true\n * ```\n *\n * @see {@link get} for reading the value as an `Option`\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => Option.isSome(get(self, key)));\n/**\n * Sets a key-value pair in the MutableHashMap, mutating the map in place.\n * If the key already exists, its value is updated.\n *\n * **When to use**\n *\n * Use to insert a new `MutableHashMap` entry or replace an existing entry in\n * place.\n *\n * **Example** (Setting key-value pairs)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n *\n * // Add new entries\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n *\n * MutableHashMap.get(map, \"key1\") // => Option.some(42)\n * MutableHashMap.size(map) // => 2\n *\n * // Update existing entry\n * MutableHashMap.set(map, \"key1\", 999)\n * MutableHashMap.get(map, \"key1\") // => Option.some(999)\n *\n * // Pipe-able version\n * MutableHashMap.set(\"key3\", 300)(map)\n * MutableHashMap.size(map) // => 3\n * ```\n *\n * @see {@link modify} for updating an existing value with a function\n * @see {@link modifyAt} for setting or removing based on the current optional value\n * @see {@link remove} for deleting an entry by key\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => {\n if (self.backing.has(key) || isSimpleKey(key)) {\n self.backing.set(key, value);\n return self;\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n self.buckets.set(hash, [key]);\n self.backing.set(key, value);\n return self;\n }\n let refKey = getRefKey(bucket, key);\n if (refKey === undefined) {\n bucket.push(key);\n refKey = key;\n }\n self.backing.set(refKey, value);\n return self;\n});\nconst getRefKey = (bucket, key) => {\n for (let i = 0, len = bucket.length; i < len; i++) {\n if (Equal.equals(key, bucket[i])) {\n return bucket[i];\n }\n }\n};\n/**\n * Updates the value of the specified key within the MutableHashMap if it exists.\n * If the key doesn't exist, the map remains unchanged.\n *\n * **When to use**\n *\n * Use to transform an existing `MutableHashMap` value in place without\n * inserting missing keys.\n *\n * **Example** (Modifying existing values)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"count\", 5], [\"total\", 100])\n *\n * // Increment existing value\n * MutableHashMap.modify(map, \"count\", (n) => n + 1)\n * MutableHashMap.get(map, \"count\") // => Option.some(6)\n *\n * // Double existing value\n * MutableHashMap.modify(map, \"total\", (n) => n * 2)\n * MutableHashMap.get(map, \"total\") // => Option.some(200)\n *\n * // Try to modify non-existent key (no effect)\n * MutableHashMap.modify(map, \"missing\", (n) => n + 1)\n * MutableHashMap.has(map, \"missing\") // => false\n *\n * // Pipe-able version\n * MutableHashMap.modify(\"count\", (n: number) => n + 1)(map)\n * MutableHashMap.get(map, \"count\") // => Option.some(7)\n * ```\n *\n * @see {@link set} for inserting or replacing a value directly\n * @see {@link modifyAt} for handling both missing and existing keys\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(3, (self, key, f) => {\n const hasKey = self.backing.has(key);\n if (hasKey || isSimpleKey(key)) {\n if (hasKey) {\n self.backing.set(key, f(self.backing.get(key)));\n }\n return self;\n }\n const hash = Hash.hash(key);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return self;\n }\n const refKey = getRefKey(bucket, key);\n if (refKey === undefined) {\n return self;\n }\n self.backing.set(refKey, f(self.backing.get(refKey)));\n return self;\n});\n/**\n * Updates or removes the specified key using a function from the current\n * optional value to the next optional value.\n *\n * **When to use**\n *\n * Use to decide whether to insert, update, or remove a key based on its current\n * optional value.\n *\n * **Example** (Updating or removing a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap, Option } from \"effect\"\n *\n * const map = MutableHashMap.make([\"count\", 5])\n *\n * // Update existing key\n * MutableHashMap.modifyAt(\n * map,\n * \"count\",\n * (option) => Option.map(option, (n) => n * 2)\n * )\n * MutableHashMap.get(map, \"count\") // => Option.some(10)\n *\n * // Add new key\n * MutableHashMap.modifyAt(\n * map,\n * \"new\",\n * (option) => Option.isNone(option) ? Option.some(42) : option\n * )\n * MutableHashMap.get(map, \"new\") // => Option.some(42)\n *\n * // Remove key by returning None\n * MutableHashMap.modifyAt(map, \"count\", () => Option.none())\n * MutableHashMap.get(map, \"count\") // => Option.none()\n *\n * // Conditional update\n * MutableHashMap.modifyAt(\n * map,\n * \"new\",\n * (option) => Option.filter(option, (n) => n > 50) // Remove if <= 50\n * )\n * MutableHashMap.get(map, \"new\") // => Option.none()\n * ```\n *\n * @see {@link modify} for updating only when the key already exists\n * @see {@link set} for inserting or replacing directly\n * @see {@link remove} for deleting directly\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modifyAt = /*#__PURE__*/dual(3, (self, key, f) => {\n const current = get(self, key);\n const result = f(current);\n if (Option.isNone(result)) {\n if (Option.isSome(current)) {\n remove(self, key);\n }\n return self;\n }\n set(self, key, result.value);\n return self;\n});\n/**\n * Removes the specified key from the MutableHashMap, mutating the map in place.\n * If the key doesn't exist, the map remains unchanged.\n *\n * **When to use**\n *\n * Use to delete one key from a mutable hash map in place.\n *\n * **Example** (Removing a key)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.size(map) // => 3\n *\n * // Remove existing key\n * MutableHashMap.remove(map, \"key2\")\n * MutableHashMap.size(map) // => 2\n * MutableHashMap.has(map, \"key2\") // => false\n *\n * // Remove non-existent key (no effect)\n * MutableHashMap.remove(map, \"nonexistent\")\n * MutableHashMap.size(map) // => 2\n *\n * // Pipe-able version\n * MutableHashMap.remove(\"key1\")(map)\n * MutableHashMap.size(map) // => 1\n * ```\n *\n * @see {@link clear} for removing all entries\n * @see {@link modifyAt} for conditionally removing based on the current value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const remove = /*#__PURE__*/dual(2, (self, key_) => {\n if (isSimpleKey(key_)) {\n self.backing.delete(key_);\n return self;\n }\n const hash = Hash.hash(key_);\n const bucket = self.buckets.get(hash);\n if (bucket === undefined) {\n return self;\n }\n for (let i = 0, len = bucket.length; i < len; i++) {\n const bkey = bucket[i];\n if (bkey === key_ || Equal.equals(key_, bkey)) {\n self.backing.delete(bkey);\n bucket.splice(i, 1);\n break;\n }\n }\n if (bucket.length === 0) {\n self.buckets.delete(hash);\n }\n return self;\n});\n/**\n * Removes all key-value pairs from the MutableHashMap, mutating the map in place.\n * The map becomes empty after this operation.\n *\n * **When to use**\n *\n * Use to empty a mutable hash map while keeping the same map instance.\n *\n * **Example** (Clearing all entries)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.make(\n * [\"key1\", 42],\n * [\"key2\", 100],\n * [\"key3\", 200]\n * )\n *\n * MutableHashMap.size(map) // => 3\n *\n * // Clear all entries\n * MutableHashMap.clear(map)\n *\n * MutableHashMap.size(map) // => 0\n * MutableHashMap.has(map, \"key1\") // => false\n *\n * // Can still add new entries after clearing\n * MutableHashMap.set(map, \"new\", 999)\n * Array.from(map) // => [[\"new\", 999]]\n * ```\n *\n * @see {@link remove} for deleting one key\n * @see {@link empty} for creating a fresh empty map\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const clear = self => {\n self.backing.clear();\n self.buckets.clear();\n return self;\n};\n/**\n * Returns the number of key-value pairs in the MutableHashMap.\n *\n * **When to use**\n *\n * Use to read how many entries are currently stored in the mutable hash map.\n *\n * **Example** (Checking map size)\n *\n * ```ts import.meta.vitest\n * import { MutableHashMap } from \"effect\"\n *\n * const map = MutableHashMap.empty<string, number>()\n * MutableHashMap.size(map) // => 0\n *\n * MutableHashMap.set(map, \"key1\", 42)\n * MutableHashMap.set(map, \"key2\", 100)\n * MutableHashMap.size(map) // => 2\n *\n * MutableHashMap.remove(map, \"key1\")\n * MutableHashMap.size(map) // => 1\n *\n * MutableHashMap.clear(map)\n * MutableHashMap.size(map) // => 0\n * ```\n *\n * @see {@link isEmpty} for checking whether the map has no entries\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const size = self => self.backing.size;\n/**\n * Returns `true` when the `MutableHashMap` contains no key-value pairs.\n *\n * **When to use**\n *\n * Use to branch on whether a mutable map currently has any entries.\n *\n * @see {@link size} for reading the exact number of entries\n *\n * @stability stable\n * @category predicates\n * @since 2.0.0\n */\nexport const isEmpty = self => self.backing.size === 0;\n/**\n * Runs a callback for each key-value pair in the `MutableHashMap`.\n *\n * **When to use**\n *\n * Use to run a synchronous side-effecting callback for every key-value pair in\n * an existing mutable map.\n *\n * **Details**\n *\n * Iteration follows the backing map's order. The callback receives the value\n * first and the key second, matching `Map.prototype.forEach`.\n *\n * @see {@link keys} for iterating only keys\n * @see {@link values} for iterating only values\n *\n * @stability stable\n * @category traversing\n * @since 2.0.0\n */\nexport const forEach = /*#__PURE__*/dual(2, (self, f) => {\n self.backing.forEach(f);\n});\n//# sourceMappingURL=MutableHashMap.js.map","/**\n * Records and reads measurements from Effect programs.\n *\n * A `Metric<Input, State>` accepts typed update values and stores an aggregated\n * state that can be read directly or included in a snapshot. Metrics are used\n * for counters, gauges, frequencies, histograms, summaries, and timers. This\n * module includes metric constructors, update and read helpers, attributes,\n * histogram boundaries, registry snapshots, text dumps, and controls for\n * enabling runtime metrics.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Arr from \"./Array.js\";\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport { constUndefined, constVoid, dual, identity } from \"./Function.js\";\nimport { withFiberSucceed } from \"./internal/core.js\";\nimport * as InternalEffect from \"./internal/effect.js\";\nimport { FiberRuntimeMetricsKey as InternalFiberRuntimeMetricsKey } from \"./internal/fiberCachedKeys.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Order from \"./Order.js\";\nimport { pipeArguments } from \"./Pipeable.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport * as _String from \"./String.js\";\n/**\n * Service key for the current metric attributes context.\n *\n * **Example** (Accessing the current metric attributes key)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // The key is used internally by the Effect runtime to manage metric attributes\n * const key = Metric.CurrentMetricAttributesKey\n *\n * // Create metrics with base attributes\n * const requestCounter = Metric.counter(\"requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n *\n * // The CurrentMetricAttributes service provides default attributes\n * // that get applied to all metrics in the current context\n * const baseAttributes = { service: \"api\", version: \"1.0\" }\n *\n * // Use withAttributes to apply attributes to metrics\n * const taggedCounter1 = Metric.withAttributes(requestCounter, baseAttributes)\n * const program1 = Metric.update(taggedCounter1, 1)\n *\n * const taggedCounter2 = Metric.withAttributes(requestCounter, {\n * ...baseAttributes,\n * endpoint: \"/users\"\n * })\n * const program2 = Metric.update(taggedCounter2, 5)\n *\n * yield* program1\n * yield* program2\n *\n * return {\n * keyValue: key, // \"effect/Metric/CurrentMetricAttributes\"\n * keyType: typeof key, // \"string\"\n * isConstant: key === \"effect/Metric/CurrentMetricAttributes\" // true\n * }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const key = result // => { keyValue: \"effect/Metric/CurrentMetricAttributes\", keyType: \"string\", isConstant: true }\n * ```\n *\n * @stability stable\n * @category constants\n * @since 4.0.0\n */\nexport const CurrentMetricAttributesKey = \"effect/Metric/CurrentMetricAttributes\";\n/**\n * Context reference for metric attributes applied from the current Effect\n * context.\n *\n * **When to use**\n *\n * Use to provide default attributes that should be merged into metric updates\n * and reads in a scoped part of a program.\n *\n * **Details**\n *\n * The default value is an empty attribute set. Metric reads and updates merge\n * these contextual attributes with the metric's own attributes to select the\n * metric series being accessed.\n *\n * **Example** (Providing current metric attributes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Access current metric attributes\n * yield* Metric.CurrentMetricAttributes\n *\n * // Set new attributes context\n * const newAttributes = { service: \"api\", version: \"1.0\" }\n * const result = yield* Effect.provideService(\n * Effect.gen(function*() {\n * const updatedAttributes = yield* Metric.CurrentMetricAttributes\n * return updatedAttributes\n * }),\n * Metric.CurrentMetricAttributes,\n * newAttributes\n * )\n *\n * return result\n * })\n *\n * const attributes = await Effect.runPromise(program)\n * const actual = attributes // => { service: \"api\", version: \"1.0\" }\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const CurrentMetricAttributes = /*#__PURE__*/Context.Reference(CurrentMetricAttributesKey, {\n defaultValue: () => ({})\n});\nconst MetricRegistryKey = \"effect/Metric/MetricRegistry\";\n/**\n * Context reference for the metric registry in the current context.\n *\n * **When to use**\n *\n * Use when you need a custom metric registry for an isolated program or test\n * instead of the default registry.\n *\n * **Details**\n *\n * By default, the reference creates an empty `Map` the first time it is\n * resolved. Metrics register their metadata and hooks lazily in this map when\n * they are read or updated.\n *\n * **Gotchas**\n *\n * Because `Context.Reference` caches default values, the default `Map` is\n * shared by contexts that do not provide an override. Provide `MetricRegistry`\n * with a fresh `Map` when isolation matters.\n *\n * @see {@link snapshot} for reading all registered metrics from the current `Effect` context\n * @see {@link snapshotUnsafe} for reading all registered metrics from an explicit `Context`\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const MetricRegistry = /*#__PURE__*/Context.Reference(MetricRegistryKey, {\n defaultValue: () => new Map()\n});\nconst TypeId = \"~effect/Metric\";\nclass Metric$ {\n [TypeId] = TypeId;\n // The last series resolved through this metric and its contextual attributes.\n #extraAttributes;\n #series;\n // Series resolved by this metric, keyed by serialized contextual attributes.\n #cache;\n id;\n description;\n attributes;\n constructor(id, description, attributes) {\n this.id = id;\n this.description = description;\n this.attributes = attributes;\n }\n valueUnsafe(context) {\n return this.run(\"get\", undefined, context, this);\n }\n modifyUnsafe(input, context) {\n return this.run(\"modify\", input, context, this);\n }\n updateUnsafe(input, context) {\n return this.run(\"update\", input, context, this);\n }\n // Runs an operation through the wrapper chain. `slot` is the metric the\n // caller holds: it keeps its own last series, so sibling wrappers do not\n // evict each other.\n run(op, input, context, slot) {\n const hooks = this.hook(context, slot);\n return op === \"get\" ? hooks.get(context) : hooks[op](input, context);\n }\n hook(context, slot) {\n const series = this.series(context, slot);\n // The registry owns the series, so it is looked up on every update.\n const registry = Context.get(context, MetricRegistry);\n let metadata = registry.get(series.key);\n if (Predicate.isUndefined(metadata)) {\n metadata = this.metadata(series, this.createHooks());\n registry.set(series.key, metadata);\n }\n return metadata.hooks;\n }\n removeUnsafe(context) {\n Context.get(context, MetricRegistry).delete(this.series(context).key);\n }\n registerUnsafe(context, hooks) {\n const series = this.series(context);\n const key = series.key;\n // Keep the registry from registration time, so removal does not depend on\n // the context it is called from.\n const registry = Context.get(context, MetricRegistry);\n const metadata = this.metadata(series, {\n get: hooks.get,\n update: constVoid,\n modify: constVoid\n });\n registry.set(key, metadata);\n return {\n remove() {\n if (registry.get(key) === metadata) {\n registry.delete(key);\n }\n }\n };\n }\n // Series key and metadata share one merged attribute set.\n series(context, slot = this) {\n const extraAttributes = Context.get(context, CurrentMetricAttributes);\n if (extraAttributes !== slot.#extraAttributes) {\n slot.#extraAttributes = extraAttributes;\n // Finds a known set under a new object, such as a wrapper built per\n // update. The attributes are read once, so key and series agree; a\n // different key order only costs a miss.\n const extra = {\n ...extraAttributes\n };\n const seen = JSON.stringify(extra);\n const cache = this.#cache ??= new Map();\n let series = cache.get(seen);\n if (series === undefined) {\n const merged = mergeAttributes(this.attributes, extra);\n series = {\n key: makeKey(this, merged),\n attributes: seen === \"{}\" ? this.attributes : merged\n };\n // Bounds the cache for attribute values that never repeat.\n if (cache.size >= 1024) cache.clear();\n cache.set(seen, series);\n }\n slot.#series = series;\n }\n return slot.#series;\n }\n metadata(series, hooks) {\n return {\n id: this.id,\n type: this.type,\n description: this.description,\n attributes: series.attributes,\n hooks\n };\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\nconst bigint0 = /*#__PURE__*/BigInt(0);\nclass CounterMetric extends Metric$ {\n type = \"Counter\";\n #bigint;\n #incremental;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#bigint = options?.bigint ?? false;\n this.#incremental = options?.incremental ?? false;\n }\n createHooks() {\n let count = this.#bigint ? bigint0 : 0;\n const canUpdate = this.#incremental ? this.#bigint ? value => value >= bigint0 : value => value >= 0 : _value => true;\n const update = value => {\n if (canUpdate(value)) {\n count = count + value;\n }\n };\n return makeHooks(() => ({\n count,\n incremental: this.#incremental\n }), update);\n }\n}\nclass GaugeMetric extends Metric$ {\n type = \"Gauge\";\n #bigint;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#bigint = options?.bigint ?? false;\n }\n createHooks() {\n let value = this.#bigint ? BigInt(0) : 0;\n const update = input => {\n value = input;\n };\n const modify = input => {\n value = value + input;\n };\n return makeHooks(() => ({\n value\n }), update, modify);\n }\n}\nclass FrequencyMetric extends Metric$ {\n type = \"Frequency\";\n #preregisteredWords;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#preregisteredWords = options?.preregisteredWords;\n }\n createHooks() {\n const occurrences = new Map();\n if (Predicate.isNotUndefined(this.#preregisteredWords)) {\n for (const word of this.#preregisteredWords) {\n occurrences.set(word, 0);\n }\n }\n const update = word => {\n const count = occurrences.get(word) ?? 0;\n occurrences.set(word, count + 1);\n };\n return makeHooks(() => ({\n occurrences: new Map(occurrences)\n }), update);\n }\n}\nclass HistogramMetric extends Metric$ {\n type = \"Histogram\";\n #boundaries;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#boundaries = options.boundaries;\n }\n createHooks() {\n const bounds = this.#boundaries;\n const size = bounds.length;\n const values = new Uint32Array(size + 1);\n const boundaries = new Float64Array(size);\n let count = 0;\n let sum = 0;\n let min = Number.MAX_VALUE;\n let max = -Number.MAX_VALUE;\n Arr.map(Arr.sort(bounds, Order.Number), (n, i) => {\n boundaries[i] = n;\n });\n // Insert the value into the right bucket with a binary search\n const update = value => {\n let from = 0;\n let to = size;\n while (from !== to) {\n const mid = Math.floor(from + (to - from) / 2);\n const boundary = boundaries[mid];\n if (value <= boundary) {\n to = mid;\n } else {\n from = mid;\n }\n // The special case when to / from have a distance of one\n if (to === from + 1) {\n if (value <= boundaries[from]) {\n to = from;\n } else {\n from = to;\n }\n }\n }\n values[from] = values[from] + 1;\n count = count + 1;\n sum = sum + value;\n if (value < min) {\n min = value;\n }\n if (value > max) {\n max = value;\n }\n };\n const getBuckets = () => {\n const builder = Arr.allocate(size);\n let cumulated = 0;\n for (let i = 0; i < size; i++) {\n const boundary = boundaries[i];\n const value = values[i];\n cumulated = cumulated + value;\n builder[i] = [boundary, cumulated];\n }\n return builder;\n };\n return makeHooks(() => ({\n buckets: getBuckets(),\n count,\n min,\n max,\n sum\n }), update);\n }\n}\nclass SummaryMetric extends Metric$ {\n type = \"Summary\";\n #maxAge;\n #maxSize;\n #quantiles;\n constructor(id, options) {\n super(id, options?.description, attributesToRecord(options?.attributes));\n this.#maxAge = Math.max(Duration.toMillis(Duration.fromInputUnsafe(options.maxAge)), 0);\n this.#maxSize = options.maxSize;\n this.#quantiles = options.quantiles;\n }\n createHooks() {\n const sortedQuantiles = Arr.sort(this.#quantiles, Order.Number);\n const observations = Arr.allocate(this.#maxSize);\n for (const quantile of this.#quantiles) {\n if (!(quantile >= 0 && quantile <= 1)) {\n throw new Error(`Quantile must be between 0 and 1, found: ${quantile}`);\n }\n }\n let head = 0;\n let count = 0;\n let sum = 0;\n let min = Number.MAX_VALUE;\n let max = -Number.MAX_VALUE;\n const snapshot = now => {\n const builder = [];\n let i = 0;\n while (i < this.#maxSize) {\n const observation = observations[i];\n if (Predicate.isNotUndefined(observation)) {\n const [timestamp, value] = observation;\n const age = now - timestamp;\n if (age >= 0 && age <= this.#maxAge) {\n builder.push(value);\n }\n }\n i = i + 1;\n }\n const samples = Arr.sort(builder, Order.Number);\n const sampleSize = samples.length;\n if (sampleSize === 0) {\n return sortedQuantiles.map(q => [q, undefined]);\n }\n // Compute the value of the quantile in terms of rank:\n // For a given quantile `q`, return the maximum value `v` such that at\n // most `q * n` values are less than or equal to `v`.\n return sortedQuantiles.map(q => {\n if (q <= 0) return [q, samples[0]];\n if (q >= 1) return [q, samples[sampleSize - 1]];\n const index = Math.ceil(q * sampleSize) - 1;\n return [q, samples[index]];\n });\n };\n const observe = (value, timestamp) => {\n if (this.#maxSize > 0) {\n const target = head % this.#maxSize;\n observations[target] = [timestamp, value];\n head = head + 1;\n }\n count = count + 1;\n sum = sum + value;\n if (value < min) {\n min = value;\n }\n if (value > max) {\n max = value;\n }\n };\n const get = context => {\n const clock = Context.get(context, InternalEffect.ClockRef);\n const quantiles = snapshot(clock.currentTimeMillisUnsafe());\n return {\n quantiles,\n count,\n min,\n max,\n sum\n };\n };\n const update = ([value, timestamp]) => observe(value, timestamp);\n return makeHooks(get, update);\n }\n}\n// Every operation maps the context first and the input second, so wrappers\n// such as `withAttributes` address the same series for update, remove and\n// register.\nclass MetricTransform extends Metric$ {\n type;\n metric;\n mapInput;\n mapContext;\n constructor(metric, mapInput, mapContext) {\n super(metric.id, metric.description, metric.attributes);\n this.metric = metric;\n this.mapInput = mapInput;\n this.mapContext = mapContext;\n this.type = metric.type;\n }\n createHooks() {\n return this.metric.createHooks();\n }\n run(op, input, context, slot) {\n const mapped = this.mapContext(context);\n if (op !== \"get\") input = this.mapInput(input, mapped);\n const metric = this.metric;\n // A metric from another copy of this module only has the public methods.\n return metric instanceof Metric$ ? metric.run(op, input, mapped, slot) : op === \"get\" ? metric.valueUnsafe(mapped) : op === \"update\" ? metric.updateUnsafe(input, mapped) : metric.modifyUnsafe(input, mapped);\n }\n removeUnsafe(context) {\n removeUnsafe(this.metric, this.mapContext(context));\n }\n registerUnsafe(context, hooks) {\n return registerUnsafe(this.metric, this.mapContext(context), {\n get: hooks.get,\n update: constVoid,\n modify: constVoid\n });\n }\n}\n/**\n * Returns `true` if the specified value is a `Metric`, otherwise returns `false`.\n *\n * **When to use**\n *\n * Use when you need runtime type checking and ensuring that a value\n * conforms to the Metric interface before performing metric operations.\n *\n * **Example** (Checking metric values)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.isMetric(Metric.counter(\"requests\")) // => true\n * Metric.isMetric({ name: \"requests\" }) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isMetric = u => Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId;\n/**\n * Represents a Counter metric that tracks cumulative numerical values over\n * time. Counters can be incremented and decremented and provide a running total\n * of changes.\n *\n * **Details**\n *\n * The optional `description` describes the counter, and `attributes` attach\n * dimensions to it. Set `bigint` to create a counter that accepts `bigint`\n * inputs. Set `incremental` to `true` to create a counter that can only ever be\n * incremented.\n *\n * **Example** (Creating counter metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a basic counter for tracking requests\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total number of HTTP requests processed\"\n * })\n *\n * // Create an incremental-only counter for events\n * const eventCounter = Metric.counter(\"events_processed\", {\n * description: \"Events processed (increment only)\",\n * incremental: true\n * })\n *\n * // Create a bigint counter for large values\n * const bytesCounter = Metric.counter(\"bytes_transferred\", {\n * description: \"Total bytes transferred\",\n * bigint: true,\n * attributes: { service: \"file-transfer\" }\n * })\n *\n * // Update counters with values\n * yield* Metric.update(requestCounter, 1) // Increment by 1\n * yield* Metric.update(requestCounter, 5) // Increment by 5 (total: 6)\n * yield* Metric.update(eventCounter, 1) // Increment by 1\n * yield* Metric.update(bytesCounter, 1024n) // Add 1024 bytes\n *\n * // Get current counter values\n * const requestValue = yield* Metric.value(requestCounter)\n * const eventValue = yield* Metric.value(eventCounter)\n * const bytesValue = yield* Metric.value(bytesCounter)\n *\n * return { requestValue, eventValue, bytesValue }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const counts = [result.requestValue.count, result.eventValue.count, result.bytesValue.count] // => [6, 1, 1024n]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const counter = (name, options) => new CounterMetric(name, options);\n/**\n * Represents a `Gauge` metric that tracks and reports a single numerical value\n * at a specific moment.\n *\n * **When to use**\n *\n * Use when you need a metric for instantaneous values, such as memory usage or\n * CPU load.\n *\n * **Details**\n *\n * The optional `description` describes the gauge, and `attributes` attach\n * dimensions to it. Set `bigint` to create a gauge that accepts `bigint`\n * inputs.\n *\n * **Example** (Creating gauge metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a gauge for tracking memory usage\n * const memoryGauge = Metric.gauge(\"memory_usage_mb\", {\n * description: \"Current memory usage in megabytes\"\n * })\n *\n * // Create a gauge for CPU utilization\n * const cpuGauge = Metric.gauge(\"cpu_utilization\", {\n * description: \"Current CPU utilization percentage\",\n * attributes: { host: \"server-01\" }\n * })\n *\n * // Create a bigint gauge for large values\n * const diskSpaceGauge = Metric.gauge(\"disk_free_bytes\", {\n * description: \"Free disk space in bytes\",\n * bigint: true\n * })\n *\n * // Set gauge values (replaces current value)\n * yield* Metric.update(memoryGauge, 512) // Set to 512 MB\n * yield* Metric.update(cpuGauge, 85.5) // Set to 85.5%\n * yield* Metric.update(diskSpaceGauge, 1024000000n) // Set to ~1GB\n *\n * // Modify gauge values (adds to current value)\n * yield* Metric.modify(memoryGauge, 128) // Increase by 128 MB (total: 640)\n * yield* Metric.modify(cpuGauge, -10.5) // Decrease by 10.5% (total: 75%)\n *\n * // Update with new absolute values\n * yield* Metric.update(memoryGauge, 800) // Set to 800 MB (replaces 640)\n *\n * // Get current gauge values\n * const memoryValue = yield* Metric.value(memoryGauge)\n * const cpuValue = yield* Metric.value(cpuGauge)\n * const diskValue = yield* Metric.value(diskSpaceGauge)\n *\n * return { memoryValue, cpuValue, diskValue }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.memoryValue.value, result.cpuValue.value, result.diskValue.value] // => [800, 75, 1024000000n]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const gauge = (name, options) => new GaugeMetric(name, options);\n/**\n * Creates a `Frequency` metric which can be used to count the number of\n * occurrences of a string.\n *\n * **When to use**\n *\n * Use when you need a metric for counting how often a specific event or\n * incident occurs.\n *\n * **Details**\n *\n * The optional `description` describes the frequency, and `attributes` attach\n * dimensions to it. Use `preregisteredWords` to initialize occurrence counts\n * for known string values before updates arrive.\n *\n * **Example** (Creating frequency metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a frequency metric for HTTP status codes\n * const statusFrequency = Metric.frequency(\"http_status_codes\", {\n * description: \"Frequency of HTTP response status codes\",\n * preregisteredWords: [\"200\", \"404\", \"500\"] // Pre-register common codes\n * })\n *\n * // Create a frequency metric for user actions\n * const userActionFrequency = Metric.frequency(\"user_actions\", {\n * description: \"Frequency of user actions performed\",\n * attributes: { application: \"web-app\" }\n * })\n *\n * // Create a frequency metric for error types\n * const errorTypeFrequency = Metric.frequency(\"error_types\", {\n * description: \"Frequency of different error types\"\n * })\n *\n * // Record different occurrences\n * yield* Metric.update(statusFrequency, \"200\") // Success response\n * yield* Metric.update(statusFrequency, \"200\") // Another success\n * yield* Metric.update(statusFrequency, \"404\") // Not found error\n * yield* Metric.update(statusFrequency, \"500\") // Server error\n * yield* Metric.update(statusFrequency, \"200\") // Another success\n *\n * yield* Metric.update(userActionFrequency, \"login\")\n * yield* Metric.update(userActionFrequency, \"view_dashboard\")\n * yield* Metric.update(userActionFrequency, \"login\")\n * yield* Metric.update(userActionFrequency, \"logout\")\n *\n * yield* Metric.update(errorTypeFrequency, \"ValidationError\")\n * yield* Metric.update(errorTypeFrequency, \"NetworkError\")\n * yield* Metric.update(errorTypeFrequency, \"ValidationError\")\n *\n * // Get frequency counts\n * const statusCounts = yield* Metric.value(statusFrequency)\n * const actionCounts = yield* Metric.value(userActionFrequency)\n * const errorCounts = yield* Metric.value(errorTypeFrequency)\n *\n * // statusCounts.occurrences will be:\n * // Map { \"200\" => 3, \"404\" => 1, \"500\" => 1 }\n * // actionCounts.occurrences will be:\n * // Map { \"login\" => 2, \"view_dashboard\" => 1, \"logout\" => 1 }\n * // errorCounts.occurrences will be:\n * // Map { \"ValidationError\" => 2, \"NetworkError\" => 1 }\n *\n * return { statusCounts, actionCounts, errorCounts }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const counts = [\n * result.statusCounts.occurrences.get(\"200\"),\n * result.actionCounts.occurrences.get(\"login\"),\n * result.errorCounts.occurrences.get(\"ValidationError\")\n * ]\n * counts // => [3, 2, 2]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const frequency = (name, options) => new FrequencyMetric(name, options);\n/**\n * Represents a `Histogram` metric that records observations into buckets.\n *\n * **When to use**\n *\n * Use when you need a metric for measuring the distribution of values within a\n * range.\n *\n * **Details**\n *\n * The optional `description` describes the histogram, and `attributes` attach\n * dimensions to it. The required `boundaries` option defines the histogram\n * bucket boundaries.\n *\n * **Example** (Creating histogram metrics)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a histogram for API response times\n * const responseTimeHistogram = Metric.histogram(\"api_response_time\", {\n * description: \"Distribution of API response times in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 50, count: 10 })\n * // Creates buckets: 0-50ms, 50-100ms, 100-150ms, ..., 350-400ms, 400ms+\n * })\n *\n * // Create a histogram for request payload sizes\n * const payloadSizeHistogram = Metric.histogram(\"payload_size\", {\n * description: \"Distribution of request payload sizes in KB\",\n * boundaries: Metric.exponentialBoundaries({ start: 1, factor: 2, count: 8 }),\n * // Creates exponential buckets: 1KB, 2KB, 4KB, 8KB, 16KB, 32KB, 64KB, 128KB+\n * attributes: { service: \"api-gateway\" }\n * })\n *\n * // Create a histogram with custom boundaries\n * const customHistogram = Metric.histogram(\"custom_metric\", {\n * description: \"Custom distribution metric\",\n * boundaries: [0.1, 0.5, 1, 2.5, 5, 10, 25, 50, 100]\n * })\n *\n * // Record various response times\n * yield* Metric.update(responseTimeHistogram, 25) // Goes in 0-50ms bucket\n * yield* Metric.update(responseTimeHistogram, 75) // Goes in 50-100ms bucket\n * yield* Metric.update(responseTimeHistogram, 125) // Goes in 100-150ms bucket\n * yield* Metric.update(responseTimeHistogram, 200) // Goes in 150-200ms bucket\n * yield* Metric.update(responseTimeHistogram, 75) // Another 50-100ms\n *\n * // Record payload sizes\n * yield* Metric.update(payloadSizeHistogram, 3) // Goes in 2-4KB bucket\n * yield* Metric.update(payloadSizeHistogram, 15) // Goes in 8-16KB bucket\n * yield* Metric.update(payloadSizeHistogram, 0.5) // Goes in 0-1KB bucket\n *\n * // Get histogram state with distribution data\n * const responseTimeState = yield* Metric.value(responseTimeHistogram)\n * const payloadSizeState = yield* Metric.value(payloadSizeHistogram)\n *\n * // responseTimeState will contain:\n * // - buckets: [[50, 1], [100, 3], [150, 4], [200, 5], ...]\n * // - count: 5, min: 25, max: 200, sum: 500\n * // - Useful for calculating percentiles, averages, etc.\n *\n * return { responseTimeState, payloadSizeState }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.responseTimeState.count, result.responseTimeState.sum, result.payloadSizeState.count]\n * values // => [5, 500, 3]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const histogram = (name, options) => new HistogramMetric(name, options);\n/**\n * Creates a `Summary` metric that records observations and calculates quantiles\n * which takes a value as input and uses the current time.\n *\n * **When to use**\n *\n * Use when you need a metric that records statistical information about a set\n * of values, including quantiles.\n *\n * **Details**\n *\n * The optional `description` describes the summary, and `attributes` attach\n * dimensions to it. `maxAge` controls how long observations are retained,\n * `maxSize` controls how many observations are kept, and `quantiles` lists the\n * quantiles to calculate, such as `[0.5, 0.9]`.\n *\n * **Example** (Creating summary metrics)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create a summary for API response times\n * const responseTimeSummary = Metric.summary(\"api_response_time\", {\n * description: \"API response time quantiles over 5-minute windows\",\n * maxAge: Duration.minutes(5), // Keep observations for 5 minutes\n * maxSize: 1000, // Maximum 1000 observations in memory\n * quantiles: [0.5, 0.9, 0.95, 0.99] // 50th, 90th, 95th, 99th percentiles\n * })\n *\n * // Create a summary for request payload sizes\n * const payloadSizeSummary = Metric.summary(\"request_payload_size\", {\n * description: \"Request payload size distribution over 2-minute windows\",\n * maxAge: Duration.minutes(2), // Shorter window for recent trends\n * maxSize: 500, // Smaller buffer for memory efficiency\n * quantiles: [0.5, 0.75, 0.9], // Median, 75th, 90th percentiles\n * attributes: { service: \"upload-service\" }\n * })\n *\n * // Record deterministic response times\n * const responseTimes = [82, 96, 104, 118, 135, 170, 210, 240]\n * for (const responseTime of responseTimes) {\n * yield* Metric.update(responseTimeSummary, responseTime)\n * }\n *\n * // Record some payload sizes\n * yield* Metric.update(payloadSizeSummary, 1.2) // 1.2KB\n * yield* Metric.update(payloadSizeSummary, 5.8) // 5.8KB\n * yield* Metric.update(payloadSizeSummary, 15.6) // 15.6KB\n * yield* Metric.update(payloadSizeSummary, 3.4) // 3.4KB\n *\n * // Get summary statistics with quantiles\n * const responseStats = yield* Metric.value(responseTimeSummary)\n * const payloadStats = yield* Metric.value(payloadSizeSummary)\n *\n * // Both summaries include quantile information for their configured windows.\n *\n * return { responseStats, payloadStats }\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const response = result.responseStats\n * const payload = result.payloadStats\n * const responseValues = [response.count, response.min, response.max, response.sum] // => [8, 82, 240, 1155]\n * const payloadValues = [payload.count, payload.min, payload.max, payload.sum] // => [4, 1.2, 15.6, 26]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const summary = (name, options) => mapInput(summaryWithTimestamp(name, options), (input, context) => [input, Context.get(context, InternalEffect.ClockRef).currentTimeMillisUnsafe()]);\n/**\n * Creates a `Summary` metric that records observations with explicit\n * timestamps and calculates quantiles.\n *\n * **When to use**\n *\n * Use when you need a metric that records statistical information about a set\n * of values together with timestamps.\n *\n * **Details**\n *\n * Inputs to this metric are `[value, timestamp]` pairs; the current clock is\n * used when reading quantiles against the configured `maxAge`.\n *\n * The optional `description` describes the summary, and `attributes` attach\n * dimensions to it. `maxAge` controls how long observations are retained,\n * `maxSize` controls how many observations are kept, and `quantiles` lists the\n * quantiles to calculate, such as `[0.5, 0.9]`.\n *\n * **Example** (Creating summaries with explicit timestamps)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * const responseTimesSummary = Metric.summaryWithTimestamp(\n * \"response_times_summary\",\n * {\n * description: \"Measures the distribution of response times\",\n * maxAge: \"60 seconds\", // Retain observations for 60 seconds.\n * maxSize: 1000, // Keep a maximum of 1000 observations.\n * quantiles: [0.5, 0.9, 0.99] // Calculate 50th, 90th, and 99th quantiles.\n * }\n * )\n * const metadata = [responseTimesSummary.id, responseTimesSummary.type] // => [\"response_times_summary\", \"Summary\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const summaryWithTimestamp = (name, options) => new SummaryMetric(name, options);\n/**\n * Creates a timer metric, based on a `Histogram`, which keeps track of\n * durations in milliseconds.\n *\n * **Details**\n *\n * The unit of time will automatically be added to the metric as a tag (i.e.\n * `\"time_unit: milliseconds\"`).\n *\n * If `options.boundaries` is not provided, the boundaries will be computed\n * using `Metric.exponentialBoundaries({ start: 0.5, factor: 2, count: 35 })`.\n *\n * **Example** (Recording durations with a timer)\n *\n * ```ts import.meta.vitest\n * import { Duration, Effect, Metric } from \"effect\"\n *\n * // Create a timer metric to track API request durations\n * const apiRequestTimer = Metric.timer(\"api_request_duration\", {\n * description: \"Duration of API requests\",\n * attributes: { service: \"user-api\" }\n * })\n *\n * // Record a measured API operation duration\n * const apiOperation = Effect.gen(function*() {\n * const duration = Duration.millis(120)\n * yield* Metric.update(apiRequestTimer, duration)\n *\n * const state = yield* Metric.value(apiRequestTimer)\n * return {\n * count: state.count,\n * min: state.min,\n * max: state.max,\n * sum: state.sum\n * }\n * })\n *\n * await Effect.runPromise(\n * Effect.provideService(apiOperation, Metric.MetricRegistry, new Map())\n * ) // => { count: 1, min: 120, max: 120, sum: 120 }\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const timer = (name, options) => {\n const boundaries = Predicate.isNotUndefined(options?.boundaries) ? options.boundaries : exponentialBoundaries({\n start: 0.5,\n factor: 2,\n count: 35\n });\n const attributes = mergeAttributes(options?.attributes, {\n time_unit: \"milliseconds\"\n });\n const metric = new HistogramMetric(name, {\n ...options,\n boundaries,\n attributes\n });\n return mapInput(metric, Duration.toMillis);\n};\n/**\n * Retrieves the current state of the specified `Metric`.\n *\n * **Details**\n *\n * The returned state depends on the metric type. Counters return\n * `CounterState<number | bigint>` with `count` and `incremental`, gauges return\n * `GaugeState<number | bigint>` with `value`, frequencies return\n * `FrequencyState` with `occurrences`, histograms return `HistogramState` with\n * buckets, count, min, max, and sum, and summaries return `SummaryState` with\n * quantiles, count, min, max, and sum.\n *\n * **Example** (Reading metric state)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"modify_requests\")\n * const responseTime = Metric.histogram(\"response_time\", {\n * boundaries: [100, 500, 1000, 2000]\n * })\n *\n * const program = Effect.gen(function*() {\n * // Update metrics\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 750)\n *\n * // Get current values\n * const counterState = yield* Metric.value(requestCounter)\n * const histogramState = yield* Metric.value(responseTime)\n * return {\n * requestCount: counterState.count,\n * count: histogramState.count,\n * min: histogramState.min,\n * max: histogramState.max,\n * average: histogramState.sum / histogramState.count\n * }\n * })\n *\n * await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * ) // => { requestCount: 1, count: 1, min: 750, max: 750, average: 750 }\n * ```\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const value = self => withFiberSucceed(fiber => self.valueUnsafe(fiber.context));\n/**\n * Modifies the metric with the specified input.\n *\n * **Details**\n *\n * The behavior of `modify` depends on the metric type. Counters add the input\n * value to the current count, gauges add the input value to the current gauge\n * value, frequencies increment the occurrence count for the input string,\n * histograms record the input value in the appropriate bucket, and summaries\n * record the input observation.\n *\n * **Example** (Modifying metric values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const temperatureGauge = Metric.gauge(\"temperature\")\n * const requestCounter = Metric.counter(\"requests\")\n *\n * const program = Effect.gen(function*() {\n * // Set initial temperature\n * yield* Metric.update(temperatureGauge, 20)\n *\n * // Modify by adding/subtracting values\n * yield* Metric.modify(temperatureGauge, 5) // Now 25\n * yield* Metric.modify(temperatureGauge, -3) // Now 22\n *\n * // For counters, modify increments by the specified amount\n * yield* Metric.modify(requestCounter, 10) // Add 10 to counter\n * yield* Metric.modify(requestCounter, 5) // Add 5 more (total: 15)\n *\n * const temp = yield* Metric.value(temperatureGauge)\n * const requests = yield* Metric.value(requestCounter)\n * return [temp.value, requests.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [22, 15]\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 3.6.5\n */\nexport const modify = /*#__PURE__*/dual(2, (self, input) => withFiberSucceed(fiber => self.modifyUnsafe(input, fiber.context)));\n/**\n * Updates the metric with the specified input.\n *\n * **Details**\n *\n * The behavior of `update` depends on the metric type. Counters add the input\n * value to the current count, gauges replace the current value with the input\n * value, frequencies increment the occurrence count for the input string,\n * histograms record the input value in the appropriate bucket, and summaries\n * record the input value as a new observation.\n *\n * **Example** (Updating metric values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const cpuUsage = Metric.gauge(\"cpu_usage_percent\")\n * const httpStatus = Metric.frequency(\"http_status_codes\")\n * const responseTime = Metric.histogram(\"response_time_ms\", {\n * boundaries: [100, 500, 1000, 2000]\n * })\n *\n * const program = Effect.gen(function*() {\n * // Update gauge to specific values\n * yield* Metric.update(cpuUsage, 45.2)\n * yield* Metric.update(cpuUsage, 67.8) // Replaces previous value\n *\n * // Track HTTP status code occurrences\n * yield* Metric.update(httpStatus, \"200\")\n * yield* Metric.update(httpStatus, \"404\")\n * yield* Metric.update(httpStatus, \"200\") // Increments 200 count\n *\n * // Record response times\n * yield* Metric.update(responseTime, 250)\n * yield* Metric.update(responseTime, 750)\n * yield* Metric.update(responseTime, 1500)\n *\n * // Check current states\n * const cpu = yield* Metric.value(cpuUsage)\n * const statuses = yield* Metric.value(httpStatus)\n * const times = yield* Metric.value(responseTime)\n * return [cpu.value, statuses.occurrences.get(\"200\"), times.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [67.8, 2, 3]\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, input) => withFiberSucceed(fiber => self.updateUnsafe(input, fiber.context)));\n/**\n * Removes the series of a metric for the current attributes from the metric\n * registry.\n *\n * **When to use**\n *\n * Use when a series describes something that has gone away, such as a\n * connection or an entity, so the registry and exporters stop tracking it.\n *\n * **Details**\n *\n * The series is identified the same way `update` identifies it: by the metric\n * and its attributes merged with `CurrentMetricAttributes`. Other series of the\n * same metric are left alone. A later update creates the series again from its\n * initial state. Removing a series that does not exist does nothing.\n *\n * **Example** (Removing a series)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const connections = Metric.gauge(\"connections\")\n *\n * const program = Effect.gen(function*() {\n * yield* Metric.update(connections, 3).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"a\" })\n * )\n * yield* Metric.update(connections, 5).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"b\" })\n * )\n * yield* Metric.remove(connections).pipe(\n * Effect.provideService(Metric.CurrentMetricAttributes, { pool: \"a\" })\n * )\n * const snapshots = yield* Metric.snapshot\n * return snapshots.map((snapshot) => snapshot.attributes)\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [{ pool: \"b\" }]\n * ```\n *\n * @see {@link removeUnsafe} for removing a series with an explicit `Context`\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const remove = self => withFiberSucceed(fiber => removeUnsafe(self, fiber.context));\n/**\n * Removes the series of a metric for the attributes in the provided `Context`\n * from the metric registry in that `Context`.\n *\n * **When to use**\n *\n * Use when a low-level integration already holds a `Context`. Use `remove`\n * in application code.\n *\n * @see {@link remove} for the `Effect` version\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const removeUnsafe = (self, context) => self.removeUnsafe(context);\n/**\n * Registers a series backed by caller-supplied hooks, for gauges whose value is\n * read when metrics are snapshotted rather than pushed with updates.\n *\n * **When to use**\n *\n * Use when the value already lives in some data structure, such as a queue\n * size, and updating a metric on every change would cost more than reading the\n * value at export time.\n *\n * **Details**\n *\n * The series is identified as in `remove`, using the attributes and registry\n * from `context`, and replaces any series with the same identity. `hooks.get`\n * is called each time the series is read, for example by `snapshot` or an\n * exporter. The returned {@link Registration} removes it again.\n * `update` and `modify` on this series do nothing; the supplied mutation hooks\n * are ignored.\n *\n * **Gotchas**\n *\n * The registry keeps `hooks.get` reachable until the series is removed, along\n * with anything it closes over. Call `remove` once the source goes away.\n *\n * **Example** (Reporting a queue size on snapshot)\n *\n * ```ts import.meta.vitest\n * import { Context, Metric } from \"effect\"\n *\n * const context = Context.make(Metric.MetricRegistry, new Map())\n * const queueSize = Metric.gauge(\"queue_size\")\n * const queue: Array<string> = [\"a\", \"b\"]\n *\n * const registration = Metric.registerUnsafe(queueSize, context, {\n * get: () => ({ value: queue.length }),\n * update: () => {},\n * modify: () => {}\n * })\n * queue.push(\"c\")\n * const sizes = Metric.snapshotUnsafe(context).map((snapshot) => snapshot.state)\n * registration.remove()\n *\n * sizes // => [{ value: 3 }]\n * Metric.snapshotUnsafe(context).length // => 0\n * ```\n *\n * @see {@link remove} for removing a series updated with `update`\n *\n * @stability unstable\n * @category mutations\n * @since 4.0.6\n */\nexport const registerUnsafe = (self, context, hooks) => self.registerUnsafe(context, hooks);\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of the specified new type, which must be transformable to the input type of\n * this metric.\n *\n * **Example** (Mapping metric inputs)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const durationHistogram = Metric.histogram(\"request_duration_ms\", {\n * description: \"Request duration in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 100, count: 10 })\n * })\n *\n * // Accept duration strings while recording numeric milliseconds\n * const durationStringHistogram = Metric.mapInput(\n * durationHistogram,\n * (input: string) => Number(input)\n * )\n *\n * const program = Effect.gen(function*() {\n * yield* Metric.update(durationStringHistogram, \"250\")\n * return yield* Metric.value(durationStringHistogram)\n * })\n *\n * const value = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [value.count, value.sum] // => [1, 250]\n * ```\n *\n * @stability stable\n * @category annotations\n * @since 2.0.0\n */\nexport const mapInput = /*#__PURE__*/dual(2, (self, f) => new MetricTransform(self, f, identity));\n/**\n * Returns a new metric that is powered by this one, but which accepts updates\n * of any type, and translates them to updates with the specified constant\n * update value.\n *\n * **Example** (Ignoring inputs with a constant value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * // Create a counter that normally expects a number increment\n * const requestCounter = Metric.counter(\"total_requests\", {\n * description: \"Total number of requests processed\"\n * })\n *\n * // Create a version that always increments by 1, regardless of input\n * const simpleRequestCounter = Metric.withConstantInput(requestCounter, 1)\n *\n * const program = Effect.gen(function*() {\n * // These all increment the counter by 1, ignoring the input value\n * yield* Metric.update(simpleRequestCounter, \"any string\")\n * yield* Metric.update(simpleRequestCounter, { complex: \"object\" })\n * yield* Metric.update(simpleRequestCounter, 999) // Still increments by 1\n *\n * const value = yield* Metric.value(simpleRequestCounter)\n * return value // Counter state will show count: 3\n * })\n *\n * const value = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const count = value.count // => 3\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const withConstantInput = /*#__PURE__*/dual(2, (self, input) => mapInput(self, () => input));\n/**\n * Returns a new metric that applies the specified attributes to all operations.\n *\n * **Details**\n *\n * Attributes are key-value pairs that provide additional context for metrics,\n * enabling filtering, grouping, and more detailed analysis. Each combination\n * of attribute values creates a separate metric series.\n *\n * **Example** (Applying metric attributes)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n *\n * // Create tagged versions of the metric\n * const getRequests = Metric.withAttributes(requestCounter, {\n * method: \"GET\",\n * endpoint: \"/api/users\"\n * })\n *\n * const postRequests = Metric.withAttributes(requestCounter, {\n * method: \"POST\",\n * endpoint: \"/api/users\"\n * })\n *\n * const program = Effect.gen(function*() {\n * // These will be tracked as separate metric series\n * yield* Metric.update(getRequests, 1) // http_requests_total{method=\"GET\", endpoint=\"/api/users\"}\n * yield* Metric.update(postRequests, 1) // http_requests_total{method=\"POST\", endpoint=\"/api/users\"}\n * yield* Metric.update(getRequests, 1) // Increments the GET counter\n *\n * // You can also chain attributes\n * const taggedMetric = requestCounter.pipe(\n * Metric.withAttributes({ service: \"user-api\" }),\n * Metric.withAttributes({ version: \"v1\" })\n * )\n *\n * yield* Metric.update(taggedMetric, 1) // http_requests_total{service=\"user-api\", version=\"v1\"}\n * })\n *\n * const result = Effect.gen(function*() {\n * yield* program\n * const get = yield* Metric.value(getRequests)\n * const post = yield* Metric.value(postRequests)\n * return [get.count, post.count] as const\n * })\n *\n * await Effect.runPromise(Effect.provideService(result, Metric.MetricRegistry, new Map())) // => [2, 1]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 4.0.0\n */\nexport const withAttributes = /*#__PURE__*/dual(2, (self, attributes) => {\n return new MetricTransform(self, identity, addAttributesToContext(attributes));\n});\n// Metric Snapshots\n/**\n * Captures a snapshot of all registered metrics in the current context.\n *\n * **Details**\n *\n * Returns an array of metric snapshots, each containing the metric's metadata\n * (name, description, type) and current state (values, counts, etc.).\n *\n * **Example** (Capturing metric snapshots)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create and update some metrics\n * const requestCounter = Metric.counter(\"http_requests\", {\n * description: \"Total HTTP requests\"\n * })\n * const responseTime = Metric.histogram(\"response_time_ms\", {\n * description: \"Response time in milliseconds\",\n * boundaries: Metric.linearBoundaries({ start: 0, width: 100, count: 5 })\n * })\n *\n * // Update the metrics with some values\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 150)\n * yield* Metric.update(responseTime, 75)\n *\n * // Take a snapshot of all metrics\n * const snapshots = yield* Metric.snapshot\n *\n * return snapshots\n * })\n *\n * const snapshots = await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * )\n * const ids = snapshots.map((snapshot) => snapshot.id).sort() // => [\"http_requests\", \"response_time_ms\"]\n * ```\n *\n * @stability stable\n * @category snapshotting\n * @since 2.0.0\n */\nexport const snapshot = /*#__PURE__*/withFiberSucceed(fiber => snapshotUnsafe(fiber.context));\n/**\n * Returns a human-readable string representation of all currently registered\n * metrics in a tabular format.\n *\n * **Details**\n *\n * This debugging utility captures a snapshot of all metrics and formats them\n * in an easy-to-read table showing names, descriptions, types, attributes,\n * and current state values.\n *\n * **Example** (Dumping metrics as text)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Create and update some metrics for demonstration\n * const requestCounter = Metric.counter(\"http_requests_total\", {\n * description: \"Total HTTP requests\"\n * })\n * const responseTime = Metric.gauge(\"response_time_ms\", {\n * description: \"Current response time in milliseconds\"\n * })\n * const statusFreq = Metric.frequency(\"http_status_codes\", {\n * description: \"Frequency of HTTP status codes\"\n * })\n *\n * // Update metrics with some values\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(requestCounter, 1)\n * yield* Metric.update(responseTime, 125)\n * yield* Metric.update(statusFreq, \"200\")\n * yield* Metric.update(statusFreq, \"404\")\n * yield* Metric.update(statusFreq, \"200\")\n *\n * // Get formatted dump of all metrics\n * const metricsReport = yield* Metric.dump\n * return metricsReport\n * })\n *\n * const report = await Effect.runPromise(\n * Effect.provideService(program, Metric.MetricRegistry, new Map())\n * )\n * const included = [\n * report.includes(\"http_requests_total\"),\n * report.includes(\"response_time_ms\"),\n * report.includes(\"http_status_codes\")\n * ]\n * included // => [true, true, true]\n * ```\n *\n * @stability stable\n * @category formatting\n * @since 4.0.0\n */\nexport const dump = /*#__PURE__*/withFiberSucceed(fiber => {\n const metrics = snapshotUnsafe(fiber.context);\n if (metrics.length > 0) {\n const maxNameLength = metrics.reduce((max, metric) => {\n const length = metric.id.length;\n return length > max ? length : max;\n }, 0) + 2;\n const maxDescriptionLength = metrics.reduce((max, metric) => {\n const length = Predicate.isNotUndefined(metric.description) ? metric.description.length : 0;\n return length > max ? length : max;\n }, 0) + 2;\n const maxTypeLength = metrics.reduce((max, metric) => {\n const length = metric.type.length;\n return length > max ? length : max;\n }, 0) + 2;\n const maxAttributesLength = metrics.reduce((max, metric) => {\n const length = Predicate.isNotUndefined(metric.attributes) ? attributesToString(metric.attributes).length : 0;\n return length > max ? length : max;\n }, 0) + 2;\n const grouped = Object.entries(Arr.groupBy(metrics, metric => metric.id));\n const sorted = Arr.sortWith(grouped, entry => entry[0], _String.Order);\n const rendered = sorted.map(([, group]) => group.map(metric => renderName(metric, maxNameLength) + renderDescription(metric, maxDescriptionLength) + renderType(metric, maxTypeLength) + renderAttributes(metric, maxAttributesLength) + renderState(metric)).join(\"\\n\")).join(\"\\n\");\n return rendered;\n }\n return \"\";\n});\n/**\n * Captures a snapshot of all registered metrics synchronously using the provided\n * service context.\n *\n * **When to use**\n *\n * Use to read metric snapshots from an explicit `Context` in low-level\n * integrations, exporters, or debugging tools that already have the context.\n *\n * **Details**\n *\n * This is the \"unsafe\" version that bypasses Effect's safety guarantees and requires\n * manual handling of the services context. Use the safe `snapshot` function for normal\n * application code.\n *\n * **Example** (Capturing snapshots from a context)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const requestCounter = Metric.counter(\"http_requests\")\n * const program = Effect.gen(function*() {\n * yield* Metric.update(requestCounter, 1)\n * const context = yield* Effect.context()\n * return Metric.snapshotUnsafe(context).map((snapshot) => snapshot.id)\n * })\n *\n * await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map())) // => [\"http_requests\"]\n * ```\n *\n * @stability stable\n * @category snapshotting\n * @since 4.0.0\n */\nexport const snapshotUnsafe = context => {\n const registry = Context.get(context, MetricRegistry);\n return Array.from(registry.values()).map(({\n hooks,\n ...meta\n }) => ({\n ...meta,\n state: hooks.get(context)\n }));\n};\nconst renderName = (metric, padTo) => `name=${metric.id.padEnd(padTo, \" \")}`;\nconst renderDescription = (metric, padTo) => `description=${(metric.description ?? \"\").padEnd(padTo, \" \")}`;\nconst renderType = (metric, padTo) => `type=${metric.type.padEnd(padTo, \" \")}`;\nconst renderAttributes = (metric, padTo) => {\n const attrs = attributesToString(metric.attributes ?? {});\n const padding = \" \".repeat(Math.max(0, padTo - attrs.length));\n return `${attrs}${padding}`;\n};\nconst renderState = metric => {\n const prefix = \"state=\";\n switch (metric.type) {\n case \"Counter\":\n {\n const state = metric.state;\n return `${prefix}[count: [${state.count}]]`;\n }\n case \"Frequency\":\n {\n const state = metric.state;\n return `${prefix}[occurrences: ${renderKeyValues(state.occurrences)}]`;\n }\n case \"Gauge\":\n {\n const state = metric.state;\n return `${prefix}[value: [${state.value}]]`;\n }\n case \"Histogram\":\n {\n const state = metric.state;\n const buckets = `buckets: [${renderKeyValues(state.buckets)}]`;\n const count = `count: [${state.count}]`;\n const min = `min: [${state.min}]`;\n const max = `max: [${state.max}]`;\n const sum = `sum: [${state.sum}]`;\n return `${prefix}[${buckets}, ${count}, ${min}, ${max}, ${sum}]`;\n }\n case \"Summary\":\n {\n const state = metric.state;\n const printableQuantiles = state.quantiles.map(([key, value]) => [key, value ?? 0]);\n const quantiles = `quantiles: [${renderKeyValues(printableQuantiles)}]`;\n const count = `count: [${state.count}]`;\n const min = `min: [${state.min}]`;\n const max = `max: [${state.max}]`;\n const sum = `sum: [${state.sum}]`;\n return `${prefix}[${quantiles}, ${count}, ${min}, ${max}, ${sum}]`;\n }\n }\n};\nconst renderKeyValues = keyValues => Array.from(keyValues).map(([key, value]) => `(${key} -> ${value})`).join(\", \");\nconst attributesToString = attributes => {\n const attrs = Object.entries(attributes);\n const sorted = Arr.sortWith(attrs, attr => attr[0], _String.Order);\n return `attributes=[${sorted.map(([key, value]) => `${key}: ${value}`).join(\", \")}]`;\n};\n// Metric Boundaries\n/**\n * Creates histogram bucket boundaries from an iterable set of values.\n *\n * **Details**\n *\n * Processes any iterable of numbers by removing duplicates, filtering out\n * non-positive values, and automatically appending positive infinity as the\n * final boundary.\n *\n * **Example** (Creating boundaries from values)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.boundariesFromIterable([-5, 0, 10, 10, 25, 50]) // => [10, 25, 50, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const boundariesFromIterable = iterable => Arr.append(Arr.filter(new Set(iterable), n => n > 0), Number.POSITIVE_INFINITY);\n/**\n * Creates histogram bucket boundaries from a linear sequence and appends\n * positive infinity.\n *\n * **Details**\n *\n * Generates `count - 1` candidate boundaries using `start + index * width` for\n * each zero-based index, then applies the same normalization as\n * `boundariesFromIterable`: non-positive values are removed, duplicates are\n * collapsed, and `Infinity` is appended.\n *\n * **Example** (Creating linear boundaries)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.linearBoundaries({ start: 10, width: 20, count: 5 }) // => [10, 30, 50, 70, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const linearBoundaries = options => boundariesFromIterable(Arr.makeBy(options.count - 1, n => options.start + n * options.width));\n/**\n * Creates histogram bucket boundaries with exponentially increasing values.\n *\n * **Details**\n *\n * Creates boundaries that grow exponentially, useful for metrics that span\n * multiple orders of magnitude. Each boundary is calculated as start * factor^i.\n *\n * **Example** (Creating exponential boundaries)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.exponentialBoundaries({ start: 1, factor: 2, count: 5 }) // => [1, 2, 4, 8, Infinity]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const exponentialBoundaries = options => boundariesFromIterable(Arr.makeBy(options.count - 1, i => options.start * Math.pow(options.factor, i)));\n// Fiber Runtime Metrics\nconst fibersActive = /*#__PURE__*/gauge(\"child_fibers_active\", {\n description: \"The current count of active child fibers\"\n});\nconst fibersStarted = /*#__PURE__*/counter(\"child_fibers_started\", {\n description: \"The total number of child fibers that have been started\",\n incremental: true\n});\nconst fiberSuccesses = /*#__PURE__*/counter(\"child_fiber_successes\", {\n description: \"The total number of child fibers that have succeeded\",\n incremental: true\n});\nconst fiberFailures = /*#__PURE__*/counter(\"child_fiber_failures\", {\n description: \"The total number of child fibers that have failed\",\n incremental: true\n});\n/**\n * Service key for the fiber runtime metrics service.\n *\n * **Example** (Accessing the fiber runtime metrics key)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * Metric.FiberRuntimeMetricsKey // => \"effect/Metric/FiberRuntimeMetrics\"\n * ```\n *\n * @stability stable\n * @category constants\n * @since 4.0.0\n */\nexport const FiberRuntimeMetricsKey = InternalFiberRuntimeMetricsKey;\n/**\n * Context reference for the optional service that records fiber runtime\n * metrics.\n *\n * **When to use**\n *\n * Use to provide or inspect the service that receives fiber start and end\n * notifications for automatic runtime metrics.\n *\n * **Details**\n *\n * When provided, the runtime can notify the service about child-fiber start and\n * end events. When the reference is `undefined`, automatic fiber runtime metric\n * collection is disabled.\n *\n * **Example** (Accessing the fiber runtime metrics service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const metricsService = yield* Metric.FiberRuntimeMetrics\n * return metricsService === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * const result = await Effect.runPromise(\n * Effect.provideService(program, Metric.FiberRuntimeMetrics, Metric.FiberRuntimeMetricsImpl)\n * )\n * const isDefault = result // => true\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const FiberRuntimeMetrics = /*#__PURE__*/Context.Reference(InternalFiberRuntimeMetricsKey, {\n defaultValue: constUndefined\n});\n/**\n * Default implementation of the fiber runtime metrics service.\n *\n * **Example** (Accessing the default fiber metrics implementation)\n *\n * ```ts import.meta.vitest\n * import { Metric } from \"effect\"\n *\n * [\n * typeof Metric.FiberRuntimeMetricsImpl.recordFiberStart,\n * typeof Metric.FiberRuntimeMetricsImpl.recordFiberEnd\n * ] // => [\"function\", \"function\"]\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const FiberRuntimeMetricsImpl = {\n recordFiberStart(context) {\n fibersStarted.updateUnsafe(1, context);\n fibersActive.modifyUnsafe(1, context);\n },\n recordFiberEnd(context, exit) {\n fibersActive.modifyUnsafe(-1, context);\n if (InternalEffect.exitIsSuccess(exit)) {\n fiberSuccesses.updateUnsafe(1, context);\n } else {\n fiberFailures.updateUnsafe(1, context);\n }\n }\n};\n/**\n * Layer that enables automatic collection of fiber runtime metrics across\n * an entire Effect application.\n *\n * **When to use**\n *\n * Use when you need runtime metrics collection for all Effects in the\n * application context rather than wrapping individual Effects.\n *\n * **Example** (Enabling runtime metrics with a layer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * await Effect.runPromise(Effect.provide(program, Metric.enableRuntimeMetricsLayer)) // => true\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const enableRuntimeMetricsLayer = /*#__PURE__*/Layer.succeed(FiberRuntimeMetrics)(FiberRuntimeMetricsImpl);\n/**\n * Layer that disables automatic collection of fiber runtime metrics.\n *\n * **Example** (Disabling runtime metrics with a layer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * // Disable runtime metrics collection\n * const disabledLayer = Metric.disableRuntimeMetricsLayer\n *\n * return yield* Effect.gen(function*() {\n * // Check that metrics service is disabled\n * const metricsService = yield* Metric.FiberRuntimeMetrics\n *\n * // Run some Effects - no metrics will be collected\n * yield* Effect.forkChild(Effect.sleep(\"50 millis\"))\n * yield* Effect.forkChild(Effect.sleep(\"100 millis\"))\n * yield* Effect.sleep(\"200 millis\")\n *\n * // Create test metrics to show they still work\n * const testCounter = Metric.counter(\"test_counter\")\n * yield* Metric.update(testCounter, 1)\n * const counterValue = yield* Metric.value(testCounter)\n *\n * return { counterValue, metricsEnabled: metricsService !== undefined }\n * }).pipe(Effect.provide(disabledLayer))\n * })\n *\n * const result = await Effect.runPromise(Effect.provideService(program, Metric.MetricRegistry, new Map()))\n * const values = [result.counterValue.count, result.metricsEnabled] // => [1, false]\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const disableRuntimeMetricsLayer = /*#__PURE__*/Layer.succeed(FiberRuntimeMetrics)(undefined);\n/**\n * Enables automatic collection of fiber runtime metrics for the provided Effect.\n *\n * **Details**\n *\n * When enabled, automatically tracks fiber lifecycle metrics including active fibers,\n * started fibers, successful completions, and failures. These metrics provide valuable\n * insights into the concurrency patterns and health of your Effect application.\n *\n * **Example** (Enabling runtime metrics for an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === Metric.FiberRuntimeMetricsImpl\n * })\n *\n * await Effect.runPromise(Metric.enableRuntimeMetrics(program)) // => true\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const enableRuntimeMetrics = /*#__PURE__*/InternalEffect.provideService(FiberRuntimeMetrics, FiberRuntimeMetricsImpl);\n/**\n * Disables automatic collection of fiber runtime metrics for the provided Effect.\n *\n * **When to use**\n *\n * Use when you need to disable runtime metrics for a specific effect while\n * keeping them enabled elsewhere.\n *\n * **Example** (Disabling runtime metrics for an effect)\n *\n * ```ts import.meta.vitest\n * import { Effect, Metric } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const service = yield* Metric.FiberRuntimeMetrics\n * return service === undefined\n * })\n *\n * await Effect.runPromise(Metric.disableRuntimeMetrics(program)) // => true\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const disableRuntimeMetrics = /*#__PURE__*/InternalEffect.provideService(FiberRuntimeMetrics, undefined);\n// Utilities\nfunction makeKey(metric, attributes) {\n // Tuple encoding keeps ids, descriptions and attributes unambiguous.\n const entries = Object.entries(attributes).sort((a, b) => a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0);\n return JSON.stringify([metric.type, metric.id, metric.description, entries]);\n}\nfunction makeHooks(get, update, modify) {\n return {\n get,\n update,\n modify: modify ?? update\n };\n}\nfunction mergeAttributes(self, other) {\n return {\n ...attributesToRecord(self),\n ...attributesToRecord(other)\n };\n}\nfunction attributesToRecord(attributes) {\n if (Predicate.isNotUndefined(attributes) && Array.isArray(attributes)) {\n return attributes.reduce((acc, [key, value]) => {\n InternalRecord.assignProperty(acc, key, value);\n return acc;\n }, {});\n }\n return attributes;\n}\nfunction addAttributesToContext(attributes) {\n // Merge once per contextual attribute set, so the wrapped metric can reuse its cached series key.\n let current;\n let merged = {};\n return context => {\n const extraAttributes = Context.get(context, CurrentMetricAttributes);\n if (extraAttributes !== current) {\n current = extraAttributes;\n merged = mergeAttributes(extraAttributes, attributes);\n }\n return Context.add(context, CurrentMetricAttributes, merged);\n };\n}\n//# sourceMappingURL=Metric.js.map","import * as Cause from \"./Cause.js\";\nimport * as SecureRandom from \"./crypto/SecureRandom.js\";\nimport * as Effect from \"./Effect.js\";\nimport { dual } from \"./Function.js\";\nimport * as random from \"./internal/random.js\";\nimport * as Predicate from \"./Predicate.js\";\n/**\n * Represents a service for generating pseudo-random numbers.\n *\n * **When to use**\n *\n * Use to access or provide the random-number generator service used by Effect\n * programs.\n *\n * **Gotchas**\n *\n * The default implementation is based on `Math.random` and is not\n * cryptographically secure. Replace the service with a cryptographically secure\n * implementation before using these generators for security-sensitive values.\n *\n * **Example** (Accessing the random service)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const float = yield* Random.next\n * const integer = yield* Random.nextInt\n * const inRange = yield* Random.nextIntBetween(1, 100)\n * return [float, integer, inRange] as const\n * })\n *\n * await Effect.runPromise(program.pipe(Random.withSeed(\"example\"))) // => [0.1633802591287037, 3434461687501127, 1]\n * ```\n *\n * @stability stable\n * @category services\n * @since 2.0.0\n */\nexport const Random = random.Random;\nconst randomWith = f => Effect.withFiber(fiber => Effect.succeed(f(fiber.getRef(Random))));\n/**\n * Generates a random number between 0 (inclusive) and 1 (exclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random floating-point number in the standard\n * `[0, 1)` range.\n *\n * **Example** (Generating a random number)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.next.pipe(Random.withSeed(\"example\"))) // => 0.1633802591287037\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const next = /*#__PURE__*/randomWith(r => r.nextDoubleUnsafe());\n/**\n * Generates a random boolean value.\n *\n * **When to use**\n *\n * Use to make a pseudo-random true-or-false choice.\n *\n * **Example** (Generating a random boolean)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextBoolean.pipe(Random.withSeed(\"example\"))) // => false\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextBoolean = /*#__PURE__*/randomWith(r => r.nextDoubleUnsafe() > 0.5);\n/**\n * Generates a random integer between `Number.MIN_SAFE_INTEGER` (inclusive)\n * and `Number.MAX_SAFE_INTEGER` (inclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random safe integer across the full safe-integer\n * range.\n *\n * **Example** (Generating a random integer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextInt.pipe(Random.withSeed(\"example\"))) // => -6064002158214091\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextInt = /*#__PURE__*/randomWith(r => r.nextIntUnsafe());\n/**\n * Generates a random number between `min` (inclusive) and `max` (exclusive).\n *\n * **When to use**\n *\n * Use to generate a pseudo-random floating-point number within a numeric range.\n *\n * **Example** (Generating a bounded random number)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.nextBetween(0, 1).pipe(Random.withSeed(\"example\"))) // => 0.1633802591287037\n * ```\n *\n * @stability stable\n * @category generators\n * @since 4.0.0\n */\nexport const nextBetween = (min, max) => randomWith(r => random.nextBetween(min, max, r.nextDoubleUnsafe()));\n/**\n * Generates a random integer between `min` and `max`.\n *\n * **When to use**\n *\n * Use to generate a pseudo-random integer within a rounded numeric range.\n *\n * **Details**\n *\n * The lower bound is rounded up with `Math.ceil` and the upper bound is\n * rounded down with `Math.floor`. By default the range is inclusive; set\n * `options.halfOpen: true` to exclude the upper bound.\n *\n * **Example** (Generating a bounded random integer)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const diceRoll1 = yield* Random.nextIntBetween(1, 6)\n * const diceRoll2 = yield* Random.nextIntBetween(1, 6, {\n * halfOpen: true\n * })\n * const diceRoll3 = yield* Random.nextIntBetween(0, 10)\n * return [diceRoll1, diceRoll2, diceRoll3]\n * })\n *\n * await Effect.runPromise(program.pipe(Random.withSeed(\"example\"))) // => [1, 4, 0]\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const nextIntBetween = (min, max, options) => {\n const extra = options?.halfOpen === true ? 0 : 1;\n return randomWith(r => {\n const minInt = Math.ceil(min);\n const maxInt = Math.floor(max);\n return Math.floor(r.nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt;\n });\n};\n/**\n * Uses the pseudo-random number generator to shuffle the specified iterable.\n *\n * **When to use**\n *\n * Use to randomly reorder an iterable using the active `Random` service.\n *\n * **Example** (Shuffling values)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.shuffle([1, 2, 3, 4, 5]).pipe(Random.withSeed(\"example\"))) // => [4, 2, 5, 3, 1]\n * ```\n *\n * @stability stable\n * @category generators\n * @since 2.0.0\n */\nexport const shuffle = elements => randomWith(r => {\n const buffer = Array.from(elements);\n for (let i = buffer.length - 1; i >= 1; i = i - 1) {\n const index = Math.min(i, Math.floor(r.nextDoubleUnsafe() * (i + 1)));\n const value = buffer[i];\n buffer[i] = buffer[index];\n buffer[index] = value;\n }\n return buffer;\n});\n/**\n * Gets a random element from an iterable.\n *\n * **When to use**\n *\n * Use to select one value uniformly from a collection using the active `Random`\n * service.\n *\n * **Details**\n *\n * If the input type is known to be non-empty, the returned effect cannot fail.\n * Otherwise, empty iterables fail with `Cause.NoSuchElementError`.\n *\n * **Example** (Choosing a random value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * await Effect.runPromise(Random.choice([\"red\", \"green\", \"blue\"] as const).pipe(Random.withSeed(\"example\"))) // => \"red\"\n * ```\n *\n * @stability stable\n * @category generators\n * @since 3.6.0\n */\nexport const choice = elements => {\n const buffer = Array.from(elements);\n return buffer.length === 0 ? Effect.fail(new Cause.NoSuchElementError(\"Cannot select a random element from an empty array\")) : randomWith(r => buffer[Math.min(buffer.length - 1, Math.floor(r.nextDoubleUnsafe() * buffer.length))]);\n};\n/**\n * Seeds the pseudo-random number generator with the specified value.\n *\n * **When to use**\n *\n * Use to run an effect with a deterministic pseudo-random sequence.\n *\n * **Details**\n *\n * Using the same seed produces the same random sequence, which is useful for\n * tests and reproducible simulations.\n *\n * **Gotchas**\n *\n * Use an unpredictable seed when uniqueness or unpredictability matters.\n *\n * **Example** (Seeding random generation)\n *\n * ```ts import.meta.vitest\n * import { Effect, Random } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const value1 = yield* Random.next\n * const value2 = yield* Random.next\n * return [value1, value2]\n * })\n *\n * await Effect.runPromise(Effect.all([\n * program.pipe(Random.withSeed(\"my-seed\")),\n * program.pipe(Random.withSeed(\"my-seed\"))\n * ])) // => [[0.018368576514773527, 0.4010840628128671], [0.018368576514773527, 0.4010840628128671]]\n * ```\n *\n * @stability stable\n * @category providing services\n * @since 4.0.0\n */\nexport const withSeed = /*#__PURE__*/dual(2, (self, seed) => Effect.suspend(() => Effect.provideService(self, Random, ISAAC_CSPRNG(seed))));\n/*///////////////////////////////////////////////////////////////////////////////////////////////////\nThis is a derivative work copyright (c) 2025 Effectful Technologies Inc, under MIT license.\nThis is a derivative work copyright (c) 2018, William P. \"Mac\" McMeans, under BSD license.\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.\n3. Neither the name of isaacCSPRNG nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\nOriginal work copyright (c) 2012 Yves-Marie K. Rinquin, under MIT license.\nhttps://github.com/rubycon/isaac.js\n///////////////////////////////////////////////////////////////////////////////////////////////////*/\nfunction ISAAC_CSPRNG(userSeed) {\n // Internal State\n const memory = new Array(256);\n const result = new Array(256);\n let accumulator = 0;\n let lastResult = 0;\n let generation = 0;\n let counter = 0;\n // Initial Seed\n const internalSeed = Predicate.isUndefined(userSeed) ? getInitialSeed() : userSeed;\n seed(internalSeed);\n function getInitialSeed() {\n const view = new DataView(SecureRandom.randomBytesUnsafe(8).buffer);\n return view.getUint32(0) + view.getUint32(4);\n }\n function reset() {\n accumulator = 0;\n lastResult = 0;\n counter = 0;\n for (let i = 0; i < 256; ++i) {\n memory[i] = 0;\n result[i] = 0;\n }\n generation = 0;\n }\n function seed(userSeed) {\n // The golden ratio ( 2654435769 )\n // See https://stackoverflow.com/questions/4948780/magic-number-in-boosthash-combine\n const magicNumber = 0x9e3779b9;\n let a = magicNumber;\n let b = magicNumber;\n let c = magicNumber;\n let d = magicNumber;\n let e = magicNumber;\n let f = magicNumber;\n let g = magicNumber;\n let h = magicNumber;\n let i = 0;\n let seed;\n if (Predicate.isString(userSeed)) {\n seed = toIntArray(userSeed);\n } else {\n seed = [userSeed];\n }\n reset();\n for (i = 0; i < seed.length; i++) {\n result[i & 0xff] += seed[i];\n }\n function mix() {\n a ^= b << 11;\n d = add32(d, a);\n b = add32(b, c);\n b ^= c >>> 2;\n e = add32(e, b);\n c = add32(c, d);\n c ^= d << 8;\n f = add32(f, c);\n d = add32(d, e);\n d ^= e >>> 16;\n g = add32(g, d);\n e = add32(e, f);\n e ^= f << 10;\n h = add32(h, e);\n f = add32(f, g);\n f ^= g >>> 4;\n a = add32(a, f);\n g = add32(g, h);\n g ^= h << 8;\n b = add32(b, g);\n h = add32(h, a);\n h ^= a >>> 9;\n c = add32(c, h);\n a = add32(a, b);\n }\n // Scramble the seed\n for (i = 0; i < 4; i++) {\n mix();\n }\n for (i = 0; i < 256; i += 8) {\n // Use all the information in the seed\n a = add32(a, result[i]);\n b = add32(b, result[i + 1]);\n c = add32(c, result[i + 2]);\n d = add32(d, result[i + 3]);\n e = add32(e, result[i + 4]);\n f = add32(f, result[i + 5]);\n g = add32(g, result[i + 6]);\n h = add32(h, result[i + 7]);\n mix();\n // Fill in the memory with messy stuff\n memory[i] = a;\n memory[i + 1] = b;\n memory[i + 2] = c;\n memory[i + 3] = d;\n memory[i + 4] = e;\n memory[i + 5] = f;\n memory[i + 6] = g;\n memory[i + 7] = h;\n }\n // Second pass to make sure seed affects memory\n for (i = 0; i < 256; i += 8) {\n a = add32(a, memory[i]);\n b = add32(b, memory[i + 1]);\n c = add32(c, memory[i + 2]);\n d = add32(d, memory[i + 3]);\n e = add32(e, memory[i + 4]);\n f = add32(f, memory[i + 5]);\n g = add32(g, memory[i + 6]);\n h = add32(h, memory[i + 7]);\n mix();\n // Fill in the memory with messy stuff (again)\n memory[i] = a;\n memory[i + 1] = b;\n memory[i + 2] = c;\n memory[i + 3] = d;\n memory[i + 4] = e;\n memory[i + 5] = f;\n memory[i + 6] = g;\n memory[i + 7] = h;\n }\n pnrg();\n generation = 256;\n }\n function pnrg(n) {\n let i = 0;\n let x = 0;\n let y = 0;\n n = Predicate.isUndefined(n) ? 1 : Math.abs(Math.floor(n));\n while (n--) {\n counter = add32(counter, 1);\n lastResult = add32(lastResult, counter);\n for (i = 0; i < 256; i++) {\n switch (i & 3) {\n case 0:\n {\n accumulator ^= accumulator << 13;\n break;\n }\n case 1:\n {\n accumulator ^= accumulator >>> 6;\n break;\n }\n case 2:\n {\n accumulator ^= accumulator << 2;\n break;\n }\n case 3:\n {\n accumulator ^= accumulator >>> 16;\n break;\n }\n }\n accumulator = add32(memory[i + 128 & 0xff], accumulator);\n x = memory[i];\n memory[i] = add32(memory[x >>> 2 & 0xff], add32(accumulator, lastResult));\n y = memory[i];\n result[i] = add32(memory[y >>> 10 & 0xff], x);\n lastResult = result[i];\n }\n }\n }\n /**\n * Returns a signed, random integer in the range [-2^31, 2^31).\n */\n function nextInt32() {\n if (!generation--) {\n pnrg();\n generation = 255;\n }\n return result[generation];\n }\n function nextIntUnsafe() {\n return Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER;\n }\n /**\n * Returns a 53-bit fraction in the range [0, 1).\n */\n function nextDoubleUnsafe() {\n const hi = nextInt32() >>> 0 & 0x1FFFFF; // take top 21 bits\n const lo = nextInt32() >>> 0; // full 32 bits\n // 53-bit integer\n const combined = hi * 4294967296 + lo;\n return combined / 0x20000000000000; // [0, 1)\n }\n return {\n nextIntUnsafe,\n nextDoubleUnsafe\n };\n}\n/**\n * 32-bit addition with overflow handling (JavaScript numbers are 53-bit).\n *\n * Example: add32(0xFFFFFFFF, 0x00000001) = 0x00000000 (wraps around)\n */\nfunction add32(x, y) {\n // Add lower 16 bits separately to handle carry\n // Example: x=0x12345678, y=0xABCDEF01\n // lsb = (0x5678 + 0xEF01) = 0x14579\n const lsb = (x & 0xffff) + (y & 0xffff);\n // Add upper 16 bits + carry from lower addition\n // msb = (0x1234 + 0xABCD + (0x14579 >>> 16)) = (0x1234 + 0xABCD + 0x1) = 0xBE02\n const msb = (x >>> 16) + (y >>> 16) + (lsb >>> 16);\n // Combine: upper 16 bits | lower 16 bits (masked to prevent double carry)\n // return (0xBE02 << 16) | (0x14579 & 0xffff) = 0xBE024579\n return msb << 16 | lsb & 0xffff;\n}\nconst seedEncoder = /*#__PURE__*/new TextEncoder();\n/**\n * Convert a string to UTF-8 encoded 32-bit integers (little-endian).\n */\nfunction toIntArray(seed) {\n const bytes = seedEncoder.encode(seed);\n const result = [];\n for (let index = 0; index < bytes.length; index += 4) {\n result.push((bytes[index] ?? 0) << 0 | (bytes[index + 1] ?? 0) << 8 | (bytes[index + 2] ?? 0) << 16 | (bytes[index + 3] ?? 0) << 24);\n }\n return result;\n}\n//# sourceMappingURL=Random.js.map","/**\n * Caches values loaded by an Effect lookup function.\n *\n * A cache stores successful and failed lookup results, shares an in-progress\n * lookup when multiple callers request the same missing key, and limits entries\n * by capacity and optional time-to-live rules. This module includes helpers for\n * reading, setting, refreshing, invalidating, and inspecting cache contents.\n *\n * @stability stable\n * @since 4.0.0\n */\nimport * as Context from \"./Context.js\";\nimport * as Duration from \"./Duration.js\";\nimport { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as MutableHashMap from \"./MutableHashMap.js\";\nimport * as Option from \"./Option.js\";\nimport * as Result from \"./Result.js\";\nconst TypeId = \"~effect/Cache\";\n/**\n * Creates a cache with dynamic time-to-live based on the result and key.\n *\n * **When to use**\n *\n * Use when you need different cache entry lifetimes based on the lookup result\n * or key characteristics.\n *\n * **Details**\n *\n * The timeToLive function receives both the exit result and the key, allowing\n * for flexible TTL policies based on success/failure state and key characteristics.\n *\n * **Example** (Configuring dynamic time to live)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Exit } from \"effect\"\n *\n * // Cache with TTL based on computed value\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.makeWith(\n * (id: number) => Effect.succeed({ id, active: id % 2 === 0 }),\n * {\n * capacity: 1000,\n * timeToLive(exit) {\n * if (Exit.isSuccess(exit)) {\n * const user = exit.value\n * return user.active ? \"1 hour\" : \"5 minutes\"\n * }\n * return \"30 seconds\"\n * }\n * }\n * )\n *\n * return cache.capacity\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 1000\n * ```\n *\n * @see {@link make} for a simpler cache constructor with a fixed time-to-live for all entries\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeWith = (lookup, options) => effect.contextWith(context => {\n const self = Object.create(Proto);\n self.lookup = key => effect.updateContext(lookup(key), input => Context.merge(context, input));\n self.map = MutableHashMap.make();\n self.capacity = options.capacity;\n self.timeToLive = options.timeToLive ? (exit, key) => Duration.fromInputUnsafe(options.timeToLive(exit, key)) : defaultTimeToLive;\n return effect.succeed(self);\n});\n/**\n * Creates a cache with a fixed time-to-live for all entries.\n *\n * **Details**\n *\n * This is the basic cache constructor where all entries share the same TTL.\n * The lookup function will be called when a key is not found or has expired.\n *\n * **Example** (Creating a basic cache)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Basic cache with string keys\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make<string, number>({\n * capacity: 100,\n * lookup: (key) => Effect.succeed(key.length)\n * })\n *\n * const result1 = yield* Cache.get(cache, \"hello\")\n * const result2 = yield* Cache.get(cache, \"world\")\n * return { result1, result2 }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { result1: 5, result2: 5 }\n * ```\n *\n * **Example** (Creating a cache with TTL)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const users = new Map([\n * [123, { name: \"Ada\", email: \"ada@example.com\" }],\n * [456, { name: \"Grace\", email: \"grace@example.com\" }]\n * ])\n *\n * const cache = yield* Cache.make<\n * number,\n * { name: string; email: string },\n * string\n * >({\n * capacity: 500,\n * lookup: (userId) =>\n * Effect.suspend(() => {\n * const user = users.get(userId)\n * return user === undefined\n * ? Effect.fail(`User ${userId} not found`)\n * : Effect.succeed(user)\n * }),\n * timeToLive: \"15 minutes\"\n * })\n *\n * const user1 = yield* Cache.get(cache, 123)\n * const user2 = yield* Cache.get(cache, 123)\n * return [user1, user2, user1 === user2] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [{ name: \"Ada\", email: \"ada@example.com\" }, { name: \"Ada\", email: \"ada@example.com\" }, true]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = options => makeWith(options.lookup, {\n ...options,\n timeToLive: options.timeToLive !== undefined ? () => options.timeToLive : defaultTimeToLive\n});\nconst Proto = {\n ...PipeInspectableProto,\n [TypeId]: TypeId,\n toJSON() {\n return {\n _id: \"Cache\",\n capacity: this.capacity,\n map: this.map\n };\n }\n};\nconst defaultTimeToLive = (_, _key) => Duration.infinity;\n/**\n * Retrieves the value for a key, invoking the lookup function on a cache miss\n * or expired entry.\n *\n * **Details**\n *\n * Concurrent `get` calls for the same missing key share the same pending\n * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and\n * will fail again until the entry expires, is invalidated, or is refreshed.\n *\n * **Example** (Getting cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Cache miss - triggers lookup function\n * const result1 = yield* Cache.get(cache, \"hello\")\n *\n * // Cache hit - returns cached value without lookup\n * const result2 = yield* Cache.get(cache, \"hello\")\n *\n * return { result1, result2 }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { result1: 5, result2: 5 }\n * ```\n *\n * **Example** (Handling lookup failures)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Exit } from \"effect\"\n *\n * // Error handling when lookup fails\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make<string, number, string>({\n * capacity: 10,\n * lookup: (key: string) =>\n * key === \"error\"\n * ? Effect.fail(\"Lookup failed\")\n * : Effect.succeed(key.length)\n * })\n *\n * // Successful lookup\n * const success = yield* Cache.get(cache, \"hello\")\n *\n * // Failed lookup - returns error\n * const failure = yield* Effect.exit(Cache.get(cache, \"error\"))\n * return [success, failure] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [5, Exit.fail(\"Lookup failed\")]\n * ```\n *\n * **Example** (Sharing concurrent lookups)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Concurrent access - multiple gets of same key only invoke lookup once\n * const program = Effect.gen(function*() {\n * let lookupCount = 0\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) =>\n * Effect.sync(() => {\n * lookupCount++\n * return key.length\n * })\n * })\n *\n * // Multiple concurrent gets\n * const results = yield* Effect.all([\n * Cache.get(cache, \"hello\"),\n * Cache.get(cache, \"hello\"),\n * Cache.get(cache, \"hello\")\n * ], { concurrency: \"unbounded\" })\n *\n * return { results, lookupCount }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { results: [5, 5, 5], lookupCount: 1 }\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const oentry = MutableHashMap.get(self.map, key);\n if (Option.isSome(oentry)) {\n MutableHashMap.remove(self.map, key);\n if (!hasExpired(oentry.value, fiber)) {\n // Move the entry to the end of the map to keep it fresh\n MutableHashMap.set(self.map, key, oentry.value);\n return oentry.value.await(fiber);\n }\n }\n const clock = fiber.getRef(effect.ClockRef);\n const entry = new EntryImpl(fiber, self.lookup(key));\n entry.onInterrupt = () => removeEntry(self, key, entry);\n let skipCache = false;\n entry.fiber.addObserver(exit => {\n // Release the key once the lookup can no longer be interrupted.\n entry.onInterrupt = undefined;\n if (effect.exitHasInterrupts(exit)) {\n removeEntry(self, key, entry);\n return;\n }\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n skipCache = true;\n removeEntry(self, key, entry);\n } else if (Duration.isFinite(ttl)) {\n entry.expiresAt = clock.currentTimeMillisUnsafe() + Duration.toMillis(ttl);\n }\n });\n const exit = entry.fiber.pollUnsafe();\n if (!skipCache && (exit === undefined || !effect.exitHasInterrupts(exit))) {\n MutableHashMap.set(self.map, key, entry);\n }\n if (Number.isFinite(self.capacity)) {\n checkCapacity(self);\n }\n return entry.await(fiber);\n}));\nclass EntryImpl {\n expiresAt;\n awaiters;\n fiber;\n onInterrupt;\n constructor(parent, valueEffect) {\n this.fiber = effect.forkUnsafe(parent, valueEffect, true, true);\n this.awaiters = 0;\n this.expiresAt = undefined;\n }\n await(fiber) {\n if (fiber === undefined) return core.withFiber(fiber => this.await(fiber));\n const exit = this.fiber.pollUnsafe();\n if (exit) return exit;\n this.awaiters++;\n // Register cleanup in the same evaluation as the increment, before interruption\n // can prevent the returned join effect from starting.\n effect.onExitUnsafe(fiber, () => {\n this.awaiters--;\n if (this.awaiters > 0 || this.fiber.pollUnsafe()) return effect.void;\n // Detach before interrupting so new lookups do not join the abandoned fiber\n // while its finalizers run.\n this.onInterrupt?.();\n return effect.fiberInterrupt(this.fiber);\n });\n return effect.fiberJoin(this.fiber);\n }\n}\nconst removeEntry = (self, key, entry) => {\n const current = MutableHashMap.get(self.map, key);\n if (Option.isSome(current) && current.value === entry) {\n MutableHashMap.remove(self.map, key);\n }\n};\nconst hasExpired = (entry, fiber) => {\n if (entry.expiresAt === undefined) {\n return false;\n }\n return fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() >= entry.expiresAt;\n};\nconst checkCapacity = self => {\n let diff = MutableHashMap.size(self.map) - self.capacity;\n if (diff <= 0) return;\n // MutableHashMap has insertion order, so we can remove the oldest entries\n for (const [key] of self.map) {\n MutableHashMap.remove(self.map, key);\n diff--;\n if (diff === 0) return;\n }\n};\n/**\n * Reads an existing cache entry without invoking the lookup function.\n *\n * **Details**\n *\n * Returns `Option.none()` when the key is missing or expired, and `Option.some`\n * when a cached lookup has succeeded. If the entry is still pending, waits for\n * it to complete. If the cached or pending lookup fails, this effect fails with\n * the same error.\n *\n * **Example** (Reading cached values without lookup)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Option } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // No value in cache yet - returns None without lookup\n * const empty = yield* Cache.getOption(cache, \"hello\")\n *\n * // Populate cache using get\n * yield* Cache.get(cache, \"hello\")\n *\n * // Now getOption returns the cached value\n * const cached = yield* Cache.getOption(cache, \"hello\")\n * return [empty, cached] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Option.none(), Option.some(5)]\n * ```\n *\n * **Example** (Skipping expired entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect, Option } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // Expired entries return None\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Add value to cache\n * yield* Cache.get(cache, \"hello\")\n *\n * // Value exists before expiration\n * const beforeExpiry = yield* Cache.getOption(cache, \"hello\")\n *\n * // Simulate time passing\n * yield* TestClock.adjust(\"2 hours\")\n *\n * // Value expired - returns None\n * const afterExpiry = yield* Cache.getOption(cache, \"hello\")\n * return [beforeExpiry, afterExpiry] as const\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [Option.some(5), Option.none()]\n * ```\n *\n * **Example** (Waiting for pending lookups)\n *\n * ```ts import.meta.vitest\n * import { Cache, Deferred, Effect, Fiber, Option } from \"effect\"\n *\n * // Waits for ongoing computation to complete\n * const program = Effect.gen(function*() {\n * const deferred = yield* Deferred.make<void>()\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (_key: string) => Deferred.await(deferred).pipe(Effect.as(42))\n * })\n *\n * // Start lookup in background\n * const getFiber = yield* Effect.forkChild(Cache.get(cache, \"key\"))\n *\n * // getOption waits for ongoing computation\n * const optionFiber = yield* Effect.forkChild(Cache.getOption(cache, \"key\"))\n *\n * // Complete the computation\n * yield* Deferred.succeed(deferred, void 0)\n *\n * const result = yield* Fiber.join(optionFiber)\n * const value = yield* Fiber.join(getFiber)\n * return [result, value] as const\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [Option.some(42), 42]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const getOption = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const entry = getImpl(self, key, fiber);\n return entry ? effect.asSome(entry.await(fiber)) : effect.succeedNone;\n}));\nconst getImpl = (self, key, fiber, isRead = true) => {\n const oentry = MutableHashMap.get(self.map, key);\n if (Option.isNone(oentry)) {\n return undefined;\n } else if (hasExpired(oentry.value, fiber)) {\n MutableHashMap.remove(self.map, key);\n return undefined;\n } else if (isRead) {\n MutableHashMap.remove(self.map, key);\n MutableHashMap.set(self.map, key, oentry.value);\n }\n return oentry.value;\n};\n/**\n * Retrieves the value associated with the specified key from the cache, only if\n * it contains a resolved successful value.\n *\n * **Details**\n *\n * This checks only an existing non-expired entry. It returns `Option.some` when\n * the entry has already resolved successfully, and `Option.none` for missing,\n * expired, failed, or still-pending entries.\n *\n * @see {@link get} for triggering or awaiting the cache lookup\n * @see {@link getOption} for reading an existing entry as an optional effect\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const getSuccess = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const exit = getImpl(self, key, fiber)?.fiber.pollUnsafe();\n if (exit && effect.exitIsSuccess(exit)) {\n return effect.succeedSome(exit.value);\n }\n return effect.succeedNone;\n}));\n/**\n * Sets the value associated with the specified key in the cache. This will\n * overwrite any existing value for that key, skipping the lookup function.\n *\n * **Example** (Setting values directly)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Set a value directly without invoking lookup\n * yield* Cache.set(cache, \"hello\", 42)\n * return yield* Cache.get(cache, \"hello\")\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 42\n * ```\n *\n * **Example** (Overwriting cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Overwriting existing cached values\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // First get populates via lookup\n * const original = yield* Cache.get(cache, \"test\") // 4\n *\n * // Set overwrites the cached value\n * yield* Cache.set(cache, \"test\", 999)\n * const updated = yield* Cache.get(cache, \"test\") // 999\n *\n * return { original, updated }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { original: 4, updated: 999 }\n * ```\n *\n * **Example** (Applying TTL to set values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // TTL behavior with set operations\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Set value with TTL applied\n * yield* Cache.set(cache, \"temporary\", 123)\n * const beforeExpiry = yield* Cache.has(cache, \"temporary\")\n *\n * // Advance time past TTL\n * yield* TestClock.adjust(\"2 hours\")\n * const afterExpiry = yield* Cache.has(cache, \"temporary\")\n * return [beforeExpiry, afterExpiry]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, false]\n * ```\n *\n * **Example** (Enforcing capacity when setting values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Capacity enforcement with set operations\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 2,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Fill cache to capacity\n * yield* Cache.set(cache, \"a\", 1)\n * yield* Cache.set(cache, \"b\", 2)\n * const sizeBeforeEviction = yield* Cache.size(cache)\n *\n * // Adding another entry evicts oldest\n * yield* Cache.set(cache, \"c\", 3)\n * const sizeAfterEviction = yield* Cache.size(cache)\n * const hasOldest = yield* Cache.has(cache, \"a\")\n * const hasNewest = yield* Cache.has(cache, \"c\")\n * return [sizeBeforeEviction, sizeAfterEviction, hasOldest, hasNewest]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [2, 2, false, true]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const set = /*#__PURE__*/dual(3, (self, key, value) => core.withFiber(fiber => {\n const exit = core.exitSucceed(value);\n const entry = new EntryImpl(fiber, exit);\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n MutableHashMap.remove(self.map, key);\n return effect.void;\n }\n entry.expiresAt = Duration.isFinite(ttl) ? fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe() + Duration.toMillis(ttl) : undefined;\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n return effect.void;\n}));\n/**\n * Checks whether the cache contains an entry for the specified key.\n *\n * **Details**\n *\n * This checks for an existing non-expired entry without invoking the cache\n * lookup function. Expired entries are treated as absent.\n *\n * **Example** (Checking for cached keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Check non-existent key\n * const missing = yield* Cache.has(cache, \"missing\")\n *\n * // Add entry and check existence\n * yield* Cache.get(cache, \"hello\")\n * const present = yield* Cache.has(cache, \"hello\")\n * return [missing, present]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [false, true]\n * ```\n *\n * **Example** (Checking TTL expiration)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // TTL expiration behavior\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * // Add entry with TTL\n * yield* Cache.get(cache, \"expires\")\n * const initial = yield* Cache.has(cache, \"expires\")\n *\n * // Still valid before expiration\n * yield* TestClock.adjust(\"30 minutes\")\n * const beforeExpiry = yield* Cache.has(cache, \"expires\")\n *\n * // Expired after TTL\n * yield* TestClock.adjust(\"31 minutes\")\n * const afterExpiry = yield* Cache.has(cache, \"expires\")\n * return [initial, beforeExpiry, afterExpiry]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, true, false]\n * ```\n *\n * **Example** (Checking multiple keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Checking multiple keys efficiently\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 100,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Populate some entries\n * yield* Cache.set(cache, \"apple\", 5)\n * yield* Cache.set(cache, \"banana\", 6)\n *\n * // Check multiple keys\n * const keys = [\"apple\", \"banana\", \"cherry\", \"date\"]\n * const results: Array<string> = []\n * for (const key of keys) {\n * const exists = yield* Cache.has(cache, key)\n * results.push(`${key}: ${exists}`)\n * }\n * return results\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"apple: true\", \"banana: true\", \"cherry: false\", \"date: false\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const has = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const oentry = getImpl(self, key, fiber, false);\n return effect.succeed(oentry !== undefined);\n}));\n/**\n * Invalidates the entry associated with the specified key in the cache.\n *\n * **Example** (Invalidating cached entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add a value to the cache\n * yield* Cache.get(cache, \"hello\")\n * const beforeInvalidation = yield* Cache.has(cache, \"hello\")\n *\n * // Invalidate the entry\n * yield* Cache.invalidate(cache, \"hello\")\n * const afterInvalidation = yield* Cache.has(cache, \"hello\")\n *\n * // Invalidating non-existent keys doesn't error\n * yield* Cache.invalidate(cache, \"nonexistent\")\n *\n * // Get after invalidation will invoke lookup again\n * let lookupCount = 0\n * const cache2 = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) =>\n * Effect.sync(() => {\n * lookupCount++\n * return key.length\n * })\n * })\n *\n * yield* Cache.get(cache2, \"test\") // lookupCount = 1\n * yield* Cache.invalidate(cache2, \"test\")\n * yield* Cache.get(cache2, \"test\") // lookupCount = 2 (lookup called again)\n * return { beforeInvalidation, afterInvalidation, lookupCount }\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => { beforeInvalidation: true, afterInvalidation: false, lookupCount: 2 }\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidate = /*#__PURE__*/dual(2, (self, key) => effect.sync(() => {\n MutableHashMap.remove(self.map, key);\n}));\n/**\n * Invalidates the entry associated with the specified key in the cache when the\n * predicate returns true for the cached value.\n *\n * **Example** (Invalidating entries conditionally)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add values to the cache\n * yield* Cache.get(cache, \"hello\") // value = 5\n * yield* Cache.get(cache, \"hi\") // value = 2\n *\n * // Invalidate when value equals 5\n * const invalidated1 = yield* Cache.invalidateWhen(\n * cache,\n * \"hello\",\n * (value) => value === 5\n * )\n * const hasHello = yield* Cache.has(cache, \"hello\")\n *\n * // Don't invalidate when predicate doesn't match\n * const invalidated2 = yield* Cache.invalidateWhen(\n * cache,\n * \"hi\",\n * (value) => value === 5\n * )\n * const hasHi = yield* Cache.has(cache, \"hi\")\n *\n * // Returns false for non-existent keys\n * const invalidated3 = yield* Cache.invalidateWhen(\n * cache,\n * \"nonexistent\",\n * () => true\n * )\n *\n * // Returns false for failed cached values\n * const cacheWithErrors = yield* Cache.make<string, number, string>({\n * capacity: 10,\n * lookup: (key: string) =>\n * key === \"fail\" ? Effect.fail(\"error\") : Effect.succeed(key.length)\n * })\n *\n * yield* Effect.exit(Cache.get(cacheWithErrors, \"fail\"))\n * const invalidated4 = yield* Cache.invalidateWhen(\n * cacheWithErrors,\n * \"fail\",\n * () => true\n * )\n * return [invalidated1, hasHello, invalidated2, hasHi, invalidated3, invalidated4]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [true, false, false, true, false, false]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidateWhen = /*#__PURE__*/dual(3, (self, key, f) => core.withFiber(fiber => {\n const oentry = getImpl(self, key, fiber, false);\n if (oentry === undefined) {\n return effect.succeed(false);\n }\n return oentry.await(fiber).pipe(effect.map(value => {\n if (f(value)) {\n const current = MutableHashMap.get(self.map, key);\n if (Option.isNone(current) || current.value !== oentry) {\n return false;\n }\n MutableHashMap.remove(self.map, key);\n return true;\n }\n return false;\n }), effect.catchCause(() => effect.succeed(false)));\n}));\n/**\n * Forces a refresh of the value associated with the specified key in the cache.\n *\n * **Details**\n *\n * It will always invoke the lookup function to construct a new value,\n * overwriting any existing value for that key.\n *\n * **Example** (Refreshing cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Force refresh of existing cached values\n * const program = Effect.gen(function*() {\n * let counter = 0\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.sync(() => `${key}-${++counter}`)\n * })\n *\n * // Initial cache population\n * const value1 = yield* Cache.get(cache, \"user\")\n *\n * // Get from cache (no lookup)\n * const value2 = yield* Cache.get(cache, \"user\")\n *\n * // Force refresh - always calls lookup\n * const refreshed = yield* Cache.refresh(cache, \"user\")\n *\n * // Subsequent gets return refreshed value\n * const value3 = yield* Cache.get(cache, \"user\")\n * return [value1, value2, refreshed, value3, counter]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"user-1\", \"user-1\", \"user-2\", \"user-2\", 2]\n * ```\n *\n * **Example** (Resetting TTL on refresh)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n * import { TestClock } from \"effect/testing\"\n *\n * // Refresh resets TTL (Time To Live)\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length),\n * timeToLive: \"1 hour\"\n * })\n *\n * yield* Cache.get(cache, \"test\")\n * yield* TestClock.adjust(\"45 minutes\")\n *\n * // Entry would normally expire in 15 minutes\n * const beforeRefresh = yield* Cache.has(cache, \"test\")\n *\n * // Refresh resets the TTL to full 1 hour\n * yield* Cache.refresh(cache, \"test\")\n * yield* TestClock.adjust(\"30 minutes\")\n *\n * // Still valid because TTL was reset\n * const afterRefresh = yield* Cache.has(cache, \"test\")\n * return [beforeRefresh, afterRefresh]\n * })\n *\n * const actual = await Effect.runPromise(Effect.provide(program, TestClock.layer()))\n * actual // => [true, true]\n * ```\n *\n * **Example** (Refreshing missing keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Refresh non-existent keys\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(`value-for-${key}`)\n * })\n *\n * // Refresh non-existent key creates new entry\n * const result = yield* Cache.refresh(cache, \"newKey\")\n *\n * // Verify it's now cached\n * const cached = yield* Cache.has(cache, \"newKey\")\n * return [result, cached]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"value-for-newKey\", true]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const refresh = /*#__PURE__*/dual(2, (self, key) => core.withFiber(fiber => {\n const clock = fiber.getRef(effect.ClockRef);\n const entry = new EntryImpl(fiber, self.lookup(key));\n entry.onInterrupt = () => removeEntry(self, key, entry);\n const existing = getImpl(self, key, fiber, false) !== undefined;\n if (!existing) {\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n }\n entry.fiber.addObserver(exit => {\n // Release the key once the lookup can no longer be interrupted.\n entry.onInterrupt = undefined;\n if (effect.exitHasInterrupts(exit)) {\n removeEntry(self, key, entry);\n return;\n }\n const ttl = self.timeToLive(exit, key);\n if (Duration.isZero(ttl)) {\n if (existing) MutableHashMap.remove(self.map, key);else removeEntry(self, key, entry);\n return effect.void;\n }\n entry.expiresAt = Duration.isFinite(ttl) ? clock.currentTimeMillisUnsafe() + Duration.toMillis(ttl) : undefined;\n if (existing) {\n MutableHashMap.set(self.map, key, entry);\n checkCapacity(self);\n }\n });\n return entry.await(fiber);\n}));\n/**\n * Invalidates all entries in the cache.\n *\n * **Example** (Invalidating all entries)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Clear all cached entries at once\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Populate cache with multiple entries\n * yield* Cache.get(cache, \"apple\")\n * yield* Cache.get(cache, \"banana\")\n * yield* Cache.get(cache, \"cherry\")\n *\n * const sizeBeforeInvalidation = yield* Cache.size(cache)\n * const hasAppleBeforeInvalidation = yield* Cache.has(cache, \"apple\")\n *\n * // Clear all entries\n * yield* Cache.invalidateAll(cache)\n *\n * // Verify cache is empty\n * const sizeAfterInvalidation = yield* Cache.size(cache)\n * const hasAppleAfterInvalidation = yield* Cache.has(cache, \"apple\")\n * const hasBananaAfterInvalidation = yield* Cache.has(cache, \"banana\")\n * const hasCherryAfterInvalidation = yield* Cache.has(cache, \"cherry\")\n * return [\n * sizeBeforeInvalidation,\n * hasAppleBeforeInvalidation,\n * sizeAfterInvalidation,\n * hasAppleAfterInvalidation,\n * hasBananaAfterInvalidation,\n * hasCherryAfterInvalidation\n * ]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [3, true, 0, false, false, false]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const invalidateAll = self => effect.sync(() => {\n MutableHashMap.clear(self.map);\n});\n/**\n * Retrieves the approximate number of entries in the cache.\n *\n * **Details**\n *\n * Note that expired entries are counted until they are accessed and removed.\n * The size reflects the current number of entries stored, not the number\n * of valid entries.\n *\n * **Example** (Reading cache size)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Empty cache has size 0\n * const emptySize = yield* Cache.size(cache)\n *\n * // Add entries and check size\n * yield* Cache.get(cache, \"hello\")\n * yield* Cache.get(cache, \"world\")\n * const sizeAfterAdding = yield* Cache.size(cache)\n *\n * // Size decreases after invalidation\n * yield* Cache.invalidate(cache, \"hello\")\n * const sizeAfterInvalidation = yield* Cache.size(cache)\n * return [emptySize, sizeAfterAdding, sizeAfterInvalidation]\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [0, 2, 1]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const size = self => effect.sync(() => MutableHashMap.size(self.map));\n/**\n * Retrieves all active keys from the cache, automatically filtering out expired entries.\n *\n * **Example** (Reading active keys)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * // Basic key enumeration\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add some entries to the cache\n * yield* Cache.get(cache, \"hello\")\n * yield* Cache.get(cache, \"world\")\n * yield* Cache.get(cache, \"cache\")\n *\n * // Retrieve all active keys\n * const keys = yield* Cache.keys(cache)\n * return Array.from(keys).sort()\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [\"cache\", \"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const keys = self => core.withFiber(fiber => {\n const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe();\n return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {\n if (entry.expiresAt === undefined || entry.expiresAt > now) {\n return Result.succeed(key);\n }\n MutableHashMap.remove(self.map, key);\n return Result.failVoid;\n }));\n});\n/**\n * Retrieves all successfully cached values from the cache, excluding failed\n * lookups and expired entries.\n *\n * **Example** (Reading all cached values)\n *\n * ```ts import.meta.vitest\n * import { Cache, Effect } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const cache = yield* Cache.make({\n * capacity: 10,\n * lookup: (key: string) => Effect.succeed(key.length)\n * })\n *\n * // Add some values to the cache\n * yield* Cache.get(cache, \"a\")\n * yield* Cache.get(cache, \"ab\")\n * yield* Cache.get(cache, \"abc\")\n *\n * // Retrieve all cached values\n * const values = yield* Cache.values(cache)\n * return Array.from(values).sort()\n * })\n *\n * const actual = await Effect.runPromise(program)\n * actual // => [1, 2, 3]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const values = self => effect.map(entries(self), Iterable.map(([, value]) => value));\n/**\n * Retrieves all key-value pairs from the cache as an iterable. This function\n * only returns entries with successfully resolved values, filtering out any\n * failed lookups or expired entries.\n *\n * **Gotchas**\n *\n * Expired entries are removed from the cache while `entries` filters them out.\n *\n * @see {@link keys} for retrieving only cached keys\n * @see {@link values} for retrieving only cached values\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const entries = self => core.withFiber(fiber => {\n const now = fiber.getRef(effect.ClockRef).currentTimeMillisUnsafe();\n return effect.succeed(Iterable.filterMap(self.map, ([key, entry]) => {\n if (entry.expiresAt === undefined || entry.expiresAt > now) {\n const exit = entry.fiber.pollUnsafe();\n return exit && exit._tag === \"Success\" ? Result.succeed([key, exit.value]) : Result.failVoid;\n }\n MutableHashMap.remove(self.map, key);\n return Result.failVoid;\n }));\n});\n//# sourceMappingURL=Cache.js.map","import { dual } from \"./Function.js\";\nimport * as core from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\n/**\n * Context reference for the current console service in the Effect system, allowing access to the active console implementation from within the Effect context.\n *\n * **When to use**\n *\n * Use when you need an effect to run against a provided console implementation,\n * such as tests or alternate runtimes, rather than the default console.\n *\n * **Details**\n *\n * When no override is provided, the reference resolves to `globalThis.console`.\n *\n * **Example** (Accessing the current console)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n * Effect.sync(() => {\n * console.log(\"Hello from current console!\")\n * })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello from current console!\"]\n * ```\n *\n * @see {@link consoleWith} for using the current console service inside an effect\n *\n * @stability stable\n * @category services\n * @since 2.0.0\n */\nexport const Console = effect.ConsoleRef;\n/**\n * Creates an Effect that provides access to the current console service and lets you perform operations with it within an Effect context.\n *\n * **Example** (Accessing the current console service)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(...args),\n * error: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Console.consoleWith((console) =>\n * Effect.sync(() => {\n * console.log(\"Hello, world!\")\n * console.error(\"This is an error message\")\n * })\n * )\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"Hello, world!\", \"This is an error message\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const consoleWith = f => core.withFiber(fiber => f(fiber.getRef(Console)));\n/**\n * Writes the supplied assertion message to the console as an error when `condition` is false; when `condition` is true, no console output is produced.\n *\n * **Example** (Logging failed assertions)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const errors: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * assert: (condition: boolean, ...args: ReadonlyArray<unknown>) => {\n * if (!condition) errors.push(...args)\n * }\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.assert(2 + 2 === 4, \"Math is working correctly\")\n * yield* Console.assert(2 + 2 === 5, \"This will be logged as an error\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * errors // => [\"This will be logged as an error\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const assert = (condition, ...args) => consoleWith(console => effect.sync(() => {\n console.assert(condition, ...args);\n}));\n/**\n * Runs the current console service's clear operation.\n *\n * **When to use**\n *\n * Use to request that the active console implementation clear its visible\n * output.\n *\n * **Gotchas**\n *\n * The clearing behavior depends on the active console implementation and host\n * environment.\n *\n * **Example** (Clearing console output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (message: string) => operations.push(`log:${message}`),\n * clear: () => operations.push(\"clear\")\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.log(\"This will be cleared\")\n * yield* Console.clear\n * yield* Console.log(\"This appears after clearing\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"log:This will be cleared\", \"clear\", \"log:This appears after clearing\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const clear = /*#__PURE__*/consoleWith(console => effect.sync(() => {\n console.clear();\n}));\n/**\n * Logs and increments the counter associated with `label`, using the console's default counter when no label is provided.\n *\n * **Example** (Counting repeated calls)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * count: (label = \"default\") => {\n * const count = (counters.get(label) ?? 0) + 1\n * counters.set(label, count)\n * messages.push(`${label}: ${count}`)\n * }\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.count(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * yield* Console.count()\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"default: 1\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const count = label => consoleWith(console => effect.sync(() => {\n console.count(label);\n}));\n/**\n * Resets the counter associated with the specified label back to zero.\n *\n * **Example** (Resetting a counter)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const counters = new Map<string, number>()\n * const messages: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * count: (label = \"default\") => {\n * const count = (counters.get(label) ?? 0) + 1\n * counters.set(label, count)\n * messages.push(`${label}: ${count}`)\n * },\n * countReset: (label = \"default\") => counters.set(label, 0)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.count(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * yield* Console.countReset(\"my-counter\")\n * yield* Console.count(\"my-counter\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"my-counter: 1\", \"my-counter: 2\", \"my-counter: 1\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const countReset = label => consoleWith(console => effect.sync(() => {\n console.countReset(label);\n}));\n/**\n * Writes a debug message through the current `Console` service.\n *\n * **Details**\n *\n * The arguments are passed to the service's `debug` method when the returned\n * Effect is executed. Any filtering behavior depends on the active console\n * implementation.\n *\n * **Example** (Writing debug messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * debug: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.debug(\"Debug info:\", { userId: 123, action: \"login\" })\n * yield* Console.debug(\"Processing step\", 1, \"of\", 5)\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [[\"Debug info:\", { userId: 123, action: \"login\" }], [\"Processing step\", 1, \"of\", 5]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const debug = (...args) => consoleWith(console => effect.sync(() => {\n console.debug(...args);\n}));\n/**\n * Displays an interactive list of the properties of the specified object, optionally using console-specific inspection options for debugging complex data structures.\n *\n * **Example** (Inspecting an object)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const inspected: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * dir: (item: unknown, options?: unknown) => inspected.push([item, options])\n * })\n * const program = Effect.gen(function*() {\n * const obj = { name: \"John\", age: 30, nested: { city: \"New York\" } }\n * yield* Console.dir(obj)\n * yield* Console.dir(obj, { depth: 2 })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, undefined],\n * [{ name: \"John\", age: 30, nested: { city: \"New York\" } }, { depth: 2 }]\n * ]\n * inspected // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const dir = (item, options) => consoleWith(console => effect.sync(() => {\n console.dir(item, options);\n}));\n/**\n * Displays an interactive tree of descendant XML or HTML elements, which is particularly useful for inspecting DOM elements in browser environments.\n *\n * **Example** (Inspecting XML-like data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * dirxml: (...args: ReadonlyArray<unknown>) => messages.push(...args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.dirxml(\"<user id=\\\"1\\\">Ada</user>\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * messages // => [\"<user id=\\\"1\\\">Ada</user>\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const dirxml = (...args) => consoleWith(console => effect.sync(() => {\n console.dirxml(...args);\n}));\n/**\n * Writes an error-level message to the console, typically displayed with error\n * styling by the active console implementation.\n *\n * **Example** (Writing error messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * error: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.error(\"Something went wrong!\")\n * yield* Console.error(\"Error details:\", {\n * code: 500,\n * message: \"Internal Server Error\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Something went wrong!\"],\n * [\"Error details:\", { code: 500, message: \"Internal Server Error\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const error = (...args) => consoleWith(console => effect.sync(() => {\n console.error(...args);\n}));\n/**\n * Creates a scoped console group, optionally collapsed and labeled, and closes it automatically when the Effect scope is finalized.\n *\n * **Example** (Grouping scoped output)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * group: (label?: string) => operations.push(`group:${label}`),\n * groupEnd: () => operations.push(\"groupEnd\"),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.group({ label: \"User Processing\" })\n * yield* Console.log(\"Loading user data...\")\n * yield* Console.log(\"Validating user...\")\n * yield* Console.log(\"User processed successfully\")\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * \"group:User Processing\",\n * \"log:Loading user data...\",\n * \"log:Validating user...\",\n * \"log:User processed successfully\",\n * \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const group = options => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n if (options?.collapsed) {\n console.groupCollapsed(options.label);\n } else {\n console.group(options?.label);\n }\n}), () => effect.sync(() => {\n console.groupEnd();\n})));\n/**\n * Writes an informational message to the console, typically displayed with info\n * styling by the active console implementation.\n *\n * **Example** (Writing informational messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * info: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.info(\"Application started successfully\")\n * yield* Console.info(\"Server configuration:\", {\n * port: 3000,\n * env: \"development\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Application started successfully\"],\n * [\"Server configuration:\", { port: 3000, env: \"development\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const info = (...args) => consoleWith(console => effect.sync(() => {\n console.info(...args);\n}));\n/**\n * Logs a general-purpose message to the console.\n *\n * **Example** (Writing log messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * log: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.log(\"Hello, world!\")\n * yield* Console.log(\"User data:\", { name: \"John\", age: 30 })\n * yield* Console.log(\"Processing\", 42, \"items\")\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"Hello, world!\"],\n * [\"User data:\", { name: \"John\", age: 30 }],\n * [\"Processing\", 42, \"items\"]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const log = (...args) => consoleWith(console => effect.sync(() => {\n console.log(...args);\n}));\n/**\n * Displays tabular data as a formatted table in the console, optionally limited to selected properties.\n *\n * **Example** (Displaying tabular data)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const calls: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * table: (data: ReadonlyArray<unknown>, properties?: ReadonlyArray<string>) => {\n * calls.push({ rows: data.length, properties })\n * }\n * })\n *\n * const program = Effect.gen(function*() {\n * const users = [\n * { name: \"John\", age: 30, city: \"New York\" },\n * { name: \"Jane\", age: 25, city: \"London\" },\n * { name: \"Bob\", age: 35, city: \"Paris\" }\n * ]\n * yield* Console.table(users)\n * yield* Console.table(users, [\"name\", \"age\"]) // Only show specific columns\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * calls // => [{ rows: 3, properties: undefined }, { rows: 3, properties: [\"name\", \"age\"] }]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const table = (tabularData, properties) => consoleWith(console => effect.sync(() => {\n console.table(tabularData, properties);\n}));\n/**\n * Starts a scoped timer for `label` and automatically ends it when the Effect scope is finalized.\n *\n * **Example** (Timing scoped work)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push(`start:${label}`),\n * timeEnd: (label?: string) => operations.push(`end:${label}`),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.time(\"operation-timer\")\n * yield* Console.log(\"Operation completed\")\n * // Timer ends automatically when scope closes\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:operation-timer\", \"log:Operation completed\", \"end:operation-timer\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const time = label => consoleWith(console => effect.acquireRelease(effect.sync(() => {\n console.time(label);\n}), () => effect.sync(() => {\n console.timeEnd(label);\n})));\n/**\n * Logs the elapsed time for an existing timer without stopping it, allowing progress reports for long-running operations.\n *\n * **Example** (Logging timer progress)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<unknown> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push([\"start\", label]),\n * timeLog: (label?: string, ...args: ReadonlyArray<unknown>) => operations.push([\"log\", label, ...args]),\n * timeEnd: (label?: string) => operations.push([\"end\", label])\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.scoped(\n * Effect.gen(function*() {\n * yield* Console.time(\"long-operation\")\n * yield* Console.timeLog(\"long-operation\", \"Halfway done\")\n * // Timer ends when scope closes\n * })\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [[\"start\", \"long-operation\"], [\"log\", \"long-operation\", \"Halfway done\"], [\"end\", \"long-operation\"]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const timeLog = (label, ...args) => consoleWith(console => effect.sync(() => {\n console.timeLog(label, ...args);\n}));\n/**\n * Writes the current stack trace to the console to show how the current point in\n * the code was reached.\n *\n * **Example** (Writing stack traces)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const traces: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * trace: (...args: ReadonlyArray<unknown>) => traces.push(args)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Console.trace(\"Debug trace point\")\n * yield* Console.trace(\"Function call:\", { functionName: \"processData\" })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * traces // => [[\"Debug trace point\"], [\"Function call:\", { functionName: \"processData\" }]]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const trace = (...args) => consoleWith(console => effect.sync(() => {\n console.trace(...args);\n}));\n/**\n * Writes a warning-level message to the console, typically displayed with\n * warning styling by the active console implementation.\n *\n * **Example** (Writing warning messages)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * warn: (...args: ReadonlyArray<unknown>) => messages.push(args)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.warn(\"This feature is deprecated\")\n * yield* Console.warn(\"Performance warning:\", {\n * slowQuery: \"SELECT * FROM large_table\"\n * })\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"This feature is deprecated\"],\n * [\"Performance warning:\", { slowQuery: \"SELECT * FROM large_table\" }]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const warn = (...args) => consoleWith(console => effect.sync(() => {\n console.warn(...args);\n}));\n/**\n * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes.\n *\n * **Example** (Wrapping an effect in a group)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * group: (label?: string) => operations.push(`group:${label}`),\n * groupEnd: () => operations.push(\"groupEnd\"),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n * const program = Effect.gen(function*() {\n * yield* Console.withGroup(\n * Effect.gen(function*() {\n * yield* Console.log(\"Step 1: Initialize\")\n * yield* Console.log(\"Step 2: Process\")\n * yield* Console.log(\"Step 3: Complete\")\n * }),\n * { label: \"Processing Steps\", collapsed: false }\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * \"group:Processing Steps\",\n * \"log:Step 1: Initialize\",\n * \"log:Step 2: Process\",\n * \"log:Step 3: Complete\",\n * \"groupEnd\"\n * ]\n * operations // => expected\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const withGroup = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, options) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n if (options?.collapsed) {\n console.groupCollapsed(options.label);\n } else {\n console.group(options?.label);\n }\n}), () => self, () => effect.sync(() => {\n console.groupEnd();\n}))));\n/**\n * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes.\n *\n * **Example** (Timing an effect)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect } from \"effect\"\n *\n * const operations: Array<string> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * time: (label?: string) => operations.push(`start:${label}`),\n * timeEnd: (label?: string) => operations.push(`end:${label}`),\n * log: (message: string) => operations.push(`log:${message}`)\n * })\n *\n * const program = Effect.gen(function*() {\n * yield* Console.withTime(\n * Effect.gen(function*() {\n * yield* Console.log(\"Operation completed\")\n * }),\n * \"my-operation\"\n * )\n * })\n *\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * operations // => [\"start:my-operation\", \"log:Operation completed\", \"end:my-operation\"]\n * ```\n *\n * @stability stable\n * @category accessors\n * @since 2.0.0\n */\nexport const withTime = /*#__PURE__*/dual(args => core.isEffect(args[0]), (self, label) => consoleWith(console => effect.acquireUseRelease(effect.sync(() => {\n console.time(label);\n}), () => self, () => effect.sync(() => {\n console.timeEnd(label);\n}))));\n//# sourceMappingURL=Console.js.map","/**\n * Manages many fibers together inside one scope.\n *\n * A `FiberSet<A, E>` tracks running fibers, removes each fiber when it\n * completes, and interrupts all still-running fibers when the owning scope\n * closes. This module includes scoped runtime constructors plus helpers for\n * adding, clearing, running, counting, joining, and waiting for managed fibers.\n *\n * A fiber's success or failure does not interrupt the other fibers or close\n * the set. The set removes the completed fiber and keeps accepting new ones.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Cause from \"./Cause.js\";\nimport * as Deferred from \"./Deferred.js\";\nimport * as Effect from \"./Effect.js\";\nimport * as Exit from \"./Exit.js\";\nimport * as Fiber from \"./Fiber.js\";\nimport * as Filter from \"./Filter.js\";\nimport { constVoid, dual } from \"./Function.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as internalEffect from \"./internal/effect.js\";\nimport * as Iterable from \"./Iterable.js\";\nimport * as Predicate from \"./Predicate.js\";\nconst TypeId = \"~effect/FiberSet\";\n/**\n * Checks whether a value is a FiberSet.\n *\n * **Example** (Checking if a value is a FiberSet)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * return [FiberSet.isFiberSet(set), FiberSet.isFiberSet({})]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [true, false]\n * ```\n *\n * @stability stable\n * @category guards\n * @since 2.0.0\n */\nexport const isFiberSet = u => Predicate.hasProperty(u, TypeId);\nconst Proto = {\n [TypeId]: TypeId,\n [Symbol.iterator]() {\n if (this.state._tag === \"Closed\") {\n return Iterable.empty();\n }\n return this.state.backing[Symbol.iterator]();\n },\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"FiberSet\",\n state: this.state\n };\n }\n};\nconst makeUnsafe = (backing, deferred) => {\n const self = Object.create(Proto);\n self.state = {\n _tag: \"Open\",\n backing\n };\n self.deferred = deferred;\n return self;\n};\n/**\n * Creates a scoped `FiberSet` for storing fibers.\n *\n * **Details**\n *\n * When the associated Scope is closed, all fibers in the set will be\n * interrupted. You can add fibers to the set using `FiberSet.add` or\n * `FiberSet.run`, and the fibers will be automatically removed from the\n * FiberSet when they complete.\n *\n * **Example** (Creating a scoped FiberSet)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // run some effects and add the fibers to the set\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * yield* Effect.yieldNow\n * return yield* FiberSet.size(set)\n * }).pipe(\n * Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n *\n * const actual = await Effect.runPromise(program)\n * actual // => 2\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = () => Effect.acquireRelease(Effect.sync(() => makeUnsafe(new Set(), Deferred.makeUnsafe())), set => Effect.suspend(() => {\n const state = set.state;\n if (state._tag === \"Closed\") return Effect.void;\n set.state = {\n _tag: \"Closed\"\n };\n const fibers = state.backing;\n return Fiber.interruptAll(fibers).pipe(Deferred.into(set.deferred));\n}));\n/**\n * Creates a scoped run function that forks effects into a new `FiberSet`.\n *\n * **Details**\n *\n * Each call returns the forked fiber and adds it to the set. Managed fibers are\n * removed when they complete and are interrupted when the set's scope closes.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Creating a scoped runtime)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const runFork = yield* FiberSet.makeRuntime()\n *\n * // Fork effects using the runtime\n * const fiber1 = runFork(Effect.succeed(\"hello\"))\n * const fiber2 = runFork(Effect.succeed(\"world\"))\n *\n * return [yield* Fiber.join(fiber1), yield* Fiber.join(fiber2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const makeRuntime = () => Effect.flatMap(make(), self => runtime(self)());\n/**\n * Creates a scoped run function that forks effects into a new `FiberSet` and\n * returns a `Promise` for each effect result.\n *\n * **When to use**\n *\n * Use when many scoped fibers should be tracked as a set while exposing each\n * result through Promise-based APIs.\n *\n * **Details**\n *\n * Managed fibers are removed when they complete and are interrupted when the\n * set's scope closes. Each Promise resolves with the effect's success value or\n * rejects with the squashed failure cause.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Creating a promise runtime)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const runPromise = yield* FiberSet.makeRuntimePromise()\n *\n * // Run effects as promises\n * const promise1 = runPromise(Effect.succeed(\"hello\"))\n * const promise2 = runPromise(Effect.succeed(\"world\"))\n *\n * return [yield* Effect.promise(() => promise1), yield* Effect.promise(() => promise2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 3.13.0\n */\nexport const makeRuntimePromise = () => Effect.flatMap(make(), self => runtimePromise(self)());\nconst internalFiberId = -1;\nconst isInternalInterruption = /*#__PURE__*/Filter.toPredicate(/*#__PURE__*/Filter.compose(Cause.filterInterruptors, /*#__PURE__*/Filter.has(internalFiberId)));\n/**\n * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe\n * mutation.\n *\n * **When to use**\n *\n * Use when an already forked fiber must be registered immediately and\n * synchronous interruption on a closed set is acceptable.\n *\n * **Details**\n *\n * When the fiber completes, it is removed from the set. If the set is already\n * closed, the supplied fiber is interrupted immediately. Non-interruption\n * failures are recorded for `FiberSet.join`.\n *\n * **Example** (Adding a fiber unsafely)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const fiber = yield* Effect.forkChild(Effect.never)\n *\n * // Unsafe add - doesn't return an Effect\n * FiberSet.addUnsafe(set, fiber)\n *\n * // The fiber is now managed by the set\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 1\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 4.0.0\n */\nexport const addUnsafe = /*#__PURE__*/dual(args => isFiberSet(args[0]), (self, fiber, options) => {\n if (self.state._tag === \"Closed\") {\n fiber.interruptUnsafe(internalFiberId);\n return;\n } else if (self.state.backing.has(fiber)) {\n return;\n }\n self.state.backing.add(fiber);\n fiber.addObserver(exit => {\n if (self.state._tag === \"Closed\") {\n return;\n }\n self.state.backing.delete(fiber);\n if (Exit.isFailure(exit) && (options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !Cause.hasInterruptsOnly(exit.cause))) {\n Deferred.doneUnsafe(self.deferred, exit);\n }\n });\n});\n/**\n * Adds a fiber to the FiberSet. When the fiber completes, it will be removed.\n *\n * **Details**\n *\n * Set `propagateInterruption: true` to report external interruptions to\n * {@link join}.\n *\n * **Example** (Adding a fiber)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const fiber = yield* Effect.forkChild(Effect.never)\n *\n * // Add the fiber to the set\n * yield* FiberSet.add(set, fiber)\n *\n * // The fiber is now managed by the set\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 1\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const add = /*#__PURE__*/dual(args => isFiberSet(args[0]), (self, fiber, options) => Effect.sync(() => addUnsafe(self, fiber, options)));\n/**\n * Interrupts all fibers in the `FiberSet` and clears the set.\n *\n * **Example** (Clearing all fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // Add some fibers\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * const sizeBefore = yield* FiberSet.size(set)\n *\n * // Clear all fibers\n * yield* FiberSet.clear(set)\n *\n * return [sizeBefore, yield* FiberSet.size(set)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [2, 0]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const clear = self => Effect.suspend(() => {\n if (self.state._tag === \"Closed\") {\n return Effect.void;\n }\n return Fiber.interruptAllAs(self.state.backing, internalFiberId);\n});\nconst constInterruptedFiber = /*#__PURE__*/function () {\n let fiber = undefined;\n return () => {\n if (fiber === undefined) {\n fiber = Effect.runFork(Effect.interrupt);\n }\n return fiber;\n };\n}();\n/**\n * Forks an Effect and adds the fiber to the FiberSet. The fiber is removed\n * when it completes.\n *\n * **Details**\n *\n * The new fiber starts interruptible, even when the caller is uninterruptible.\n * By default, it runs synchronously until it suspends, yields, or completes\n * before `run` returns. Set `startImmediately: false` to defer startup as in\n * `Effect.forkChild`.\n *\n * The set owns the fiber, not the caller: it can outlive the caller's\n * completion or interruption. Forking and registration are interruption-safe,\n * so caller interruption cannot leave the fiber untracked. Closing the owning\n * scope from another fiber interrupts managed fibers and awaits their finalizers.\n *\n * Set `propagateInterruption: true` to report external interruptions to\n * {@link join}.\n *\n * **Gotchas**\n *\n * Uninterruptible work can delay scope closure.\n *\n * **Example** (Forking effects into a set)\n *\n * ```ts import.meta.vitest\n * import { Effect, Fiber, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * // Fork and add to set\n * const fiber1 = yield* FiberSet.run(set, Effect.succeed(\"hello\"))\n * const fiber2 = yield* FiberSet.run(set, Effect.succeed(\"world\"))\n *\n * // Get results\n * return [yield* Fiber.join(fiber1), yield* Fiber.join(fiber2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const run = function () {\n const self = arguments[0];\n if (!Effect.isEffect(arguments[1])) {\n const options = arguments[1];\n return effect => runImpl(self, effect, options);\n }\n return runImpl(self, arguments[1], arguments[2]);\n};\nconst runImpl = (self, effect, options) => Effect.withFiber(parent => {\n if (self.state._tag === \"Closed\") {\n return Effect.sync(constInterruptedFiber);\n }\n const fiber = internalEffect.forkUnsafe(parent, effect, options?.startImmediately ?? true, true);\n addUnsafe(self, fiber, options);\n return Effect.succeed(fiber);\n});\n/**\n * Captures a `Runtime` and uses it to fork effects into the `FiberSet`.\n *\n * **Details**\n *\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Capturing a runtime)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Fiber, FiberSet } from \"effect\"\n *\n * class Users extends Context.Service<Users, {\n * readonly getAll: Effect.Effect<Array<unknown>>\n * }>()(\"Users\") {}\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const run = yield* FiberSet.runtime(set)<Users>()\n *\n * // run some effects and add the fibers to the set\n * const fiber = run(Effect.andThen(Users, (_) => _.getAll))\n * return (yield* Fiber.join(fiber)).length\n * }).pipe(\n * Effect.scoped // The fibers will be interrupted when the scope is closed\n * )\n *\n * const actual = await Effect.runPromise(Effect.provideService(program, Users, {\n * getAll: Effect.succeed([])\n * }))\n * actual // => 0\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const runtime = self => () => Effect.map(Effect.context(), services => {\n const runFork = Effect.runForkWith(services);\n return (effect, options) => {\n if (self.state._tag === \"Closed\") {\n return constInterruptedFiber();\n }\n const fiber = runFork(effect, options);\n addUnsafe(self, fiber, options);\n return fiber;\n };\n});\n/**\n * Captures a `Runtime` and returns a Promise-based runner that forks effects\n * into the `FiberSet`.\n *\n * **When to use**\n *\n * Use when you need to bridge effects to `Promise` values while still tracking\n * their fibers in a `FiberSet`.\n *\n * **Details**\n *\n * The returned run function returns a `Promise` for each effect result.\n * The returned function starts fibers like `Effect.runForkWith`.\n *\n * **Example** (Running effects as promises)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * const runPromise = yield* FiberSet.runtimePromise(set)()\n *\n * // Run effects as promises\n * const promise1 = runPromise(Effect.succeed(\"hello\"))\n * const promise2 = runPromise(Effect.succeed(\"world\"))\n *\n * return [yield* Effect.promise(() => promise1), yield* Effect.promise(() => promise2)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [\"hello\", \"world\"]\n * ```\n *\n * @see {@link runtime} for a runner that returns the forked `Fiber`\n *\n * @stability stable\n * @category combinators\n * @since 3.13.0\n */\nexport const runtimePromise = self => () => Effect.map(runtime(self)(), runFork => (effect, options) => new Promise((resolve, reject) => runFork(effect, options).addObserver(exit => {\n if (Exit.isSuccess(exit)) {\n resolve(exit.value);\n } else {\n reject(Cause.squash(exit.cause));\n }\n})));\n/**\n * Gets the number of fibers currently in the FiberSet.\n *\n * **Example** (Checking the set size)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * const sizeBefore = yield* FiberSet.size(set)\n *\n * // Add some fibers\n * yield* FiberSet.run(set, Effect.never)\n * yield* FiberSet.run(set, Effect.never)\n *\n * return [sizeBefore, yield* FiberSet.size(set)]\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => [0, 2]\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const size = self => Effect.sync(() => self.state._tag === \"Closed\" ? 0 : self.state.backing.size);\n/**\n * Waits for the `FiberSet` to fail or close.\n *\n * **Details**\n *\n * Fails with the first recorded fiber failure. A successful fiber is removed\n * without completing `join`; use {@link awaitEmpty} to wait for an empty set.\n *\n * By default, failures caused only by interruption are ignored. If the fiber\n * was registered with `propagateInterruption: true`, its interruption is\n * recorded unless the set itself interrupted it, as on scope closure or\n * `clear`.\n *\n * **Example** (Joining failing fibers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n * yield* FiberSet.add(set, Effect.runFork(Effect.fail(\"error\")))\n *\n * // parent fiber will fail with \"error\"\n * yield* FiberSet.join(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.exit(Effect.scoped(program)))\n * actual // => Exit.fail(\"error\")\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 2.0.0\n */\nexport const join = self => Deferred.await(self.deferred);\n/**\n * Waits until the fiber set is empty.\n *\n * **Example** (Waiting for an empty set)\n *\n * ```ts import.meta.vitest\n * import { Effect, FiberSet } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const set = yield* FiberSet.make()\n *\n * yield* FiberSet.run(set, Effect.yieldNow)\n * yield* FiberSet.run(set, Effect.yieldNow)\n *\n * // Wait for all fibers to complete\n * yield* FiberSet.awaitEmpty(set)\n *\n * return yield* FiberSet.size(set)\n * })\n *\n * const actual = await Effect.runPromise(Effect.scoped(program))\n * actual // => 0\n * ```\n *\n * @stability stable\n * @category combinators\n * @since 3.13.0\n */\nexport const awaitEmpty = self => Effect.whileLoop({\n while: () => self.state._tag === \"Open\" && self.state.backing.size > 0,\n body: () => Fiber.await(Iterable.headUnsafe(self)),\n step: constVoid\n});\n//# sourceMappingURL=FiberSet.js.map","/**\n * Defines loggers and log-event data for Effect programs.\n *\n * A `Logger<Message, Output>` receives each log event as `Options` and turns it\n * into output such as a formatted string, structured object, console write,\n * file write, JSON line, or trace span event. This module also includes active\n * logger references, console routing helpers, built-in formatters, batching,\n * file logging, and layers for installing loggers.\n *\n * When a log effect (`Effect.log`, `Effect.logWithLevel`, or a level-specific\n * variant) invokes a logger, it does so synchronously in the logging fiber\n * before the log effect completes. A logger that defers work says so in its own\n * documentation, as `batched` and `toFile` do.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Array from \"./Array.js\";\nimport * as FileSystem from \"./FileSystem.js\";\nimport * as Formatter from \"./Formatter.js\";\nimport { dual } from \"./Function.js\";\nimport { isEffect, withFiber } from \"./internal/core.js\";\nimport * as effect from \"./internal/effect.js\";\nimport * as InternalRecord from \"./internal/record.js\";\nimport * as Layer from \"./Layer.js\";\nimport * as Predicate from \"./Predicate.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"./References.js\";\nconst TypeId = \"~effect/Logger\";\n/**\n * Returns `true` if the specified value is a `Logger`, otherwise returns `false`.\n *\n * **Example** (Checking logger values)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * const myLogger = Logger.make(() => undefined)\n *\n * Logger.isLogger(myLogger) // => true\n * Logger.isLogger(\"not a logger\") // => false\n * Logger.isLogger({ log: () => {} }) // => false\n * ```\n *\n * @stability stable\n * @category guards\n * @since 4.0.0\n */\nexport const isLogger = u => Predicate.hasProperty(u, TypeId);\n/**\n * Context reference containing the active loggers for the current fiber.\n *\n * **Details**\n *\n * By default this set includes the default logger and the tracer logger.\n * Providing `Logger.layer` replaces or merges with this set depending on its\n * options.\n *\n * **Example** (Accessing current loggers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n * messages.push(options.message)\n * })\n * const program = Effect.gen(function*() {\n * const currentLoggers = yield* Effect.service(Logger.CurrentLoggers)\n * yield* Effect.log(\"Hello from custom logger\").pipe(\n * Effect.provide(Logger.layer([customLogger]))\n * )\n * return currentLoggers.has(Logger.defaultLogger)\n * })\n *\n * Effect.runSync(program) // => true\n * messages // => [[\"Hello from custom logger\"]]\n * ```\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const CurrentLoggers = effect.CurrentLoggers;\n/**\n * Context reference that routes the built-in default logger and TTY pretty\n * console logger to stderr.\n *\n * **When to use**\n *\n * Use to route built-in logger output to stderr while keeping stdout reserved\n * for protocol messages or data output.\n *\n * **Details**\n *\n * The reference defaults to `false`. Providing `true` makes the affected\n * loggers call `console.error` instead of `console.log`.\n *\n * @see {@link defaultLogger} for the runtime logger affected by this reference\n * @see {@link consolePretty} for the TTY-mode pretty console logger affected by this reference\n * @see {@link withConsoleError} for routing a specific formatter logger to `console.error`\n *\n * @stability stable\n * @category services\n * @since 4.0.0\n */\nexport const LogToStderr = effect.LogToStderr;\n/**\n * Transforms the output of a `Logger` using the provided function.\n *\n * **When to use**\n *\n * Use when an existing logger's output should be transformed without recreating the\n * logging logic.\n *\n * **Details**\n *\n * The returned logger calls `self` and then `f` inside the same `log` call.\n *\n * **Example** (Transforming logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<unknown> = []\n * const structuredLogger = Logger.make((options) => ({\n * message: options.message\n * }))\n *\n * // Transform to uppercase messages\n * const uppercaseLogger = Logger.map(\n * structuredLogger,\n * (output) => ({ ...output, message: String(output.message).toUpperCase() })\n * )\n *\n * const collector = Logger.make((options) => outputs.push(uppercaseLogger.log(options)))\n * const program = Effect.log(\"hello\").pipe(Effect.provide(Logger.layer([collector])))\n * Effect.runSync(program)\n * outputs // => [{ message: \"HELLO\" }]\n * ```\n *\n * @stability stable\n * @category mapping\n * @since 2.0.0\n */\nexport const map = /*#__PURE__*/dual(2, (self, f) => effect.loggerMake(options => f(self.log(options))));\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.log`.\n *\n * **When to use**\n *\n * Use when a logger's string or object output should be routed to `console.log` for\n * development or debugging.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call.\n *\n * **Example** (Writing logger output with console.log)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create a custom formatter\n * const customFormatter = Logger.make((options) =>\n * `${options.logLevel}: ${options.message}`\n * )\n *\n * const consoleLogger = Logger.withConsoleLog(customFormatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Hello World\").pipe(Effect.provide(Logger.layer([consoleLogger])))\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"Info: Hello World\"]\n * ```\n *\n * @stability stable\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleLog = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n return console.log(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console using `console.error`.\n *\n * **When to use**\n *\n * Use when logger output should be routed to `console.error`, such as error logs that\n * should appear on stderr instead of stdout.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call.\n *\n * **Example** (Writing logger output with console.error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Create an error-specific formatter\n * const errorFormatter = Logger.make((options) =>\n * `ERROR: ${options.message}`\n * )\n *\n * const errorLogger = Logger.withConsoleError(errorFormatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logError(\"Database connection failed\").pipe(Effect.provide(Logger.layer([errorLogger])))\n * return yield* TestConsole.errorLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"ERROR: Database connection failed\"]\n * ```\n *\n * @stability stable\n * @category logging\n * @since 2.0.0\n */\nexport const withConsoleError = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n return console.error(self.log(options));\n});\n/**\n * Returns a new `Logger` that writes all output of the specified `Logger` to\n * the console.\n *\n * **Details**\n *\n * Writes to the console inside the `log` call. Will use the appropriate console\n * method (i.e. `console.log`, `console.error`, etc.) based upon the current\n * `LogLevel`.\n *\n * `Debug` uses `console.debug`, `Info` uses `console.info`, `Trace` uses\n * `console.trace`, `Warn` uses `console.warn`, `Error` and `Fatal` use\n * `console.error`, and all other levels use `console.log`.\n *\n * **Example** (Writing logs with level-based console methods)\n *\n * ```ts import.meta.vitest\n * import { Console, Effect, Logger } from \"effect\"\n *\n * const messages: Array<ReadonlyArray<unknown>> = []\n * const testConsole: Console.Console = Object.assign(Object.create(console), {\n * info: (message: unknown) => messages.push([\"info\", message]),\n * warn: (message: unknown) => messages.push([\"warn\", message]),\n * error: (message: unknown) => messages.push([\"error\", message])\n * })\n * const formatter = Logger.make((options) =>\n * `[${options.logLevel}] ${options.message}`\n * )\n *\n * const leveledLogger = Logger.withLeveledConsole(formatter)\n *\n * const program = Effect.gen(function*() {\n * yield* Effect.logInfo(\"Info message\") // -> console.info\n * yield* Effect.logWarning(\"Warning\") // -> console.warn\n * yield* Effect.logError(\"Error occurred\") // -> console.error\n * }).pipe(Effect.provide(Logger.layer([leveledLogger])))\n * Effect.runSync(Effect.provideService(program, Console.Console, testConsole))\n * const expected = [\n * [\"info\", \"[Info] Info message\"],\n * [\"warn\", \"[Warn] Warning\"],\n * [\"error\", \"[Error] Error occurred\"]\n * ]\n * messages // => expected\n * ```\n *\n * @stability stable\n * @category logging\n * @since 3.8.0\n */\nexport const withLeveledConsole = self => effect.loggerMake(options => {\n const console = options.fiber.getRef(effect.ConsoleRef);\n const output = self.log(options);\n switch (options.logLevel) {\n case \"Debug\":\n return console.debug(output);\n case \"Info\":\n return console.info(output);\n case \"Trace\":\n return console.trace(output);\n case \"Warn\":\n return console.warn(output);\n case \"Error\":\n case \"Fatal\":\n return console.error(output);\n default:\n return console.log(output);\n }\n});\n/**\n * Match strings that do not contain any whitespace characters, double quotes,\n * or equal signs.\n */\nconst textOnly = /^[^\\s\"=]*$/;\n/**\n * Escapes double quotes in a string.\n */\nconst escapeDoubleQuotes = s => `\"${s.replace(/\\\\([\\s\\S])|(\")/g, \"\\\\$1$2\")}\"`;\n/**\n * Formats the identifier of a `Fiber` by prefixing it with a hash tag.\n */\nconst formatFiberId = fiberId => `#${fiberId}`;\n/**\n * Used by both {@link formatSimple} and {@link formatLogFmt} to render a log\n * message.\n *\n * @internal\n */\nconst format = (quoteValue, space) => ({\n cause,\n date,\n fiber,\n logLevel,\n message\n}) => {\n const formatUnknown = value => typeof value === \"string\" ? value : Formatter.format(value, {\n space\n });\n const formatValue = value => value.match(textOnly) ? value : quoteValue(value);\n const format = (label, value) => `${effect.formatLabel(label)}=${formatValue(value)}`;\n const append = (label, value) => \" \" + format(label, value);\n let out = format(\"timestamp\", date.toISOString());\n out += append(\"level\", logLevel.toUpperCase());\n out += append(\"fiber\", formatFiberId(fiber.id));\n const messages = Array.ensure(message);\n for (let i = 0; i < messages.length; i++) {\n out += append(\"message\", formatUnknown(messages[i]));\n }\n if (cause.reasons.length > 0) {\n out += append(\"cause\", effect.causePretty(cause));\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const span of spans) {\n out += \" \" + effect.formatLogSpan(span, now);\n }\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [label, value] of Object.entries(annotations)) {\n out += append(label, formatUnknown(value));\n }\n return out;\n};\n/**\n * Creates a new `Logger` from a log function.\n *\n * **Details**\n *\n * The log function receives an options object containing the message, log level,\n * cause, fiber information, and timestamp, and should return the desired output.\n * `log` is called synchronously in the fiber that logs, before the log effect\n * completes.\n *\n * **Gotchas**\n *\n * If `log` throws, the log effect dies with the thrown value as a defect.\n *\n * **Example** (Creating loggers from functions)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const outputs: Array<string> = []\n * const textLogger = Logger.make((options) =>\n * `${options.logLevel}: ${options.message}`\n * )\n * const collector = Logger.make((options) => outputs.push(textLogger.log(options)))\n *\n * const program = Effect.log(\"Hello World\").pipe(\n * Effect.provide(Logger.layer([collector]))\n * )\n * Effect.runSync(program)\n * outputs // => [\"Info: Hello World\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = effect.loggerMake;\n/**\n * The default logging implementation used by the Effect runtime.\n *\n * **Example** (Referencing the default logger)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.defaultLogger) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const defaultLogger = effect.defaultLogger;\n/**\n * A `Logger` which outputs logs as a string.\n *\n * **Details**\n *\n * For example, a simple log entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as simple strings)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * // Use the simple format logger\n * const stableSimple = Logger.map(Logger.formatSimple, (output) =>\n * output\n * .replace(/timestamp=\\S+ /, \"\")\n * .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Application started\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableSimple)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=INFO message=\\\"Application started\\\"\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatSimple = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(escapeDoubleQuotes));\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style.\n *\n * **Details**\n *\n * For example, a logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`.\n *\n * **Example** (Formatting logs as logfmt)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableLogFmt = Logger.map(Logger.formatLogFmt, (output) =>\n * output\n * .replace(/timestamp=\\S+ /, \"\")\n * .replace(/fiber=#\\d+ /, \"\")\n * )\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"User login\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableLogFmt)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"level=INFO message=\\\"User login\\\"\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatLogFmt = /*#__PURE__*/effect.loggerMake(/*#__PURE__*/format(JSON.stringify, 0));\n/**\n * A `Logger` which outputs logs using a structured format.\n *\n * **Details**\n *\n * For example, a structured entry can contain `message: [ \"hello\" ]`,\n * `level: \"INFO\"`, `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Formatting logs as structured objects)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableStructured = Logger.map(Logger.formatStructured, (output) => ({\n * message: output.message,\n * level: output.level\n * }))\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"User action\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableStructured)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [{ message: \"User action\", level: \"INFO\" }]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatStructured = /*#__PURE__*/effect.loggerMake(({\n cause,\n date,\n fiber,\n logLevel,\n message\n}) => {\n const annotationsObj = {};\n const spansObj = {};\n const annotations = fiber.getRef(CurrentLogAnnotations);\n for (const [key, value] of Object.entries(annotations)) {\n InternalRecord.assignProperty(annotationsObj, key, effect.structuredMessage(value));\n }\n const now = date.getTime();\n const spans = fiber.getRef(CurrentLogSpans);\n for (const [label, timestamp] of spans) {\n InternalRecord.assignProperty(spansObj, label, now - timestamp);\n }\n const messageArr = Array.ensure(message);\n return {\n message: messageArr.length === 1 ? effect.structuredMessage(messageArr[0]) : messageArr.map(effect.structuredMessage),\n level: logLevel.toUpperCase(),\n timestamp: date.toISOString(),\n cause: cause.reasons.length > 0 ? effect.causePretty(cause) : undefined,\n annotations: annotationsObj,\n spans: spansObj,\n fiberId: formatFiberId(fiber.id)\n };\n});\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line.\n *\n * **Details**\n *\n * For example, a JSON entry can render as `{\"message\":[\"hello\"],\"level\":\"INFO\",\n * \"timestamp\":\"2025-01-03T14:28:57.508Z\",\"annotations\":{\"key\":\"value\"},\n * \"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Formatting logs as JSON)\n *\n * ```ts import.meta.vitest\n * import { Effect, Formatter, Logger } from \"effect\"\n * import { TestConsole } from \"effect/testing\"\n *\n * const stableJson = Logger.map(Logger.formatJson, (json) => {\n * const output = JSON.parse(json)\n * return Formatter.formatJson({ message: output.message, level: output.level })\n * })\n * const program = Effect.gen(function*() {\n * yield* Effect.log(\"Server started\").pipe(\n * Effect.provide(Logger.layer([Logger.withConsoleLog(stableJson)]))\n * )\n * return yield* TestConsole.logLines\n * }).pipe(Effect.provide(TestConsole.layer))\n *\n * await Effect.runPromise(program) // => [\"{\\\"message\\\":\\\"Server started\\\",\\\"level\\\":\\\"INFO\\\"}\"]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const formatJson = /*#__PURE__*/map(formatStructured, Formatter.formatJson);\n/**\n * Creates a scoped logger that batches the output of another logger.\n *\n * **Details**\n *\n * The returned logger formats each event with `self` and buffers the output\n * during the log call. A background fiber passes pending entries to `flush`\n * once per window, skipping empty windows. When the scope closes, the\n * background fiber is interrupted and the scope finalizer flushes any remaining\n * entries.\n *\n * **Example** (Batching logger output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const flushed: Array<ReadonlyArray<string>> = []\n * const messageLogger = Logger.make((options) => String(options.message))\n * const batchedLogger = Logger.batched(messageLogger, {\n * window: \"1 hour\",\n * flush: (messages) =>\n * Effect.sync(() => {\n * flushed.push(messages)\n * })\n * })\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const logger = yield* batchedLogger\n * yield* Effect.log(\"Event 1\").pipe(Effect.provide(Logger.layer([logger])))\n * yield* Effect.log(\"Event 2\").pipe(Effect.provide(Logger.layer([logger])))\n * }))\n * await Effect.runPromise(program)\n * flushed // => [[\"Event 1\", \"Event 2\"]]\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const batched = /*#__PURE__*/dual(2, (self, options) => effect.suspend(() => {\n let buffer = [];\n const flush = effect.uninterruptible(effect.suspend(() => {\n if (buffer.length === 0) {\n return effect.void;\n }\n const arr = buffer;\n buffer = [];\n return options.flush(arr);\n }));\n return effect.uninterruptibleMask(restore => restore(effect.sleep(options.window).pipe(effect.andThen(flush), effect.forever)).pipe(effect.forkDetach, effect.flatMap(fiber => effect.addFinalizer(() =>\n // Wait for any in-flight flush before draining the remaining buffer.\n effect.andThen(effect.fiberInterrupt(fiber), flush))), effect.as(effect.loggerMake(options => {\n buffer.push(self.log(options));\n }))));\n}));\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Chooses between tty and browser implementation. If the runtime\n * platform is known and fixed, prefer {@link consolePrettyBrowser} or\n * {@link consolePrettyTty}.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePretty()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * **Example** (Logging with console.error, when the environment has TTY)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Logger } from \"effect\"\n *\n * const prettyLoggerLayer = Layer.merge(\n * Logger.layer([Logger.consolePretty()]),\n * Layer.succeed(Logger.LogToStderr, true)\n * )\n *\n * Effect.log('hello').pipe(\n * Effect.provide(prettyLoggerLayer),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePrettyBrowser} for browser-specific implementation\n * @see {@link consolePrettyTty} for the TTY-mode implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePretty = effect.consolePretty;\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Intended to be used on platforms with a browser console.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePrettyBrowser()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePretty} for the platform-independent implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePrettyBrowser = effect.prettyLoggerBrowser;\n/**\n * A `Logger` which outputs logs in a \"pretty\" format and writes them to the\n * console. Intended to be used on platforms with tty console.\n *\n * **Details**\n *\n * For example, pretty output can render as\n * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line\n * such as `key: value`.\n *\n * **Example** (Logging with pretty console output)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const prettyLogger = Logger.layer([Logger.consolePrettyTty()])\n *\n * Effect.log(\"hello\").pipe(\n * Effect.withLogSpan('label'),\n * Effect.annotateLogs('key', 'value'),\n * Effect.provide(prettyLogger),\n * Effect.runSync\n * )\n * ```\n *\n * **Example** (Logging with console.error)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Logger } from \"effect\"\n *\n * const prettyLoggerLayer = Layer.merge(\n * Logger.layer([Logger.consolePrettyTty()]),\n * Layer.succeed(Logger.LogToStderr, true)\n * )\n *\n * Effect.log('hello').pipe(\n * Effect.provide(prettyLoggerLayer),\n * Effect.runSync\n * )\n * ```\n *\n * @see {@link consolePretty} for the platform-independent implementation\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consolePrettyTty = effect.prettyLoggerTty;\n/**\n * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt)\n * style and writes them to the console.\n *\n * **Details**\n *\n * For example, a console logfmt entry is rendered as\n * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=info`.\n *\n * **Example** (Logging logfmt output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleLogFmt) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleLogFmt = /*#__PURE__*/withConsoleLog(formatLogFmt);\n/**\n * A `Logger` which outputs logs using a structured format and writes them to\n * the console.\n *\n * **Details**\n *\n * For example, console structured output can contain\n * `message: [ \"info\", \"message\" ]`, `level: \"INFO\"`,\n * `timestamp: \"2025-01-03T14:25:39.666Z\"`,\n * `annotations: { key: \"value\" }`, `spans: { label: 0 }`, and\n * `fiberId: \"#1\"`.\n *\n * **Example** (Logging structured output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleStructured) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleStructured = /*#__PURE__*/withConsoleLog(formatStructured);\n/**\n * A `Logger` which outputs logs using a structured format serialized as JSON\n * on a single line and writes them to the console.\n *\n * **Details**\n *\n * For example, console JSON output can render as\n * `{\"message\":[\"hello\"],\"level\":\"INFO\",\"timestamp\":\"2025-01-03T14:28:57.508Z\",\n * \"annotations\":{\"key\":\"value\"},\"spans\":{\"label\":0},\"fiberId\":\"#1\"}`.\n *\n * **Example** (Logging JSON output to the console)\n *\n * ```ts import.meta.vitest\n * import { Logger } from \"effect\"\n *\n * Logger.isLogger(Logger.consoleJson) // => true\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const consoleJson = /*#__PURE__*/withConsoleLog(formatJson);\n/**\n * A `Logger` which includes log messages as tracer span events.\n *\n * **Details**\n *\n * This logger integrates logging with distributed tracing by recording\n * all log messages as events on the current local span, making them visible\n * in tracing tools like OpenTelemetry, Jaeger, or Zipkin. A log made with no\n * current span, or while the nearest parent span is an `ExternalSpan`, is not\n * recorded by this logger.\n *\n * This logger is included in the default set of loggers for all Effect programs,\n * so log messages automatically appear as span events unless you override the\n * default loggers.\n *\n * **Example** (Recording logs as trace span events)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const program = Effect.log(\"span event\").pipe(\n * Effect.withSpan(\"operation\"),\n * Effect.provide(Logger.layer([Logger.tracerLogger]))\n * )\n * Effect.runSync(program)\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const tracerLogger = effect.tracerLogger;\n/**\n * Creates a `Layer` which will overwrite the current set of loggers with the\n * specified array of `loggers`.\n *\n * **Details**\n *\n * If the specified array of `loggers` should be _merged_ with the current set\n * of loggers (instead of overwriting them), set `mergeWithExisting` to `true`.\n *\n * **Example** (Providing logger layers)\n *\n * ```ts import.meta.vitest\n * import { Effect, Logger } from \"effect\"\n *\n * const messages: Array<unknown> = []\n * const customLogger = Logger.make((options) => {\n * messages.push(options.message)\n * })\n * const CustomLoggerLayer = Logger.layer([customLogger])\n *\n * const program = Effect.log(\"Application started\").pipe(\n * Effect.provide(CustomLoggerLayer)\n * )\n * Effect.runSync(program)\n * messages // => [[\"Application started\"]]\n * ```\n *\n * @stability stable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (loggers, options) => Layer.effect(CurrentLoggers, withFiber(effect.fnUntraced(function* (fiber) {\n const currentLoggers = new Set(options?.mergeWithExisting === true ? fiber.getRef(effect.CurrentLoggers) : []);\n for (const logger of loggers) {\n currentLoggers.add(isEffect(logger) ? yield* logger : logger);\n }\n return currentLoggers;\n})));\n/**\n * Creates a scoped logger that writes string logger output to a file.\n *\n * **Details**\n *\n * The returned effect requires `FileSystem` and `Scope`. The file logger is\n * built on `batched`, so each log call formats and buffers its string output.\n * Each flushed batch is written to the specified path, and remaining entries\n * are flushed when the scope closes.\n *\n * **Example** (Writing JSON logs to a file)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n * writeAll: (buffer: Uint8Array) => Effect.sync(() => {\n * writes.push(new TextDecoder().decode(buffer).trim())\n * })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/log.txt\")\n * yield* Effect.log(\"a\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * yield* Effect.log(\"b\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * yield* Effect.log(\"c\").pipe(Effect.provide(Logger.layer([fileLogger])))\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"a\\nb\\nc\"]\n * ```\n *\n * **Example** (Writing logs to files)\n *\n * ```ts import.meta.vitest\n * import { Effect, FileSystem, Logger } from \"effect\"\n *\n * const writes: Array<string> = []\n * const file = {\n * writeAll: (buffer: Uint8Array) => Effect.sync(() => {\n * writes.push(new TextDecoder().decode(buffer).trim())\n * })\n * } as unknown as FileSystem.File\n * const fileSystem = FileSystem.makeNoop({ open: () => Effect.succeed(file) })\n * const messageLogger = Logger.make((options) => String(options.message))\n *\n * const program = Effect.scoped(Effect.gen(function*() {\n * const fileLogger = yield* Logger.toFile(messageLogger, \"/tmp/app.log\", {\n * batchWindow: \"1 hour\"\n * })\n * yield* Effect.log(\"Application started\").pipe(\n * Effect.provide(Logger.layer([fileLogger]))\n * )\n * })).pipe(Effect.provideService(FileSystem.FileSystem, fileSystem))\n *\n * await Effect.runPromise(program)\n * writes // => [\"Application started\"]\n * ```\n *\n * @stability unstable\n * @category logging\n * @since 4.0.0\n */\nexport const toFile = /*#__PURE__*/dual(args => isLogger(args[0]), (self, path, options) => effect.gen(function* () {\n const fs = yield* FileSystem.FileSystem;\n const logFile = yield* fs.open(path, {\n flag: \"a+\",\n ...options\n });\n const encoder = new TextEncoder();\n return yield* batched(self, {\n window: options?.batchWindow ?? 1000,\n flush: output => effect.ignore(logFile.writeAll(encoder.encode(output.join(\"\\n\") + \"\\n\")))\n });\n}));\n//# sourceMappingURL=Logger.js.map","/**\n * Stores fiber-safe mutable state inside Effect programs.\n *\n * A `Ref<A>` holds one value and exposes reads, writes, and atomic\n * transformations as effects, so state changes compose with Effect's\n * concurrency model. This module includes constructors, safe and unsafe reads,\n * set and get-and-set helpers, update and modify helpers, and conditional\n * update variants that leave the value unchanged when an `Option.none` result\n * is returned.\n *\n * @stability stable\n * @since 2.0.0\n */\nimport * as Effect from \"./Effect.js\";\nimport { dual, identity } from \"./Function.js\";\nimport { PipeInspectableProto } from \"./internal/core.js\";\nimport * as MutableRef from \"./MutableRef.js\";\nconst TypeId = \"~effect/Ref\";\nconst RefProto = {\n [TypeId]: {\n _A: identity\n },\n ...PipeInspectableProto,\n toJSON() {\n return {\n _id: \"Ref\",\n ref: this.ref\n };\n }\n};\n/**\n * Creates a new Ref with the specified initial value (unsafe version).\n *\n * **When to use**\n *\n * Use when you need immediate synchronous construction and can guarantee\n * that creating the `Ref` outside of `Effect` is safe.\n *\n * **Gotchas**\n *\n * Prefer `Ref.make` for Effect-wrapped creation in Effect programs.\n *\n * **Example** (Creating a ref unsafely)\n *\n * ```ts import.meta.vitest\n * import { Ref } from \"effect\"\n *\n * const counter = Ref.makeUnsafe(0)\n * Ref.getUnsafe(counter) // => 0\n * ```\n *\n * @stability stable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeUnsafe = value => {\n const self = Object.create(RefProto);\n self.ref = MutableRef.make(value);\n return self;\n};\n/**\n * Creates a new Ref with the specified initial value.\n *\n * **When to use**\n *\n * Use to create a `Ref` for shared mutable state inside an Effect program.\n *\n * **Example** (Creating a ref)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(42)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @see {@link makeUnsafe} for synchronous construction outside Effect code\n *\n * @stability stable\n * @category constructors\n * @since 2.0.0\n */\nexport const make = value => Effect.sync(() => makeUnsafe(value));\n/**\n * Gets the current value of the Ref.\n *\n * **When to use**\n *\n * Use to read the current `Ref` value without changing it.\n *\n * **Example** (Getting the current value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(42)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * ```\n *\n * @see {@link set} for replacing the current value\n *\n * @stability stable\n * @category getters\n * @since 2.0.0\n */\nexport const get = self => Effect.sync(() => self.ref.current);\n/**\n * Sets the value of the Ref to the specified value.\n *\n * **When to use**\n *\n * Use to replace the current `Ref` value with a known value.\n *\n * **Example** (Setting a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(0)\n * yield* Ref.set(ref, 42)\n * return yield* Ref.get(ref)\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const ref = yield* Ref.make(0)\n * yield* Ref.set(ref, 100)\n * return yield* Ref.get(ref)\n * })\n *\n * await Effect.runPromise(program) // => 42\n * await Effect.runPromise(program2) // => 100\n * ```\n *\n * @see {@link getAndSet} for setting while returning the previous value\n * @see {@link setAndGet} for setting while returning the new value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const set = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => MutableRef.set(self.ref, value)));\n/**\n * Gets the current value of the Ref, sets it to the specified value, and returns the previous value atomically.\n *\n * **When to use**\n *\n * Use to replace a plain `Ref` value while returning the previous value.\n *\n * **Example** (Replacing a value atomically)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(\"initial\")\n *\n * const previous = yield* Ref.getAndSet(ref, \"updated\")\n * const current = yield* Ref.get(ref)\n * return [previous, current]\n * })\n *\n * await Effect.runPromise(program) // => [\"initial\", \"updated\"]\n * ```\n *\n * @see {@link set} for setting without returning the previous value\n * @see {@link getAndUpdate} for deriving the new value from the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndSet = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => {\n const current = self.ref.current;\n self.ref.current = value;\n return current;\n}));\n/**\n * Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically.\n *\n * **When to use**\n *\n * Use to derive a new `Ref` value while returning the previous value.\n *\n * **Example** (Updating and returning the previous value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const previous = yield* Ref.getAndUpdate(counter, (n) => n * 2)\n * const current = yield* Ref.get(counter)\n * return [previous, current]\n * })\n *\n * await Effect.runPromise(program) // => [10, 20]\n * ```\n *\n * @see {@link update} for updating without returning the previous value\n * @see {@link updateAndGet} for returning the new value instead\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdate = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const current = self.ref.current;\n self.ref.current = f(current);\n return current;\n}));\n/**\n * Gets the current value of the Ref and updates it atomically with the given partial function.\n *\n * **When to use**\n *\n * Use to return the previous `Ref` value while applying a conditional update.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged. The effect\n * always returns the value that was in the Ref before the attempted update.\n *\n * **Example** (Conditionally updating and returning the previous value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const previous1 = yield* Ref.getAndUpdateSome(\n * counter,\n * (n) => n > 3 ? Option.some(n * 2) : Option.none()\n * )\n * const current1 = yield* Ref.get(counter)\n * const previous2 = yield* Ref.getAndUpdateSome(\n * counter,\n * (n) => n < 3 ? Option.some(n * 2) : Option.none()\n * )\n * const current2 = yield* Ref.get(counter)\n * return [previous1, current1, previous2, current2]\n * })\n *\n * await Effect.runPromise(program) // => [5, 10, 10, 10]\n * ```\n *\n * @see {@link getAndUpdate} for always applying an update\n * @see {@link updateSome} for conditional updates without returning the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const getAndUpdateSome = /*#__PURE__*/dual(2, (self, pf) => Effect.sync(() => {\n const current = self.ref.current;\n const option = pf(current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n return current;\n}));\n/**\n * Sets the value of the Ref atomically to the specified value and returns the new value.\n *\n * **When to use**\n *\n * Use when you want to set a `Ref` value and immediately get it back in one\n * atomic operation.\n *\n * **Example** (Setting and returning the new value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const ref = yield* Ref.make(10)\n *\n * const newValue = yield* Ref.setAndGet(ref, 42)\n * const current = yield* Ref.get(ref)\n * return [newValue, current]\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const counter = yield* Ref.make(0)\n * return yield* Ref.setAndGet(counter, 20)\n * })\n *\n * await Effect.runPromise(program) // => [42, 42]\n * await Effect.runPromise(program2) // => 20\n * ```\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const setAndGet = /*#__PURE__*/dual(2, (self, value) => Effect.sync(() => self.ref.current = value));\n/**\n * Modifies the value of the Ref atomically using the given function.\n *\n * **When to use**\n *\n * Use to compute both a separate return value and the next stored `Ref` value\n * in one atomic update.\n *\n * **Details**\n *\n * The function receives the current value and returns a tuple of\n * `[result, newValue]`. The Ref is updated with `newValue`, and `result` is\n * returned by the effect.\n *\n * **Example** (Modifying a value atomically)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const result = yield* Ref.modify(counter, (n) => [\n * `Previous value was ${n}`,\n * n * 2\n * ])\n * const current = yield* Ref.get(counter)\n * return [result, current]\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const state = yield* Ref.make({ count: 0, total: 0 })\n * return yield* Ref.modify(state, (s) => [\n * s.count,\n * { count: s.count + 1, total: s.total + s.count + 1 }\n * ])\n * })\n *\n * await Effect.runPromise(program) // => [\"Previous value was 10\", 20]\n * await Effect.runPromise(program2) // => 0\n * ```\n *\n * @see {@link updateAndGet} for returning the new stored value\n * @see {@link modifySome} for optionally updating while returning a separate result\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const [b, a] = f(self.ref.current);\n self.ref.current = a;\n return b;\n}));\n/**\n * Computes a result atomically and optionally updates the value of the `Ref`.\n *\n * **When to use**\n *\n * Use to compute a return value while optionally updating a plain `Ref`.\n *\n * **Details**\n *\n * The callback receives the current value and returns `[result, nextValue]`,\n * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`,\n * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left\n * unchanged. The returned effect always succeeds with `result`.\n *\n * **Example** (Conditionally modifying a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const result1 = yield* Ref.modifySome(\n * counter,\n * (n) =>\n * n > 3\n * ? [`incremented ${n}`, Option.some(n + 10)]\n * : [\"no change\", Option.none()]\n * )\n * const current1 = yield* Ref.get(counter)\n * const result2 = yield* Ref.modifySome(\n * counter,\n * (n) =>\n * n < 10\n * ? [`decremented ${n}`, Option.some(n - 5)]\n * : [\"no change\", Option.none()]\n * )\n * const current2 = yield* Ref.get(counter)\n * return [result1, current1, result2, current2]\n * })\n *\n * await Effect.runPromise(program) // => [\"incremented 5\", 15, \"no change\", 15]\n * ```\n *\n * @see {@link modify} for always storing a new value\n * @see {@link updateSome} for optional updates without a separate return value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const modifySome = /*#__PURE__*/dual(2, (self, pf) => modify(self, value => {\n const [b, option] = pf(value);\n return [b, option._tag === \"None\" ? value : option.value];\n}));\n/**\n * Updates the value of the Ref atomically using the given function.\n *\n * **When to use**\n *\n * Use to apply a `Ref` state transition without returning a value.\n *\n * **Example** (Updating a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * yield* Ref.update(counter, (n) => n * 2)\n * return yield* Ref.get(counter)\n * })\n *\n * const program2 = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n * yield* Ref.update(counter, (n: number) => n + 10)\n * return yield* Ref.get(counter)\n * })\n *\n * await Effect.runPromise(program) // => 10\n * await Effect.runPromise(program2) // => 15\n * ```\n *\n * @see {@link updateAndGet} for returning the new value\n * @see {@link getAndUpdate} for returning the previous value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const update = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n self.ref.current = f(self.ref.current);\n}));\n/**\n * Updates the value of the Ref atomically using the given function and returns the new value.\n *\n * **When to use**\n *\n * Use to apply a `Ref` state transition and return the new stored value.\n *\n * **Example** (Updating and returning the new value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * const newValue = yield* Ref.updateAndGet(counter, (n) => n * 3)\n * const current = yield* Ref.get(counter)\n * return [newValue, current]\n * })\n *\n * await Effect.runPromise(program) // => [15, 15]\n * ```\n *\n * @see {@link update} for updating without returning the new value\n * @see {@link getAndUpdate} for returning the previous value instead\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateAndGet = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => self.ref.current = f(self.ref.current)));\n/**\n * Updates the value of the Ref atomically using the given partial function.\n *\n * **When to use**\n *\n * Use to apply a conditional `Ref` update without returning a value.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged.\n *\n * **Example** (Conditionally updating a value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(5)\n *\n * yield* Ref.updateSome(\n * counter,\n * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()\n * )\n * const before = yield* Ref.get(counter)\n * yield* Ref.set(counter, 6)\n * yield* Ref.updateSome(\n * counter,\n * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none()\n * )\n * const after = yield* Ref.get(counter)\n * return [before, after]\n * })\n *\n * await Effect.runPromise(program) // => [5, 12]\n * ```\n *\n * @see {@link update} for always applying an update\n * @see {@link updateSomeAndGet} for returning the resulting current value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSome = /*#__PURE__*/dual(2, (self, f) => Effect.sync(() => {\n const option = f(self.ref.current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n}));\n/**\n * Updates the value of the Ref atomically using the given partial function and returns the current value.\n *\n * **When to use**\n *\n * Use to apply a conditional `Ref` update and return the resulting current\n * value.\n *\n * **Details**\n *\n * If the partial function returns `Option.some`, the Ref is updated with the\n * new value. If it returns `Option.none`, the Ref is left unchanged. The effect\n * returns the current value of the Ref after the potential update.\n *\n * **Example** (Conditionally updating and returning the current value)\n *\n * ```ts import.meta.vitest\n * import { Effect, Option, Ref } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const counter = yield* Ref.make(10)\n *\n * const result1 = yield* Ref.updateSomeAndGet(\n * counter,\n * (n) => n > 5 ? Option.some(n / 2) : Option.none()\n * )\n * const result2 = yield* Ref.updateSomeAndGet(\n * counter,\n * (n) => n > 5 ? Option.some(n / 2) : Option.none()\n * )\n * return [result1, result2]\n * })\n *\n * await Effect.runPromise(program) // => [5, 5]\n * ```\n *\n * @see {@link updateSome} for conditional updates without returning a value\n * @see {@link updateAndGet} for always updating and returning the new value\n *\n * @stability stable\n * @category mutations\n * @since 2.0.0\n */\nexport const updateSomeAndGet = /*#__PURE__*/dual(2, (self, pf) => Effect.sync(() => {\n const option = pf(self.ref.current);\n if (option._tag === \"Some\") {\n self.ref.current = option.value;\n }\n return self.ref.current;\n}));\n/**\n * Gets the current value of the Ref synchronously (unsafe version).\n *\n * **When to use**\n *\n * Use when you need immediate synchronous access and can guarantee that\n * reading the `Ref` outside of `Effect` is safe.\n *\n * **Gotchas**\n *\n * Prefer `Ref.get` for Effect-wrapped access in Effect programs.\n *\n * **Example** (Reading a ref unsafely)\n *\n * ```ts import.meta.vitest\n * import { Ref } from \"effect\"\n *\n * const counter = Ref.makeUnsafe(42)\n * Ref.getUnsafe(counter) // => 42\n * ```\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getUnsafe = self => self.ref.current;\n//# sourceMappingURL=Ref.js.map","/**\n * Helpers for turning an `Effect` program into a host application's main entry\n * point. This module is the low-level layer used by platform adapters to run a\n * main effect, observe its fiber, report unhandled failures, and translate the\n * resulting `Exit` into an application or process exit code. It provides\n * `makeRunMain`, the default teardown behavior, and error markers for custom\n * exit codes and already-reported failures. Application code usually calls the\n * platform-provided runner instead of using this module directly.\n *\n * @stability stable\n * @since 4.0.0\n */\nimport * as Cause from \"effect/Cause\";\nimport * as Context from \"effect/Context\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport { constVoid, dual } from \"effect/Function\";\n/**\n * Annotation specifying the exit code for an interruption handled by\n * {@link defaultTeardown}.\n *\n * **When to use**\n *\n * Use when a component finishes a program by interrupting its main fiber on\n * purpose, such as a stdio server shutting down after stdin closes, and that\n * shutdown should not report the `130` code reserved for external interruption.\n *\n * **Details**\n *\n * Pass the annotation through `Fiber.interruptAs`. {@link defaultTeardown}\n * reads it from the interrupt reasons of the final `Cause`.\n *\n * **Gotchas**\n *\n * The annotation is read from the `Cause`, not from the running effect's\n * services, so providing it with `Effect.provideService` has no effect.\n *\n * **Example** (Exiting with 0 after an intentional interruption)\n *\n * ```ts import.meta.vitest\n * import { Context, Effect, Fiber, Runtime } from \"effect\"\n *\n * const program = Effect.gen(function*() {\n * const main = yield* Effect.forkChild(Effect.never)\n * yield* Fiber.interruptAs(main, undefined, Context.make(Runtime.InterruptExitCode, 0))\n * return yield* Fiber.await(main)\n * })\n *\n * const exitCodes: Array<number> = []\n * Runtime.defaultTeardown(await Effect.runPromise(program), (code) => exitCodes.push(code))\n *\n * exitCodes // => [0]\n * ```\n *\n * @see {@link defaultTeardown} for how annotated and unannotated interruptions combine\n * @see {@link errorExitCode} for the equivalent marker on failures\n *\n * @stability stable\n * @category annotations\n * @since 4.1.3\n */\nexport class InterruptExitCode extends /*#__PURE__*/Context.Service()(\"effect/Runtime/InterruptExitCode\") {}\n/**\n * The default teardown function that determines exit codes from an Effect exit.\n *\n * **When to use**\n *\n * Use as the standard teardown for main programs with conventional process\n * exit codes and support for {@link errorExitCode}.\n *\n * **Details**\n *\n * This teardown follows these exit-code rules:\n *\n * - `0` for successful completion.\n * - The largest {@link InterruptExitCode} when every reason is an annotated interruption.\n * - `130` for interruption-only failures with any unannotated reason.\n * - The squashed error's {@link errorExitCode} value for other failures when\n * present.\n * - `1` for other failures.\n *\n * **Gotchas**\n *\n * Interruption codes apply only when the Cause contains nothing but\n * interruptions. A Cause that mixes interruptions with errors or defects uses\n * the squashed error path instead.\n *\n * **Example** (Referencing default teardown)\n *\n * ```ts import.meta.vitest\n * import { Exit, Runtime } from \"effect\"\n *\n * const exitCodes: Array<number> = []\n * const collectExitCode = (exit: Exit.Exit<any, any>) =>\n * Runtime.defaultTeardown(exit, (code) => exitCodes.push(code))\n *\n * collectExitCode(Exit.succeed(42))\n * collectExitCode(Exit.fail(\"error\"))\n * collectExitCode(Exit.interrupt(123))\n *\n * exitCodes // => [0, 1, 130]\n * ```\n *\n * **Example** (Distinguishing completion from external interruption)\n *\n * ```ts import.meta.vitest\n * import { Cause, Context, Exit, Runtime } from \"effect\"\n *\n * const completed = Cause.annotate(Cause.interrupt(1), Context.make(Runtime.InterruptExitCode, 0))\n * const custom = Cause.annotate(Cause.interrupt(2), Context.make(Runtime.InterruptExitCode, 7))\n * const external = Cause.interrupt(3)\n * const exitCodes: Array<number> = []\n * const collectExitCode = (cause: Cause.Cause<never>) =>\n * Runtime.defaultTeardown(Exit.failCause(cause), (code) => exitCodes.push(code))\n *\n * collectExitCode(completed)\n * collectExitCode(Cause.combine(completed, custom))\n * collectExitCode(Cause.combine(custom, completed))\n * collectExitCode(Cause.combine(completed, external))\n * collectExitCode(Cause.combine(external, completed))\n *\n * exitCodes // => [0, 7, 7, 130, 130]\n * ```\n *\n * @see {@link errorExitCode} for customizing failure exit codes\n *\n * @stability stable\n * @category running\n * @since 4.0.0\n */\nexport const defaultTeardown = (exit, onExit) => {\n if (Exit.isSuccess(exit)) return onExit(0);\n if (Cause.hasInterruptsOnly(exit.cause)) {\n let code = -Infinity;\n for (const reason of exit.cause.reasons) {\n const annotated = Context.getOrUndefined(Cause.reasonAnnotations(reason), InterruptExitCode);\n if (annotated === undefined) return onExit(130);\n code = Math.max(code, annotated);\n }\n return onExit(code);\n }\n return onExit(getErrorExitCode(Cause.squash(exit.cause)));\n};\n/**\n * Creates a platform-specific main program runner that handles Effect execution lifecycle.\n *\n * **When to use**\n *\n * Use when building a runtime adapter for a host platform.\n *\n * **Details**\n *\n * The setup function runs before user code and receives the main fiber and a\n * teardown callback to install platform-specific signal handlers, observers,\n * and exit behavior.\n *\n * Most applications should use a platform-provided runner, such as\n * `NodeRuntime.runMain`, rather than constructing one directly.\n *\n * `disableErrorReporting` disables the automatic log emitted for unreported\n * non-interruption failures. It does not change exit-code calculation or the\n * custom teardown callback.\n *\n * **Gotchas**\n *\n * The setup function is responsible for observing the fiber and eventually\n * invoking teardown. `makeRunMain` also tries to keep the host process alive\n * with a long interval while the main fiber is running; if the host blocks\n * timers, the runner still starts but cannot use that keep-alive fallback.\n *\n * **Example** (Creating platform runners)\n *\n * ```ts import.meta.vitest\n * import { Effect, Exit, Runtime } from \"effect\"\n *\n * const events: Array<string> = []\n * const completed = new Promise<readonly [Exit.Exit<unknown, unknown>, number]>((resolve) => {\n * // Create a simple runner for a hypothetical platform\n * const runMain = Runtime.makeRunMain(({ fiber, teardown }) => {\n * // Handle fiber completion\n * fiber.addObserver((exit) => {\n * teardown(exit, (code) => resolve([exit, code]))\n * })\n * })\n *\n * // Use the runner\n * const program = Effect.sync(() => {\n * events.push(\"Starting program\", \"Program completed\")\n * return \"success\"\n * })\n *\n * runMain(program, {\n * teardown: (exit, onExit) => {\n * events.push(\"Custom teardown logic\")\n * Runtime.defaultTeardown(exit, onExit)\n * }\n * })\n * })\n *\n * const result = await completed\n * result // => [Exit.succeed(\"success\"), 0]\n * events // => [\"Starting program\", \"Program completed\", \"Custom teardown logic\"]\n * ```\n *\n * @stability stable\n * @category running\n * @since 4.0.0\n */\nexport const makeRunMain = f => dual(args => Effect.isEffect(args[0]), (effect, options) => {\n const main = options?.disableErrorReporting === true ? effect : Effect.tapCause(effect, cause => {\n if (Cause.hasInterruptsOnly(cause)) return Effect.void;\n const isReported = getErrorReported(Cause.squash(cause));\n return isReported ? Effect.logError(cause) : Effect.void;\n });\n const teardown = options?.teardown ?? defaultTeardown;\n Effect.runFork(Effect.withFiber(fiber => {\n try {\n const keepAlive = globalThis.setInterval(constVoid, 2_147_483_647);\n fiber.addObserver(() => {\n clearInterval(keepAlive);\n });\n } catch {}\n f({\n fiber,\n teardown\n });\n return main;\n }));\n});\n/**\n * Allows associating an exit code with an error for determining the process\n * exit code on failure.\n *\n * **When to use**\n *\n * Use when error classes should map failures to a specific process exit code\n * when handled by {@link defaultTeardown}.\n *\n * **Details**\n *\n * Attach this marker as a readonly property on an error object. When the main\n * program fails, {@link defaultTeardown} squashes the Cause and reads the marker\n * from the resulting error value.\n *\n * **Gotchas**\n *\n * The marker is read from the squashed failure value. If a Cause contains\n * multiple failures, the selected squashed error determines the exit code.\n *\n * **Example** (Setting a process exit code)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n * readonly [Runtime.errorExitCode] = 42\n * }\n *\n * Runtime.getErrorExitCode(new MyError()) // => 42\n * ```\n *\n * @see {@link errorReported} for controlling automatic error logging\n * @see {@link defaultTeardown} for the default failure exit-code rules that read this marker\n * @see {@link getErrorExitCode} for reading the marker from unknown error values\n *\n * @stability stable\n * @category symbols\n * @since 4.0.0\n */\nexport const errorExitCode = \"~effect/Runtime/errorExitCode\";\n/**\n * Reads the runtime exit-code marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read a custom failure exit code from an unknown error value, falling\n * back to the default failure code.\n *\n * **Details**\n *\n * Returns the numeric `[Runtime.errorExitCode]` property when it is present on\n * an object. Otherwise returns `1`, the default failure exit code used by\n * `defaultTeardown`.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-number marker values all return\n * `1`.\n *\n * @see {@link errorExitCode} for the marker read by this function\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorExitCode = u => {\n if (typeof u === \"object\" && u !== null && errorExitCode in u) {\n const code = u[errorExitCode];\n if (typeof code === \"number\") {\n return code;\n }\n }\n return 1;\n};\n/**\n * Defines the runtime marker that controls default `runMain` error logging for an error.\n *\n * **When to use**\n *\n * Use when you need error classes reported by application code to avoid being\n * logged again by the default main runner.\n *\n * **Details**\n *\n * Set `[Runtime.errorReported]` to `false` on an error object to suppress the\n * runtime log because the error has already been reported. Omitted or\n * non-boolean values are treated as `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * This marker controls only automatic error logging. It does not change the\n * failure Cause or the process exit code.\n * `makeRunMain` reads the marker from `Cause.squash(cause)`, so for causes\n * with multiple failures, the squashed error determines whether default logging\n * is suppressed.\n *\n * **Example** (Suppressing error reporting)\n *\n * ```ts import.meta.vitest\n * import { Data, Runtime } from \"effect\"\n *\n * class MyError extends Data.TaggedError(\"MyError\") {\n * readonly [Runtime.errorReported] = false\n * }\n *\n * Runtime.getErrorReported(new MyError()) // => false\n * ```\n *\n * @see {@link errorExitCode} for controlling failure exit codes\n * @see {@link getErrorReported} for reading the marker from unknown error values\n *\n * @stability stable\n * @category symbols\n * @since 4.0.0\n */\nexport const errorReported = \"~effect/Runtime/errorReported\";\n/**\n * Reads the runtime error-reporting marker from an unknown error value.\n *\n * **When to use**\n *\n * Use to read whether an unknown error value should be treated as already\n * reported by the default main runner.\n *\n * **Details**\n *\n * Returns a boolean `[Runtime.errorReported]` property when it is present on an\n * object. Otherwise returns `true`, so failures are logged by default.\n *\n * **Gotchas**\n *\n * Non-object values, missing markers, and non-boolean marker values all return\n * `true`.\n *\n * @see {@link errorReported} for the marker read by this function\n *\n * @stability stable\n * @category getters\n * @since 4.0.0\n */\nexport const getErrorReported = u => {\n if (typeof u === \"object\" && u !== null && errorReported in u) {\n const isReported = u[errorReported];\n if (typeof isReported === \"boolean\") {\n return isReported;\n }\n }\n return true;\n};\n//# sourceMappingURL=Runtime.js.map","/** @internal */\nexport const version = \"4.2.0\";\n//# sourceMappingURL=version.js.map","/**\n * The `effect` package version used in telemetry headers, resources, and scopes.\n *\n * @stability unstable\n * @since 4.0.2\n */\nimport { version } from \"./internal/version.js\";\nlet currentVersion = version;\n/**\n * Returns the current version of the `effect` package.\n *\n * **Details**\n *\n * Defaults to the release version unless overridden by `setCurrentVersion`.\n *\n * @stability unstable\n * @category getters\n * @since 4.0.2\n */\nexport const getCurrentVersion = () => currentVersion;\n/**\n * Overrides the version returned by `getCurrentVersion`.\n *\n * **Gotchas**\n *\n * Applies to this copy of the module. Existing telemetry layers retain the\n * version they read when built.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.2\n */\nexport const setCurrentVersion = version => {\n currentVersion = version;\n};\n//# sourceMappingURL=Version.js.map","/**\n * Describes HTTP request and response bodies before they reach a platform\n * adapter.\n *\n * `HttpBody` is the shared body representation used by the HTTP modules. Each\n * variant stores the payload together with metadata that can be known before\n * sending it, such as `contentType` and `contentLength`. This module includes\n * body constructors for common payload shapes, support for schema-encoded JSON\n * bodies, streaming and file-backed bodies, and the error type used when body\n * construction fails.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as ByteSize from \"../ByteSize.js\";\nimport * as Data from \"../Data.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as FileSystem from \"../FileSystem.js\";\nimport { format } from \"../Formatter.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Option from \"../Option.js\";\nimport * as PlatformError from \"../PlatformError.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as SchemaParser from \"../SchemaParser.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpBody\";\n/**\n * Returns `true` if the provided value is an `HttpBody`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpBody = u => Predicate.hasProperty(u, TypeId);\nconst HttpBodyErrorTypeId = \"~effect/http/HttpBody/HttpBodyError\";\n/**\n * Error produced while constructing an HTTP body from JSON or schema-encoded input.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class HttpBodyError extends /*#__PURE__*/Data.TaggedError(\"HttpBodyError\") {\n /**\n * Marks this value as an HTTP body error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [HttpBodyErrorTypeId] = HttpBodyErrorTypeId;\n}\n/**\n * Checks whether a value is an `HttpBodyError`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpBodyError = u => Predicate.hasProperty(u, HttpBodyErrorTypeId);\nclass Proto {\n [TypeId];\n constructor() {\n this[TypeId] = TypeId;\n }\n [Inspectable.NodeInspectSymbol]() {\n return this.toJSON();\n }\n toString() {\n return format(this, {\n ignoreToString: true\n });\n }\n}\n/**\n * HTTP body variant representing the absence of request content.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Empty extends Proto {\n _tag = \"Empty\";\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Empty\"\n };\n }\n}\n/**\n * Provides the singleton empty HTTP body.\n *\n * **When to use**\n *\n * Use when you need an HTTP body value that represents no body content.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/new Empty();\n/**\n * HTTP body variant containing an arbitrary runtime body value with optional content metadata.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Raw extends Proto {\n _tag = \"Raw\";\n body;\n contentType;\n contentLength;\n constructor(body, contentType, contentLength) {\n super();\n this.body = body;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Raw\",\n body: this.body,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a raw HTTP body from an arbitrary value and optional `contentType` and `contentLength` metadata.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const raw = (body, options) => new Raw(body, options?.contentType, options?.contentLength);\n/**\n * HTTP body variant backed by a `Uint8Array`.\n *\n * **Details**\n *\n * It stores the bytes, content type, and byte length.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Uint8Array extends Proto {\n _tag = \"Uint8Array\";\n contentType;\n contentLength;\n /** Original text retained for adapters that can skip encoding. */\n text;\n _body;\n constructor(body, contentType, contentLength, text) {\n super();\n this._body = body;\n this.text = text;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n get body() {\n return this._body ??= encodeText(this.text);\n }\n toJSON() {\n const toString = this.contentType.startsWith(\"text/\") || this.contentType.endsWith(\"json\");\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Uint8Array\",\n body: toString ? new TextDecoder().decode(this.body) : `Uint8Array(${this.body.length})`,\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a byte-array HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`, and the content length is the byte array length.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const uint8Array = (body, contentType) => new Uint8Array(body, contentType ?? \"application/octet-stream\", body.length);\nconst encoder = /*#__PURE__*/new TextEncoder();\n// Buffer encodes UTF-8 faster than TextEncoder when available.\nconst buffer = globalThis.Buffer;\nconst encodeText = buffer !== undefined ? body => buffer.from(body, \"utf8\") : body => encoder.encode(body);\n/**\n * Creates a UTF-8 encoded text HTTP body.\n *\n * **Details**\n *\n * The content type defaults to `text/plain`. Text bodies are encoded lazily.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const text = (body, contentType) => {\n if (typeof body !== \"string\") {\n // Preserve untyped callers that relied on TextEncoder coercion.\n body = body === undefined ? \"\" : String(body);\n }\n if (buffer !== undefined) {\n return new Uint8Array(undefined, contentType ?? \"text/plain\", buffer.byteLength(body, \"utf8\"), body);\n }\n const bytes = encoder.encode(body);\n return new Uint8Array(bytes, contentType ?? \"text/plain\", bytes.length, body);\n};\n/**\n * Creates a JSON HTTP body using `JSON.stringify`, throwing if serialization fails.\n *\n * **Details**\n *\n * The content type defaults to `application/json`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonUnsafe = (body, contentType) => text(JSON.stringify(body), contentType ?? \"application/json\");\n/**\n * Creates a JSON HTTP body in an `Effect`.\n *\n * **Details**\n *\n * `JSON.stringify` failures are captured as `HttpBodyError` values, and the content type defaults to `application/json`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const json = (body, contentType) => Effect.try({\n try: () => text(JSON.stringify(body), contentType ?? \"application/json\"),\n catch: cause => new HttpBodyError({\n reason: {\n _tag: \"JsonError\"\n },\n cause\n })\n});\n/**\n * Creates a JSON body constructor that first encodes values with the schema's JSON codec.\n *\n * **Details**\n *\n * Schema encoding issues and JSON serialization failures are returned as `HttpBodyError` values.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const jsonSchema = (schema, options) => {\n const encode = SchemaParser.encodeUnknownEffect(Schema.toCodecJson(schema));\n return (body, contentType) => encode(body, options).pipe(Effect.mapError(issue => new HttpBodyError({\n reason: {\n _tag: \"SchemaError\",\n issue\n },\n cause: issue\n })), Effect.flatMap(body => json(body, contentType)));\n};\n/**\n * Creates an `application/x-www-form-urlencoded` HTTP body from `UrlParams`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const urlParams = (urlParams, contentType) => text(UrlParams.toString(UrlParams.fromInput(urlParams)), contentType ?? \"application/x-www-form-urlencoded\");\n/**\n * HTTP body variant backed by Web `FormData`.\n *\n * **Details**\n *\n * The content type and content length are left unset so the runtime can supply multipart boundaries.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class FormData extends Proto {\n _tag = \"FormData\";\n contentType = undefined;\n contentLength = undefined;\n formData;\n constructor(formData) {\n super();\n this.formData = formData;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"FormData\",\n formData: this.formData\n };\n }\n}\n/**\n * Wraps a Web `FormData` value as an HTTP body.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const formData = body => new FormData(body);\nconst appendFormDataValue = (formData, key, value) => {\n if (value == null) {\n return;\n }\n if (typeof value === \"object\") {\n formData.append(key, value);\n return;\n }\n formData.append(key, String(value));\n};\n/**\n * Creates a `FormData` HTTP body from a record.\n *\n * **Details**\n *\n * Array fields append each item under the same key; primitive values are stringified, `File` and `Blob` values are appended directly, and nullish values are skipped.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const formDataRecord = entries => {\n const data = new globalThis.FormData();\n for (const [key, value] of Object.entries(entries)) {\n if (Array.isArray(value)) {\n for (const item of value) {\n appendFormDataValue(data, key, item);\n }\n } else {\n appendFormDataValue(data, key, value);\n }\n }\n return formData(data);\n};\n/**\n * HTTP body variant backed by a stream of `Uint8Array` chunks.\n *\n * @stability unstable\n * @category models\n * @since 4.0.0\n */\nexport class Stream extends Proto {\n _tag = \"Stream\";\n stream;\n contentType;\n contentLength;\n constructor(stream, contentType, contentLength) {\n super();\n this.stream = stream;\n this.contentType = contentType;\n this.contentLength = contentLength;\n }\n toJSON() {\n return {\n _id: \"effect/HttpBody\",\n _tag: \"Stream\",\n contentType: this.contentType,\n contentLength: this.contentLength\n };\n }\n}\n/**\n * Creates a streaming HTTP body from a stream of byte chunks.\n *\n * **Details**\n *\n * The content type defaults to `application/octet-stream`; content length is optional.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const stream = (body, contentType, contentLength) => new Stream(body, contentType ?? \"application/octet-stream\", contentLength);\nconst fileRangeSize = (input, field, method) => {\n const size = ByteSize.fromInput(input);\n return Option.isSome(size) ? Effect.succeed(size.value) : Effect.fail(PlatformError.badArgument({\n module: \"HttpBody\",\n method,\n description: `Invalid ${field}: ${input}`\n }));\n};\nconst fileContentLength = /*#__PURE__*/Effect.fnUntraced(function* (size, method, options) {\n const offset = options?.offset === undefined ? ByteSize.zero : yield* fileRangeSize(options.offset, \"offset\", method);\n const bytesToRead = options?.bytesToRead === undefined ? undefined : yield* fileRangeSize(options.bytesToRead, \"bytesToRead\", method);\n const available = offset >= size ? BigInt(\"0\") : size - offset;\n const length = bytesToRead === undefined || bytesToRead > available ? available : bytesToRead;\n if (length > BigInt(Number.MAX_SAFE_INTEGER)) {\n return yield* Effect.fail(PlatformError.badArgument({\n module: \"HttpBody\",\n method,\n description: `Content length exceeds Number.MAX_SAFE_INTEGER: ${length}`\n }));\n }\n return Number(length);\n});\n/**\n * Creates a streaming HTTP body for a file path.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, stats the file to set the selected content length, and can fail with\n * `PlatformError`.\n *\n * Range validation and file access are deferred until the effect runs. Numeric range inputs must be\n * non-negative safe integers; bigint and byte-size strings can represent larger values. Malformed strings,\n * negative values, and non-finite, fractional, or unsafe numbers fail with `PlatformError` / `BadArgument`.\n *\n * The selected length is calculated exactly with bigint arithmetic and clamped to the bytes available after\n * `offset` (zero at or past EOF). Since `Stream.contentLength` is a number, a final length above\n * `Number.MAX_SAFE_INTEGER` fails with `BadArgument`. Larger sizes, offsets, and byte counts are valid when\n * the final clamped length is representable; the resulting Content-Length header preserves that exact length.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const file = (path, options) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.flatMap(fs.stat(path), info => Effect.map(fileContentLength(info.size, \"file\", options), contentLength => stream(fs.stream(path, options), options?.contentType, contentLength))));\n/**\n * Creates a streaming HTTP body for a file path using already-known file information.\n *\n * **Details**\n *\n * The effect requires `FileSystem`, uses the provided file size to determine the selected content length, and can\n * fail with `PlatformError`.\n *\n * Like {@link file}, this constructor validates ranges lazily and calculates the EOF-clamped length with exact\n * bigint arithmetic. Invalid range inputs and final lengths above `Number.MAX_SAFE_INTEGER` fail with\n * `PlatformError` / `BadArgument`. Larger sizes, offsets, and byte counts remain valid when the final length\n * is representable as a safe integer, preserving the exact Content-Length header.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fileFromInfo = (path, info, options) => Effect.flatMap(FileSystem.FileSystem, fs => Effect.map(fileContentLength(info.size, \"fileFromInfo\", options), contentLength => stream(fs.stream(path, options), options?.contentType, contentLength)));\n//# sourceMappingURL=HttpBody.js.map","/**\n * Defines supported HTTP method names for the unstable HTTP modules.\n *\n * Values are uppercase string literals such as `\"GET\"` and `\"POST\"`, matching\n * the method tokens used by HTTP requests and routes. This module also includes\n * helpers for checking whether a method can carry a request body and whether an\n * unknown value is one of the supported methods.\n *\n * @stability unstable\n * @since 4.0.0\n */\nexport function hasBody(method) {\n return method !== \"GET\" && method !== \"HEAD\" && method !== \"OPTIONS\" && method !== \"TRACE\";\n}\n/**\n * Provides a readonly set containing every supported `HttpMethod` literal.\n *\n * **When to use**\n *\n * Use when you need to iterate over or test membership against every supported\n * HTTP method literal.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const all = /*#__PURE__*/new Set([\"GET\", \"POST\", \"PUT\", \"DELETE\", \"PATCH\", \"HEAD\", \"OPTIONS\", \"TRACE\", \"QUERY\"]);\n/**\n * Provides tuples mapping each supported HTTP method to its short\n * request-constructor name.\n *\n * **When to use**\n *\n * Use when you need the mapping from supported HTTP method literals to their\n * short request-constructor names.\n *\n * @stability unstable\n * @category constants\n * @since 4.0.0\n */\nexport const allShort = [[\"GET\", \"get\"], [\"POST\", \"post\"], [\"PUT\", \"put\"], [\"DELETE\", \"del\"], [\"PATCH\", \"patch\"], [\"HEAD\", \"head\"], [\"OPTIONS\", \"options\"], [\"TRACE\", \"trace\"], [\"QUERY\", \"query\"]];\n/**\n * Checks whether a value is a `HttpMethod`.\n *\n * **Example** (Checking HTTP method values)\n *\n * ```ts import.meta.vitest\n * import { HttpMethod } from \"effect/http\"\n *\n * HttpMethod.isHttpMethod(\"GET\") // => true\n * HttpMethod.isHttpMethod(\"get\") // => false\n * HttpMethod.isHttpMethod(1) // => false\n * ```\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpMethod = u => all.has(u);\n//# sourceMappingURL=HttpMethod.js.map","import * as Effect from \"../../Effect.js\";\nimport { identity } from \"../../Function.js\";\nimport * as Stream from \"../../Stream.js\";\nimport * as HttpBody from \"../HttpBody.js\";\n/**\n * @internal\n */\nexport const compressionTransformWeb = format => stream => stream.pipeThrough(new CompressionStream(format));\n/**\n * @internal\n */\nexport const singleChunkStream = data => new ReadableStream({\n start(controller) {\n controller.enqueue(data);\n controller.close();\n }\n});\n/**\n * @internal\n */\nexport const compressBody = (body, algorithm, options) => {\n if (body._tag !== \"Uint8Array\" && body._tag !== \"Stream\") {\n return Effect.succeed(body);\n }\n if (body.contentLength !== undefined && body.contentLength < (options?.minSize ?? 1024)) {\n return Effect.succeed(body);\n }\n if (body._tag === \"Uint8Array\") {\n return Effect.map(Effect.promise(() => new globalThis.Response(compressionTransformWeb(algorithm)(singleChunkStream(body.body))).arrayBuffer()), buffer => HttpBody.uint8Array(new Uint8Array(buffer), body.contentType));\n }\n return Effect.succeed(HttpBody.stream(Stream.fromReadableStream({\n evaluate: () => compressionTransformWeb(algorithm)(Stream.toReadableStream(body.stream)),\n onError: identity\n }), body.contentType));\n};\n//# sourceMappingURL=compressionBody.js.map","import * as Headers from \"../Headers.js\";\n/**\n * @internal\n */\nexport const updateHeaders = (headers, body) => {\n if (body._tag === \"Empty\" || body._tag === \"FormData\") {\n return Headers.remove(Headers.remove(headers, \"content-type\"), \"content-length\");\n }\n headers = body.contentType === undefined ? Headers.remove(headers, \"content-type\") : Headers.set(headers, \"content-type\", body.contentType);\n return updateContentLength(headers, body);\n};\n/**\n * @internal\n */\nexport const updateContentLength = (headers, body) => {\n const contentLength = body._tag === \"Empty\" || body._tag === \"FormData\" ? undefined : body.contentLength;\n return contentLength === undefined ? Headers.remove(headers, \"content-length\") : Headers.set(headers, \"content-length\", contentLength.toString());\n};\n/**\n * @internal\n */\nexport const parseContentLength = contentLength => {\n if (contentLength === null || contentLength === undefined || !/^\\d+$/.test(contentLength)) {\n return undefined;\n }\n const parsed = Number(contentLength);\n return Number.isSafeInteger(parsed) ? parsed : undefined;\n};\n//# sourceMappingURL=httpBody.js.map","/**\n * Parses and edits platform `URL` values.\n *\n * The HTTP modules use the standard `URL` object as their URL representation.\n * This module adds safe parsing and helpers that return updated copies when\n * changing credentials, host, path, protocol, query, or hash parts. Query\n * strings can also be read or updated through `UrlParams`.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Cause from \"../Cause.js\";\nimport * as Data from \"../Data.js\";\nimport { dual } from \"../Function.js\";\nimport * as Redacted from \"../Redacted.js\";\nimport * as Result from \"../Result.js\";\nimport * as internal from \"./internal/urlParams.js\";\nimport * as UrlParams from \"./UrlParams.js\";\n/**\n * Error returned when constructing a `URL` fails.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class UrlError extends /*#__PURE__*/Data.TaggedError(\"UrlError\") {}\n/**\n * Creates a `URL` safely by appending `UrlParams` and an optional hash to a URL string.\n *\n * **Details**\n *\n * Returns a `Result` that fails with `UrlError` if the URL cannot be constructed.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = (url, params, hash) => Result.try({\n try: () => {\n const urlInstance = new URL(url, baseUrl());\n for (let i = 0; i < params.params.length; i++) {\n const [key, value] = params.params[i];\n if (value !== undefined) {\n urlInstance.searchParams.append(key, internal.unwrap(value));\n }\n }\n if (hash !== undefined) {\n urlInstance.hash = hash;\n }\n return urlInstance;\n },\n catch: cause => new UrlError({\n cause\n })\n});\nconst baseUrl = () => {\n if (\"location\" in globalThis && globalThis.location !== undefined && globalThis.location.origin !== undefined && globalThis.location.pathname !== undefined) {\n const base = location.origin + location.pathname;\n try {\n return new URL(base).href;\n } catch {\n return undefined;\n }\n }\n return undefined;\n};\n/**\n * Parses a URL string safely into a `URL` object, returning a `Result` type for\n * error handling.\n *\n * **Details**\n *\n * This function converts a string into a `URL` object, enabling safe URL\n * parsing with built-in error handling. If the string is invalid or fails to\n * parse, this function does not throw an error; instead, it wraps the error in\n * a `IllegalArgumentError` and returns it as the `Failure` value of an\n * `Result`. The `Success` value contains the successfully parsed `URL`.\n *\n * An optional `base` parameter can be provided to resolve relative URLs. If\n * specified, the function interprets the input `url` as relative to this\n * `base`. This is especially useful when dealing with URLs that might not be\n * fully qualified.\n *\n * **Example** (Parsing absolute and relative URLs)\n *\n * ```ts import.meta.vitest\n * import { Result } from \"effect\"\n * import { Url } from \"effect/http\"\n *\n * // Parse an absolute URL\n * //\n * // ┌─── Result<URL, IllegalArgumentError>\n * // ▼\n * const parsed = Url.fromString(\"https://example.com/path\")\n *\n * Result.map(parsed, (url) => url.toString()) // => Result.succeed(\"https://example.com/path\")\n *\n * // Parse a relative URL with a base\n * const relativeParsed = Url.fromString(\"/relative-path\", \"https://example.com\")\n *\n * Result.map(relativeParsed, (url) => url.toString()) // => Result.succeed(\"https://example.com/relative-path\")\n * ```\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromString = (url, base) => Result.try({\n try: () => new URL(url, base),\n catch: () => new Cause.IllegalArgumentError(`Invalid URL: \"${url}\"${base !== undefined ? ` with base \"${base}\"` : \"\"}`)\n});\n/**\n * Updates a cloned `URL` with a callback, allowing multiple changes at once.\n *\n * **Example** (Mutating URL credentials)\n *\n * ```ts import.meta.vitest\n * import { Url } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com\")\n *\n * const mutatedUrl = Url.mutate(myUrl, (url) => {\n * url.username = \"user\"\n * url.password = \"pass\"\n * })\n *\n * mutatedUrl.toString() // => \"https://user:pass@example.com/\"\n * ```\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const mutate = /*#__PURE__*/dual(2, (self, f) => {\n const copy = new URL(self);\n f(copy);\n return copy;\n});\n/**\n * @internal\n */\nconst immutableURLSetter = property => dual(2, (url, value) => mutate(url, url => {\n url[property] = value;\n}));\n/**\n * Updates the hash fragment of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHash = /*#__PURE__*/immutableURLSetter(\"hash\");\n/**\n * Updates the host (domain and port) of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHost = /*#__PURE__*/immutableURLSetter(\"host\");\n/**\n * Updates the domain of the URL without modifying the port.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHostname = /*#__PURE__*/immutableURLSetter(\"hostname\");\n/**\n * Replaces the entire URL string.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setHref = /*#__PURE__*/immutableURLSetter(\"href\");\n/**\n * Updates the password used for authentication.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPassword = /*#__PURE__*/dual(2, (url, password) => mutate(url, url => {\n url.password = typeof password === \"string\" ? password : Redacted.value(password);\n}));\n/**\n * Updates the path of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPathname = /*#__PURE__*/immutableURLSetter(\"pathname\");\n/**\n * Updates the port of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setPort = /*#__PURE__*/immutableURLSetter(\"port\");\n/**\n * Updates the protocol (e.g., `http`, `https`).\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setProtocol = /*#__PURE__*/immutableURLSetter(\"protocol\");\n/**\n * Updates the query string of the URL.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setSearch = /*#__PURE__*/immutableURLSetter(\"search\");\n/**\n * Updates the username used for authentication.\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setUsername = /*#__PURE__*/immutableURLSetter(\"username\");\n/**\n * Updates the query parameters of a URL.\n *\n * **Details**\n *\n * This function allows you to set or replace the query parameters of a `URL`\n * object using the provided `UrlParams`. It creates a new `URL` object with the\n * updated parameters, leaving the original object unchanged.\n *\n * **Example** (Replacing query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * // Write parameters\n * const updatedUrl = Url.setUrlParams(\n * myUrl,\n * UrlParams.fromInput([[\"key\", \"value\"]])\n * )\n *\n * updatedUrl.toString() // => \"https://example.com/?key=value\"\n * ```\n *\n * @stability unstable\n * @category setters\n * @since 4.0.0\n */\nexport const setUrlParams = /*#__PURE__*/dual(2, (url, urlParams) => mutate(url, url => {\n url.search = UrlParams.toString(UrlParams.fromInput(urlParams));\n}));\n/**\n * Retrieves the query parameters from a URL.\n *\n * **Details**\n *\n * This function extracts the query parameters from a `URL` object and returns\n * them as `UrlParams`. The resulting structure can be easily manipulated or\n * inspected.\n *\n * **Example** (Reading query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * // Read parameters\n * const params = Url.urlParams(myUrl)\n *\n * UrlParams.toString(params) // => \"foo=bar\"\n * ```\n *\n * @stability unstable\n * @category getters\n * @since 4.0.0\n */\nexport const urlParams = url => UrlParams.fromInput(url.searchParams);\n/**\n * Reads the query parameters of a URL, modifies them, and updates the URL.\n *\n * **Details**\n *\n * This function provides a functional way to interact with query parameters by\n * reading the current parameters, applying a transformation function, and then\n * writing the updated parameters back to the URL. It returns a new `URL` object\n * with the modified parameters, ensuring immutability.\n *\n * **Example** (Modifying query parameters)\n *\n * ```ts import.meta.vitest\n * import { Url, UrlParams } from \"effect/http\"\n *\n * const myUrl = new URL(\"https://example.com?foo=bar\")\n *\n * const changedUrl = Url.modifyUrlParams(myUrl, UrlParams.append(\"key\", \"value\"))\n *\n * changedUrl.toString() // => \"https://example.com/?foo=bar&key=value\"\n * ```\n *\n * @stability unstable\n * @category transforming\n * @since 4.0.0\n */\nexport const modifyUrlParams = /*#__PURE__*/dual(2, (url, f) => mutate(url, url => {\n const params = f(UrlParams.fromInput(url.searchParams));\n url.search = UrlParams.toString(params);\n}));\n//# sourceMappingURL=Url.js.map","import * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Base64 from \"../encoding/Base64.js\";\nimport { dual } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport { stringOrRedacted } from \"../internal/redacted.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { redact } from \"../Redactable.js\";\nimport * as Result from \"../Result.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport { hasBody } from \"./HttpMethod.js\";\nimport * as compression from \"./internal/compressionBody.js\";\nimport * as bodyInternal from \"./internal/httpBody.js\";\nimport * as Url from \"./Url.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpClientRequest\";\n/**\n * Returns `true` when a value is an `HttpClientRequest`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpClientRequest = u => hasProperty(u, TypeId);\nconst Proto = {\n [TypeId]: TypeId,\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"HttpClientRequest\",\n method: this.method,\n url: UrlParams.redactUrl(this.url),\n urlParams: this.urlParams,\n hash: this.hash,\n headers: redact(this.headers),\n body: this.body.toJSON()\n };\n },\n pipe() {\n return pipeArguments(this, arguments);\n }\n};\n/**\n * Constructs an `HttpClientRequest` from fully normalized request components.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport function makeWith(method, url, urlParams, hash, headers, body) {\n const self = Object.create(Proto);\n self.method = method;\n self.url = url;\n self.urlParams = urlParams;\n self.hash = hash;\n self.headers = headers;\n self.body = body;\n return self;\n}\n/**\n * An empty `GET` request with no URL, query parameters, hash, headers, or body.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const empty = /*#__PURE__*/makeWith(\"GET\", \"\", UrlParams.empty, /*#__PURE__*/Option.none(), Headers.empty, HttpBody.empty);\n/**\n * Creates a request constructor for the specified HTTP method.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = method => (url, options) => modify(empty, {\n method,\n url,\n ...(options ?? undefined)\n});\n/**\n * Creates a `GET` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/make(\"GET\");\n/**\n * Creates a `QUERY` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const query = /*#__PURE__*/make(\"QUERY\");\n/**\n * Creates a `POST` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const post = /*#__PURE__*/make(\"POST\");\n/**\n * Creates a `PATCH` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const patch = /*#__PURE__*/make(\"PATCH\");\n/**\n * Creates a `PUT` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const put = /*#__PURE__*/make(\"PUT\");\nconst del = /*#__PURE__*/make(\"DELETE\");\n/**\n * @stability unstable\n */\nexport {\n/**\n * Creates a `DELETE` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\ndel as delete };\n/**\n * Creates a `HEAD` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const head = /*#__PURE__*/make(\"HEAD\");\n/**\n * Creates an `OPTIONS` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const options = /*#__PURE__*/make(\"OPTIONS\");\n/**\n * Creates a `TRACE` request for the specified URL.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const trace = /*#__PURE__*/make(\"TRACE\");\n/**\n * Applies request options to an `HttpClientRequest`, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const modify = /*#__PURE__*/dual(2, (self, options) => {\n let result = self;\n if (options.method) {\n result = setMethod(result, options.method);\n }\n if (options.url) {\n result = setUrl(result, options.url);\n }\n if (options.headers) {\n result = setHeaders(result, options.headers);\n }\n if (options.urlParams) {\n result = setUrlParams(result, options.urlParams);\n }\n if (options.hash) {\n result = setHash(result, options.hash);\n }\n if (options.body) {\n result = setBody(result, options.body);\n }\n if (options.accept) {\n result = accept(result, options.accept);\n }\n if (options.acceptJson) {\n result = acceptJson(result);\n }\n return result;\n});\n/**\n * Sets the HTTP method on a request, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setMethod = /*#__PURE__*/dual(2, (self, method) => makeWith(method, self.url, self.urlParams, self.hash, self.headers, self.body));\n/**\n * Sets a single request header, replacing any existing value for that header.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeader = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(self.headers, key, value), self.body));\n/**\n * Adds a value to a request header, keeping any existing value.\n *\n * **Details**\n *\n * An existing value is joined with the new one by `\", \"`, and an empty value\n * leaves the request unchanged.\n *\n * @see {@link setHeader} to replace a header value\n *\n * @stability unstable\n * @category combinators\n * @since 4.1.6\n */\nexport const appendHeader = /*#__PURE__*/dual(3, (self, key, value) => value === \"\" ? self : updateHeaders(self, Headers.append(key, value)));\n/**\n * Sets multiple request headers from an input collection, replacing existing values with matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHeaders = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.setAll(self.headers, input), self.body));\n/**\n * Transforms the request headers with the provided function, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const updateHeaders = /*#__PURE__*/dual(2, (self, f) => makeWith(self.method, self.url, self.urlParams, self.hash, f(self.headers), self.body));\n/**\n * Removes a single request header by name, returning a new request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const removeHeader = /*#__PURE__*/dual(2, (self, key) => updateHeaders(self, Headers.remove(key)));\n/**\n * Sets the `Authorization` header using HTTP Basic authentication credentials,\n * encoded as UTF-8 before base64 encoding.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const basicAuth = /*#__PURE__*/dual(3, (self, username, password) => setHeader(self, \"Authorization\", `Basic ${Base64.encode(`${stringOrRedacted(username)}:${stringOrRedacted(password)}`)}`));\n/**\n * Sets the `Authorization` header using a bearer token.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bearerToken = /*#__PURE__*/dual(2, (self, token) => setHeader(self, \"Authorization\", `Bearer ${stringOrRedacted(token)}`));\n/**\n * Sets the `Accept` header to the specified media type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const accept = /*#__PURE__*/dual(2, (self, mediaType) => setHeader(self, \"Accept\", mediaType));\n/**\n * Sets the `Accept` header to `application/json`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const acceptJson = /*#__PURE__*/accept(\"application/json\");\n/**\n * Asks the server to switch the connection to another protocol by setting the\n * `Connection: Upgrade` and `Upgrade` headers.\n *\n * **When to use**\n *\n * Use to switch an HTTP/1.1 connection to a raw byte stream, such as Docker's\n * `Upgrade: tcp` for container attach. For WebSocket, use `Socket.makeWebSocket`.\n *\n * **Details**\n *\n * The request is otherwise ordinary, so client transforms such as base URLs,\n * authentication, and tracing apply to it. When the server answers `101\n * Switching Protocols`, `HttpClientResponse.upgrade` hands over the\n * connection as a `Socket`. Any other response is read as usual.\n *\n * **Example** (Attaching to a Docker container)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpClient, HttpClientRequest } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = yield* HttpClient.HttpClient\n * const response = yield* client.execute(\n * HttpClientRequest.post(\"/containers/abc/attach?stream=1&stdout=1\").pipe(\n * HttpClientRequest.upgrade(\"tcp\")\n * )\n * )\n * const socket = yield* response.upgrade\n * const reader = yield* socket.reader\n * return yield* reader.pull\n * })\n * ```\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.6\n */\nexport const upgrade = /*#__PURE__*/dual(2, (self, protocol) => makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(Headers.set(self.headers, \"connection\", \"Upgrade\"), \"upgrade\", protocol), self.body));\n/**\n * Sets the request URL. When given a `URL`, its search parameters and hash are extracted into the request's structured fields.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrl = /*#__PURE__*/dual(2, (self, url) => {\n if (typeof url === \"string\") {\n return makeWith(self.method, url, self.urlParams, self.hash, self.headers, self.body);\n }\n const clone = new URL(url.toString());\n const urlParams = UrlParams.fromInput(clone.searchParams);\n const hash = Option.fromNullishOr(clone.hash === \"\" ? undefined : clone.hash.slice(1));\n clone.search = \"\";\n clone.hash = \"\";\n return makeWith(self.method, clone.toString(), urlParams, hash, self.headers, self.body);\n});\n/**\n * Prepends a URL segment to the request URL, inserting or trimming one slash as needed.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const prependUrl = /*#__PURE__*/dual(2, (self, path) => {\n if (path === \"\") return self;\n return makeWith(self.method, joinSegments(path, self.url), self.urlParams, self.hash, self.headers, self.body);\n});\n/**\n * Appends a URL segment to the request URL, inserting or trimming one slash as needed.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrl = /*#__PURE__*/dual(2, (self, path) => {\n if (path === \"\") return self;\n return makeWith(self.method, joinSegments(self.url, path), self.urlParams, self.hash, self.headers, self.body);\n});\nconst joinSegments = (first, second) => {\n const endsWithSlash = first.endsWith(\"/\");\n const startsWithSlash = second.startsWith(\"/\");\n const needsTrim = endsWithSlash && startsWithSlash;\n const needsSlash = !endsWithSlash && !startsWithSlash;\n return needsTrim ? first + second.slice(1) : needsSlash ? first + \"/\" + second : first + second;\n};\n/**\n * Updates the request URL by applying a function to the current URL string.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const updateUrl = /*#__PURE__*/dual(2, (self, f) => makeWith(self.method, f(self.url), self.urlParams, self.hash, self.headers, self.body));\n/**\n * Sets one query parameter, replacing existing values for that parameter name.\n *\n * **Details**\n *\n * A `Redacted` value is sent unwrapped and stays redacted in inspection, errors and spans.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrlParam = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, UrlParams.set(self.urlParams, key, value), self.hash, self.headers, self.body));\n/**\n * Sets query parameters from an input collection, replacing existing values for matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setUrlParams = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, UrlParams.setAll(self.urlParams, input), self.hash, self.headers, self.body));\n/**\n * Appends one query parameter value without removing existing values for the same name.\n *\n * **Details**\n *\n * A `Redacted` value is sent unwrapped and stays redacted in inspection, errors and spans.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrlParam = /*#__PURE__*/dual(3, (self, key, value) => makeWith(self.method, self.url, UrlParams.append(self.urlParams, key, value), self.hash, self.headers, self.body));\n/**\n * Appends query parameters from an input collection without removing existing values for matching names.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const appendUrlParams = /*#__PURE__*/dual(2, (self, input) => makeWith(self.method, self.url, UrlParams.appendAll(self.urlParams, input), self.hash, self.headers, self.body));\n/**\n * Sets the URL fragment on a request without the leading `#`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setHash = /*#__PURE__*/dual(2, (self, hash) => makeWith(self.method, self.url, self.urlParams, Option.some(hash), self.headers, self.body));\n/**\n * Removes the URL fragment from a request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const removeHash = self => makeWith(self.method, self.url, self.urlParams, Option.none(), self.headers, self.body);\n/**\n * Sets the request body and updates `Content-Type` and `Content-Length` headers from the body metadata when available.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const setBody = /*#__PURE__*/dual(2, (self, body) => {\n return makeWith(self.method, self.url, self.urlParams, self.hash, bodyInternal.updateHeaders(self.headers, body), body);\n});\n/**\n * Compresses a request body using Web `CompressionStream` and sets `Content-Encoding`.\n *\n * **Details**\n *\n * Byte-array bodies (including text, JSON, and URL-encoded bodies) are compressed\n * into a new `Uint8Array` body, preserving the content type and updating\n * `Content-Length`. The compressed body does not retain the original lazy text.\n * Stream bodies are compressed lazily and have their content length removed.\n * They still require a client runtime that supports streaming request bodies\n * (stable Safari and Firefox do not; see `FetchHttpClient.StreamBodyFallback`).\n *\n * Returns the original request unchanged for empty, FormData, and raw bodies,\n * bodies with a known length below `options.minSize`, or requests with any\n * existing `Content-Encoding` header, including `identity`. Unknown-length\n * streams are always compressed. The default minimum is 1024 bytes because\n * gzip can make very small bodies larger.\n *\n * Requires `CompressionStream` (available in browsers, Node 18+, Bun, and Deno).\n * There is no typed error channel: byte compression failures are defects;\n * stream failures surface when the body is sent.\n *\n * To compress every request, use\n * `HttpClient.mapRequestEffect(HttpClientRequest.compressBody(\"gzip\"))`.\n * `HttpClient.retryTransient` re-runs preprocessing, so this recompresses on\n * every retry. For large bodies, compress once before calling `client.execute`.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const compressBody = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, algorithm, options) => {\n if (self.headers[\"content-encoding\"] !== undefined) {\n return Effect.succeed(self);\n }\n return Effect.map(compression.compressBody(self.body, algorithm, options), body => body === self.body ? self : makeWith(self.method, self.url, self.urlParams, self.hash, Headers.set(bodyInternal.updateContentLength(self.headers, body), \"content-encoding\", algorithm), body));\n});\n/**\n * Sets a `Uint8Array` request body with an optional content type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyUint8Array = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, contentType) => setBody(self, HttpBody.uint8Array(body, contentType)));\n/**\n * Sets a text request body with an optional content type.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyText = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, contentType) => setBody(self, HttpBody.text(body, contentType)));\n/**\n * Encodes a value as a JSON request body and sets it on the request, failing with `HttpBodyError` if encoding fails.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyJson = /*#__PURE__*/dual(2, (self, body) => Effect.map(HttpBody.json(body), body => setBody(self, body)));\n/**\n * Sets a JSON request body using unsafe JSON encoding.\n *\n * **When to use**\n *\n * Use when the request body is known to be JSON-serializable and a synchronous\n * `HttpClientRequest` result is needed.\n *\n * **Gotchas**\n *\n * JSON encoding may throw instead of failing in the Effect error channel.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyJsonUnsafe = /*#__PURE__*/dual(2, (self, body) => setBody(self, HttpBody.jsonUnsafe(body)));\n/**\n * Creates a schema-based JSON body encoder that sets the encoded value on a request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const encode = HttpBody.jsonSchema(schema, options);\n return dual(2, (self, body) => Effect.map(encode(body), body => setBody(self, body)));\n};\n/**\n * Sets an `application/x-www-form-urlencoded` request body from URL parameter input.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyUrlParams = /*#__PURE__*/dual(2, (self, input) => setBody(self, HttpBody.urlParams(UrlParams.fromInput(input))));\n/**\n * Sets a `FormData` request body.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFormData = /*#__PURE__*/dual(2, (self, body) => setBody(self, HttpBody.formData(body)));\n/**\n * Creates a `FormData` request body from record-style entries and sets it on the request.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFormDataRecord = /*#__PURE__*/dual(2, (self, entries) => setBody(self, HttpBody.formDataRecord(entries)));\n/**\n * Sets a streaming `Uint8Array` request body with optional content type and content length metadata.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyStream = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, body, options) => setBody(self, HttpBody.stream(body, options?.contentType, options?.contentLength)));\n/**\n * Creates a file-backed request body from a filesystem path and sets it on the request.\n *\n * **Details**\n *\n * Uses {@link HttpBody.file} to validate ranges lazily and calculate the EOF-clamped content length with exact\n * bigint arithmetic. Invalid range inputs or a final length above `Number.MAX_SAFE_INTEGER` fail with\n * `PlatformError` / `BadArgument`. Larger sizes, offsets, and byte counts are valid when the final length is\n * representable as a safe integer. The request's Content-Length header contains that exact length.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport const bodyFile = /*#__PURE__*/dual(args => isHttpClientRequest(args[0]), (self, path, options) => Effect.map(HttpBody.file(path, options), body => setBody(self, body)));\n/**\n * Builds a `URL` from the request URL, query parameters, and hash, returning `Option.none()` if the URL is invalid.\n *\n * @stability unstable\n * @category combinators\n * @since 4.0.0\n */\nexport function toUrl(self) {\n const r = Url.make(self.url, self.urlParams, Option.getOrUndefined(self.hash));\n if (Result.isSuccess(r)) {\n return Option.some(r.success);\n }\n return Option.none();\n}\n/**\n * Converts a Web `Request` into an `HttpClientRequest`, preserving method, URL, headers, and supported request bodies.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const fromWeb = request => {\n const method = request.method.toUpperCase();\n return modify(makeWith(method, \"\", UrlParams.empty, Option.none(), Headers.empty, HttpBody.empty), {\n url: new URL(request.url),\n headers: request.headers,\n body: fromWebBody(request, method)\n });\n};\nconst fromWebBody = (request, method) => {\n if (!hasBody(method) || request.body === null) {\n return HttpBody.empty;\n }\n return HttpBody.raw(request.body, {\n contentType: request.headers.get(\"content-type\") ?? undefined,\n contentLength: bodyInternal.parseContentLength(request.headers.get(\"content-length\"))\n });\n};\n/**\n * Converts an `HttpClientRequest` safely to a Web `Request` as a `Result`, failing when the request URL is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWebResult = (self, options) => {\n const url = Url.make(self.url, self.urlParams, Option.getOrUndefined(self.hash));\n if (Result.isFailure(url)) {\n return Result.fail(url.failure);\n }\n const requestInit = {\n method: self.method,\n headers: self.headers\n };\n if (options?.signal) {\n requestInit.signal = options.signal;\n }\n if (hasBody(self.method)) {\n switch (self.body._tag) {\n case \"Empty\":\n {\n break;\n }\n case \"Raw\":\n {\n requestInit.body = self.body.body;\n if (isReadableStream(self.body.body)) {\n ;\n requestInit.duplex = \"half\";\n }\n break;\n }\n case \"Uint8Array\":\n {\n requestInit.body = self.body.body;\n break;\n }\n case \"FormData\":\n {\n requestInit.body = self.body.formData;\n break;\n }\n case \"Stream\":\n {\n requestInit.body = Stream.toReadableStreamWith(self.body.stream, options?.context ?? Context.empty());\n requestInit.duplex = \"half\";\n break;\n }\n }\n }\n return Result.try({\n try: () => new Request(url.success, requestInit),\n catch: cause => new Url.UrlError({\n cause\n })\n });\n};\nconst isReadableStream = u => typeof ReadableStream !== \"undefined\" && u instanceof ReadableStream;\n/**\n * Converts an `HttpClientRequest` to a Web `Request`, failing with `UrlError` when the request URL is invalid.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = (self, options) => Effect.contextWith(context => Effect.fromResult(toWebResult(self, {\n context: context,\n signal: options?.signal\n})));\n//# sourceMappingURL=HttpClientRequest.js.map","import * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport { hasProperty } from \"../Predicate.js\";\nimport { redact } from \"../Redactable.js\";\nimport * as Schema from \"../Schema.js\";\n/**\n * Type identifier for `HttpIncomingMessage` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpIncomingMessage\";\n/**\n * Returns `true` when a value is an `HttpIncomingMessage`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpIncomingMessage = u => hasProperty(u, TypeId);\n/**\n * Creates a decoder that reads an incoming message's JSON body and decodes it with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema));\n const decodeJson = options?.reviver === undefined ? undefined : Schema.decodeEffect(Schema.fromJsonString(Schema.toCodecJson(schema), options));\n return self => decodeJson === undefined ? Effect.flatMap(self.json, u => decode(u, options)) : Effect.flatMap(self.text, body => body === \"\" ? Effect.flatMap(self.json, u => decode(u, options)) : decodeJson(body, options));\n};\n/**\n * Creates a decoder that reads an incoming message's URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaBodyUrlParams = (schema, options) => {\n const decode = Schema.RecordFromUrlParams.pipe(Schema.decodeTo(schema), Schema.decodeEffect);\n return self => Effect.flatMap(self.urlParamsBody, u => decode(u, options));\n};\n/**\n * Creates a decoder that validates and decodes an incoming message's headers with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaHeaders = (schema, options) => {\n const decode = Schema.decodeUnknownEffect(schema);\n return self => decode(self.headers, options);\n};\n/**\n * Context reference for the optional maximum size allowed when reading an incoming message body.\n *\n * @stability unstable\n * @category references\n * @since 4.0.0\n */\nexport const MaxBodySize = /*#__PURE__*/Context.Reference(\"effect/http/HttpIncomingMessage/MaxBodySize\", {\n defaultValue: () => undefined\n});\n/**\n * Builds an inspectable object for an incoming message and redacts headers.\n * The body is left unread.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const inspect = (self, that) => {\n return {\n ...that,\n headers: redact(self.headers),\n remoteAddress: self.remoteAddress\n };\n};\n//# sourceMappingURL=HttpIncomingMessage.js.map","/**\n * Returns the original Web `Response` of a fetch-backed client response.\n * Wrappers forward it to the response they wrap.\n *\n * @internal\n */\nexport const WebSourceSymbol = \"~effect/http/HttpClientResponse/WebSource\";\n/**\n * @internal\n */\nexport const getWebSource = self => self[WebSourceSymbol]?.();\n//# sourceMappingURL=webResponse.js.map","/**\n * Represents responses returned by the Effect HTTP client.\n *\n * An `HttpClientResponse` keeps the original request together with the response\n * status, headers, cookies, and body accessors from the shared incoming-message\n * model. This module includes constructors, schema-based decoders, helpers for\n * streaming response bodies, and utilities for matching or filtering by HTTP\n * status.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Effect from \"../Effect.js\";\nimport { dual } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as Error from \"./HttpClientError.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as internalUrlParams from \"./internal/urlParams.js\";\nimport { getWebSource, WebSourceSymbol } from \"./internal/webResponse.js\";\nimport * as UrlParams from \"./UrlParams.js\";\n/**\n * @stability unstable\n */\nexport {\n/**\n * Creates a decoder that reads a response JSON body and decodes it with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyJson,\n/**\n * Creates a decoder that reads response URL-encoded body parameters and decodes them with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaBodyUrlParams,\n/**\n * Creates a decoder that validates and decodes response headers with the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nschemaHeaders } from \"./HttpIncomingMessage.js\";\n/**\n * Type identifier for `HttpClientResponse` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const TypeId = \"~effect/http/HttpClientResponse\";\n/**\n * Wraps a Web `Response` and its original `HttpClientRequest` as an `HttpClientResponse`.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromWeb = (request, source) => new WebHttpClientResponse(request, source);\n/**\n * Returns the original Web `Response` of a fetch-backed `HttpClientResponse`.\n *\n * **When to use**\n *\n * Use to hand a response body to a Web API without copying it, such as\n * writing a fetched file to Cloudflare R2. The original body keeps runtime\n * capabilities, such as workerd's known length, that a stream converted from\n * `stream` does not.\n *\n * **Details**\n *\n * Returns `Some` for responses created with `fromWeb`, which includes every\n * response from `FetchHttpClient`, and `None` for other backends.\n *\n * Calling `toWeb` hands the body over: the response is no longer aborted when\n * the `HttpClientResponse` is garbage collected, so read or cancel the body\n * through the returned `Response`.\n *\n * **Gotchas**\n *\n * The body can be read once. After converting, read it from the returned\n * `Response`, not from the `HttpClientResponse`.\n *\n * After the hand-off, Effect aborts the request only when the scope of\n * `HttpClient.withScope` closes. When the request streams its body, finishing\n * or cancelling the returned body does not stop the upload; execute the\n * request with `HttpClient.withScope` and close the scope to stop it.\n *\n * @stability unstable\n * @category converting\n * @since 4.0.0\n */\nexport const toWeb = self => Option.fromUndefinedOr(getWebSource(self));\n/**\n * Creates a decoder for a response's status, headers, and JSON body using the supplied schema.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaJson = (schema, options) => {\n const decode = Schema.decodeEffect(Schema.toCodecJson(schema), options);\n const decodeBody = HttpIncomingMessage.schemaBodyJson(Schema.Unknown, options);\n return self => Effect.flatMap(decodeBody(self), body => decode({\n status: self.status,\n headers: self.headers,\n body: body\n }));\n};\n/**\n * Creates a decoder for a response's status and headers without reading a response body.\n *\n * @stability unstable\n * @category schemas\n * @since 4.0.0\n */\nexport const schemaNoBody = (schema, options) => {\n const decode = Schema.decodeEffect(schema, options);\n return self => decode({\n status: self.status,\n headers: self.headers\n });\n};\n/**\n * Converts an effect producing an `HttpClientResponse` into a stream of response body bytes.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const stream = effect => Stream.unwrap(Effect.map(effect, self => self.stream));\n/**\n * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`.\n *\n * @stability unstable\n * @category pattern matching\n * @since 4.0.0\n */\nexport const matchStatus = /*#__PURE__*/dual(2, (self, cases) => {\n const status = self.status;\n if (cases[status]) {\n return cases[status](self);\n } else if (status >= 200 && status < 300 && cases[\"2xx\"]) {\n return cases[\"2xx\"](self);\n } else if (status >= 300 && status < 400 && cases[\"3xx\"]) {\n return cases[\"3xx\"](self);\n } else if (status >= 400 && status < 500 && cases[\"4xx\"]) {\n return cases[\"4xx\"](self);\n } else if (status >= 500 && status < 600 && cases[\"5xx\"]) {\n return cases[\"5xx\"](self);\n }\n return cases.orElse(self);\n});\n/**\n * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatus = /*#__PURE__*/dual(2, (self, f) => Effect.suspend(() => f(self.status) ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"invalid status code\"\n })\n}))));\n/**\n * Succeeds with the response only when its status is in the 2xx range, otherwise fails with `HttpClientError`.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatusOk = self => self.status >= 200 && self.status < 300 ? Effect.succeed(self) : Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n response: self,\n request: self.request,\n description: \"non 2xx status code\"\n })\n}));\n/**\n * Returns the links of the response's `Link` header with absolute targets.\n *\n * **Details**\n *\n * Each target is resolved against the response URL, which is the final URL\n * after redirects, so `target` holds an absolute href. Links whose target does\n * not resolve are dropped. A response without a `Link` header gives `[]`.\n *\n * **Gotchas**\n *\n * Links with an `anchor` parameter are dropped, because they describe a\n * resource other than this response (RFC 8288 section 3.2). Parse the raw header\n * with `Headers.parseLink` to read them.\n *\n * @see {@link link} to look up a single link by relation type\n *\n * @stability unstable\n * @category accessors\n * @since 4.1.6\n */\nexport const links = self => {\n const header = self.headers.link;\n if (header === undefined) return [];\n const base = self.url || undefined;\n const out = [];\n for (const link of Headers.parseLink(header)) {\n if (Object.hasOwn(link.params, \"anchor\")) continue;\n const url = resolveUrl(link.target, base);\n if (url !== undefined) out.push({\n ...link,\n target: url.href\n });\n }\n return out;\n};\nconst resolveUrl = (target, base) => {\n try {\n return new URL(target, base);\n } catch {\n return undefined;\n }\n};\n/**\n * Returns the URL of the first link in the response's `Link` header with the\n * given relation type.\n *\n * **When to use**\n *\n * Use to follow pagination links such as `next` with `Stream.paginate`.\n *\n * **Details**\n *\n * The relation type is compared case-insensitively, and the URL is resolved\n * against the response URL. Returns `Option.none()` when no link matches.\n * Links are read as by {@link links}, so links with an `anchor` parameter\n * never match.\n *\n * **Example** (Reading the next page link)\n *\n * ```ts import.meta.vitest\n * import { Option } from \"effect\"\n * import { HttpClientRequest, HttpClientResponse } from \"effect/http\"\n *\n * const response = HttpClientResponse.fromWeb(\n * HttpClientRequest.get(\"https://example.com/items\"),\n * new Response(null, { headers: { link: '</items?page=2>; rel=\"next\"' } })\n * )\n *\n * Option.map(HttpClientResponse.link(response, \"next\"), (url) => url.href) // => Option.some(\"https://example.com/items?page=2\")\n * ```\n *\n * @see {@link links} to read every link\n *\n * @stability unstable\n * @category accessors\n * @since 4.1.6\n */\nexport const link = /*#__PURE__*/dual(2, (self, rel) => {\n const type = rel.toLowerCase();\n const found = links(self).find(link => link.rel.includes(type));\n return found === undefined ? Option.none() : Option.some(new URL(found.target));\n});\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nclass WebHttpClientResponse extends Inspectable.Class {\n [HttpIncomingMessage.TypeId];\n [TypeId];\n request;\n source;\n constructor(request, source) {\n super();\n this.request = request;\n this.source = source;\n this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n this[TypeId] = TypeId;\n }\n toJSON() {\n return HttpIncomingMessage.inspect(this, {\n _id: \"HttpClientResponse\",\n request: this.request.toJSON(),\n status: this.status\n });\n }\n get status() {\n return this.source.status;\n }\n get url() {\n if (this.source.url) return this.source.url.split(\"#\")[0];\n const url = HttpClientRequest.toUrl(this.request);\n if (Option.isNone(url)) return \"\";\n url.value.hash = \"\";\n return url.value.href;\n }\n cachedHeaders;\n get headers() {\n return this.cachedHeaders ??= Headers.fromInput(this.source.headers);\n }\n cachedCookies;\n get cookies() {\n if (this.cachedCookies) {\n return this.cachedCookies;\n }\n // React Native's Headers does not implement getSetCookie, and it never\n // exposes Set-Cookie to JavaScript anyway.\n return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie?.() ?? []);\n }\n get remoteAddress() {\n return Option.none();\n }\n [WebSourceSymbol]() {\n return this.source;\n }\n get stream() {\n return this.source.body ? Stream.fromReadableStream({\n evaluate: () => this.source.body,\n onError: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }) : Stream.fail(new Error.HttpClientError({\n reason: new Error.EmptyBodyError({\n request: this.request,\n response: this,\n description: \"can not create stream from empty body\"\n })\n }));\n }\n get json() {\n return Effect.flatMap(this.text, text => Effect.try({\n try: () => text === \"\" ? null : JSON.parse(text),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n textBody;\n get text() {\n return this.textBody ??= Effect.map(this.arrayBuffer, _ => new TextDecoder().decode(_));\n }\n get urlParamsBody() {\n return Effect.flatMap(this.arrayBuffer, bytes => Effect.try({\n try: () => UrlParams.fromInput(internalUrlParams.fromBody(bytes)),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }));\n }\n formDataBody;\n get formData() {\n return this.formDataBody ??= Effect.tryPromise({\n try: () => this.source.formData(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n }\n arrayBufferBody;\n get arrayBuffer() {\n if (this.arrayBufferBody) {\n return this.arrayBufferBody;\n }\n this.arrayBufferBody = Effect.tryPromise({\n try: () => this.source.arrayBuffer(),\n catch: cause => new Error.HttpClientError({\n reason: new Error.DecodeError({\n request: this.request,\n response: this,\n cause\n })\n })\n }).pipe(Effect.cached, Effect.runSync);\n return this.arrayBufferBody;\n }\n get upgrade() {\n return Effect.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n request: this.request,\n response: this,\n description: \"fetch cannot hand over the connection of an HTTP upgrade\"\n })\n }));\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\n//# sourceMappingURL=HttpClientResponse.js.map","/**\n * HTTP propagation helpers for trace context and W3C baggage.\n *\n * This module converts Effect `Tracer.Span` values into outbound trace headers\n * and decodes inbound propagation headers into `Tracer.ExternalSpan` parents.\n * HTTP clients use it to continue the current span across outgoing requests, and\n * server middleware uses it to parent request spans from upstream services.\n *\n * Baggage propagation is opt-in: `HttpMiddleware.baggage` populates\n * `CurrentBaggage` and `HttpClient.withBaggage` forwards it.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Option from \"../Option.js\";\nimport * as Str from \"../String.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Headers from \"./Headers.js\";\n/**\n * Encodes a span into HTTP trace propagation headers.\n *\n * **Details**\n *\n * The generated headers include both compact B3 (`b3`) and W3C `traceparent`\n * formats.\n *\n * @stability unstable\n * @category encoding\n * @since 4.0.0\n */\nexport const toHeaders = span => Headers.fromRecordUnsafe({\n b3: `${span.traceId}-${span.spanId}-${span.sampled ? \"1\" : \"0\"}${Option.match(span.parent, {\n onNone: () => \"\",\n onSome: parent => `-${parent.spanId}`\n })}`,\n traceparent: `00-${span.traceId.padStart(32, \"0\")}-${span.spanId}-${span.sampled ? \"01\" : \"00\"}`\n});\n/**\n * Decodes an external span safely from HTTP trace propagation headers.\n *\n * **Details**\n *\n * W3C `traceparent` is tried first, followed by compact B3 (`b3`) and then\n * multi-header B3 (`x-b3-*`).\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const fromHeaders = headers => {\n let span = w3c(headers);\n if (Option.isSome(span)) {\n return span;\n }\n span = b3(headers);\n if (Option.isSome(span)) {\n return span;\n }\n return xb3(headers);\n};\n/**\n * Decodes an external span safely from the compact B3 `b3` header.\n *\n * **Details**\n *\n * Returns `Option.none` when the header is missing or does not contain trace and\n * span identifiers.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const b3 = headers => {\n if (!(\"b3\" in headers)) {\n return Option.none();\n }\n const parts = headers[\"b3\"].split(\"-\");\n if (parts.length < 2 || isB3Ids(parts[0], parts[1]) === false) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: parts[0],\n spanId: parts[1],\n sampled: parts[2] ? parts[2] === \"1\" || parts[2] === \"d\" : true\n }));\n};\n/**\n * Decodes an external span safely from multi-header B3 propagation headers.\n *\n * **Details**\n *\n * The decoder reads `x-b3-traceid`, `x-b3-spanid`, and optional `x-b3-sampled`\n * and `x-b3-flags` headers. Debug flags override the sampling decision.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const xb3 = headers => {\n if (!headers[\"x-b3-traceid\"] || !headers[\"x-b3-spanid\"] || isB3Ids(headers[\"x-b3-traceid\"], headers[\"x-b3-spanid\"]) === false) {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId: headers[\"x-b3-traceid\"],\n spanId: headers[\"x-b3-spanid\"],\n sampled: headers[\"x-b3-flags\"] === \"1\" || (headers[\"x-b3-sampled\"] ? headers[\"x-b3-sampled\"] === \"1\" || headers[\"x-b3-sampled\"] === \"true\" : true)\n }));\n};\nconst w3cTraceId = /^[0-9a-f]{32}$/;\nconst w3cSpanId = /^[0-9a-f]{16}$/;\nconst w3cTraceFlags = /^[0-9a-f]{2}$/;\nconst b3TraceId = /^(?:[0-9a-f]{16}|[0-9a-f]{32})$/;\nconst isB3Ids = (traceId, spanId) => b3TraceId.test(traceId) && w3cSpanId.test(spanId);\n/**\n * Decodes an external span safely from the W3C `traceparent` header.\n *\n * **Details**\n *\n * Only version `00` headers with valid trace and span identifiers and trace\n * flags are accepted.\n *\n * @stability unstable\n * @category decoding\n * @since 4.0.0\n */\nexport const w3c = headers => {\n if (!headers[\"traceparent\"]) {\n return Option.none();\n }\n const parts = headers[\"traceparent\"].split(\"-\");\n if (parts.length !== 4) {\n return Option.none();\n }\n const [version, traceId, spanId, flags] = parts;\n switch (version) {\n case \"00\":\n {\n if (w3cTraceId.test(traceId) === false || w3cSpanId.test(spanId) === false || w3cTraceFlags.test(flags) === false || traceId === \"00000000000000000000000000000000\" || spanId === \"0000000000000000\") {\n return Option.none();\n }\n return Option.some(Tracer.externalSpan({\n traceId,\n spanId,\n sampled: (parseInt(flags, 16) & 1) === 1\n }));\n }\n default:\n {\n return Option.none();\n }\n }\n};\n/**\n * Context reference for current baggage, defaulting to an empty map.\n *\n * **Details**\n *\n * Read propagated values without adding a service requirement.\n * `HttpMiddleware.baggage` sets the reference from incoming headers;\n * `HttpClient.withBaggage` forwards it to outgoing requests.\n *\n * **Gotchas**\n *\n * Baggage is untrusted caller input. Validate it independently before using it\n * for authorization.\n *\n * **Example** (Reading baggage in a handler)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpServerResponse, HttpTraceContext } from \"effect/http\"\n *\n * const handler = Effect.gen(function*() {\n * const baggage = yield* HttpTraceContext.CurrentBaggage\n * return HttpServerResponse.text(baggage.get(\"tenant\")?.value ?? \"unknown\")\n * })\n * ```\n *\n * @see {@link baggageFromHeader} to decode a `baggage` header\n * @stability unstable\n * @category references\n * @since 4.1.8\n */\nexport const CurrentBaggage = /*#__PURE__*/Context.Reference(\"effect/http/HttpTraceContext/CurrentBaggage\", {\n defaultValue: () => new Map()\n});\n/**\n * Decodes a W3C `baggage` header into baggage entries.\n *\n * **Details**\n *\n * Skips members without `=` or a valid token key. Splits on the first `=`\n * and percent-decodes values as UTF-8, replacing invalid sequences with U+FFFD\n * and preserving stray `%` characters. The last value wins for duplicate keys.\n *\n * **Example** (Decoding a baggage header)\n *\n * ```ts import.meta.vitest\n * import { HttpTraceContext } from \"effect/http\"\n *\n * HttpTraceContext.baggageFromHeader(\"tenant=acme%20corp;ttl=30\").get(\"tenant\") // => { value: \"acme corp\", properties: \"ttl=30\" }\n * ```\n *\n * @see {@link baggageToHeader} for the inverse\n * @stability unstable\n * @category decoding\n * @since 4.1.8\n */\nexport const baggageFromHeader = header => {\n const baggage = new Map();\n for (const member of header.split(\",\")) {\n const semicolon = member.indexOf(\";\");\n const pair = semicolon === -1 ? member : member.slice(0, semicolon);\n const equals = pair.indexOf(\"=\");\n if (equals === -1) continue;\n const key = pair.slice(0, equals).trim();\n if (!token.test(key)) continue;\n const value = decodeValue(pair.slice(equals + 1).trim());\n const properties = semicolon === -1 ? \"\" : member.slice(semicolon + 1).trim();\n baggage.set(key, properties === \"\" ? {\n value\n } : {\n value,\n properties\n });\n }\n return baggage;\n};\n/**\n * Encodes baggage entries as a W3C `baggage` header value.\n *\n * **Details**\n *\n * Values are percent-encoded, with unpaired surrogates replaced by U+FFFD.\n * Properties are written unchanged unless they contain a `,` or a character\n * other than a tab or printable ASCII, in which case they are dropped and the\n * value is kept. Entries whose key is not a valid token are skipped. Returns an\n * empty string when no entries remain.\n *\n * @see {@link baggageFromHeader} for the inverse\n * @stability unstable\n * @category encoding\n * @since 4.1.8\n */\nexport const baggageToHeader = self => {\n let header = \"\";\n for (const [key, {\n properties,\n value\n }] of self) {\n if (!token.test(key)) continue;\n if (header !== \"\") header += \",\";\n header += `${key}=${encodeURIComponent(Str.toWellFormed(value))}`;\n if (properties && validProperties.test(properties)) header += `;${properties}`;\n }\n return header;\n};\n// RFC 7230 token\nconst token = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;\n// Allow tabs and printable ASCII except commas, which would add a member.\nconst validProperties = /^[\\t\\x20-\\x2b\\x2d-\\x7e]+$/;\nconst percentEncoded = /(?:%[0-9A-Fa-f]{2})+/g;\nconst utf8Decoder = /*#__PURE__*/new TextDecoder(\"utf-8\", {\n ignoreBOM: true\n});\n// Replace invalid UTF-8 with U+FFFD instead of throwing as decodeURIComponent does.\nconst decodeValue = value => value.replace(percentEncoded, run => utf8Decoder.decode(Uint8Array.from(run.slice(1).split(\"%\"), byte => parseInt(byte, 16))));\n//# sourceMappingURL=HttpTraceContext.js.map","import * as Headers from \"../Headers.js\";\nimport * as UrlParams from \"../UrlParams.js\";\nimport { redactClientPath } from \"./clientPath.js\";\nconst defaultPorts = {\n \"http:\": 80,\n \"https:\": 443,\n \"ws:\": 80,\n \"wss:\": 443\n};\n/**\n * Records `url.*` and `server.*` attributes with URL redaction.\n *\n * @internal\n */\nexport const addUrlAttributes = (span, url, redactedNames, path) => {\n const redactPath = url => path === undefined ? url : redactClientPath(url, path);\n const query = UrlParams.redactUrl(url.search, redactedNames).slice(1);\n span.attribute(\"url.full\", redactPath(UrlParams.redactUrl(url.href, redactedNames)));\n span.attribute(\"url.path\", redactPath(url.pathname));\n if (query !== \"\") {\n span.attribute(\"url.query\", query);\n }\n span.attribute(\"url.scheme\", url.protocol.slice(0, -1));\n if (url.hostname !== \"\") {\n // URL keeps IPv6 brackets in the hostname, but the semantic conventions do not.\n span.attribute(\"server.address\", url.hostname.startsWith(\"[\") ? url.hostname.slice(1, -1) : url.hostname);\n const port = url.port === \"\" ? defaultPorts[url.protocol] : Number(url.port);\n if (port !== undefined) {\n span.attribute(\"server.port\", port);\n }\n }\n};\n/**\n * Adds the names of `Redacted` parameters to the redacted names.\n *\n * @internal\n */\nexport const redactedNames = (urlParams, redactedNames) => {\n const keys = urlParams.params.filter(([, value]) => typeof value !== \"string\").map(([key]) => key);\n return keys.length === 0 ? redactedNames : [...redactedNames, ...new URLSearchParams(keys.map(key => [key, \"\"])).keys()];\n};\n/** @internal */\nexport const addHeaderAttributes = (span, phase, headers, filter, redactedNames) => {\n for (const name in headers) {\n if (!filter(name, phase)) continue;\n span.attribute(`http.${phase}.header.${name}`, Headers.isRedactedName(name, redactedNames) ? \"<redacted>\" : headers[name]);\n }\n};\n//# sourceMappingURL=tracing.js.map","import * as Cause from \"../Cause.js\";\nimport { Clock } from \"../Clock.js\";\nimport * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Exit from \"../Exit.js\";\nimport * as Fiber from \"../Fiber.js\";\nimport { constant, constFalse, constTrue, dual, flow, identity } from \"../Function.js\";\nimport * as Inspectable from \"../Inspectable.js\";\nimport { getStackTraceLimit, setStackTraceLimit } from \"../internal/stackTraceLimit.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport { pipeArguments } from \"../Pipeable.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Ref from \"../Ref.js\";\nimport * as References from \"../References.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Cookies from \"./Cookies.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpBody from \"./HttpBody.js\";\nimport * as Error from \"./HttpClientError.js\";\nimport * as HttpClientRequest from \"./HttpClientRequest.js\";\nimport * as HttpClientResponse from \"./HttpClientResponse.js\";\nimport * as HttpIncomingMessage from \"./HttpIncomingMessage.js\";\nimport * as HttpMethod from \"./HttpMethod.js\";\nimport * as TraceContext from \"./HttpTraceContext.js\";\nimport { CurrentClientPath, urlTemplate, withoutTemplate } from \"./internal/clientPath.js\";\nimport * as tracing from \"./internal/tracing.js\";\nimport { getWebSource, WebSourceSymbol } from \"./internal/webResponse.js\";\nimport * as Url from \"./Url.js\";\nimport * as UrlParams from \"./UrlParams.js\";\nconst TypeId = \"~effect/http/HttpClient\";\n/**\n * Returns `true` if the provided value is an `HttpClient`.\n *\n * @stability unstable\n * @category guards\n * @since 4.0.0\n */\nexport const isHttpClient = u => Predicate.hasProperty(u, TypeId);\n/**\n * Service tag for the default outgoing HTTP client service.\n *\n * **When to use**\n *\n * Use to provide the default outgoing HTTP client service used by request\n * accessors such as `execute`, `get`, and `post`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const HttpClient = /*#__PURE__*/Context.Service(\"effect/HttpClient\");\nconst accessor = method => (...args) => Effect.flatMap(HttpClient, client => client[method](...args));\n/**\n * Executes a prebuilt `HttpClientRequest` using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const execute = /*#__PURE__*/accessor(\"execute\");\n/**\n * Executes a `GET` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const get = /*#__PURE__*/accessor(\"get\");\n/**\n * Executes a `QUERY` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const query = /*#__PURE__*/accessor(\"query\");\n/**\n * Executes a `HEAD` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const head = /*#__PURE__*/accessor(\"head\");\n/**\n * Executes a `POST` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const post = /*#__PURE__*/accessor(\"post\");\n/**\n * Executes a `PATCH` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const patch = /*#__PURE__*/accessor(\"patch\");\n/**\n * Executes a `PUT` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const put = /*#__PURE__*/accessor(\"put\");\n/**\n * Executes a `DELETE` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const del = /*#__PURE__*/accessor(\"del\");\n/**\n * Executes an `OPTIONS` request using the `HttpClient` service from the environment.\n *\n * @stability unstable\n * @category accessors\n * @since 4.0.0\n */\nexport const options = /*#__PURE__*/accessor(\"options\");\n/**\n * Transforms a client by wrapping the response effect for each request.\n *\n * **Details**\n *\n * The transformation receives both the response effect and the original request, allowing it to change success, error, and environment behavior.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const transform = /*#__PURE__*/dual(2, (self, f) => makeWith(Effect.flatMap(request => f(self.postprocess(Effect.succeed(request)), request)), self.preprocess));\n/**\n * Transforms a client by applying an effectful transformation to each response effect.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const transformResponse = /*#__PURE__*/dual(2, (self, f) => makeWith(request => f(self.postprocess(request)), self.preprocess));\nconst catch_ = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.catch(f)));\n/**\n * @stability unstable\n */\nexport {\n/**\n * Handles all client failures with an effectful recovery function and returns a transformed client.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\ncatch_ as catch };\n/**\n * Handles client failures with one or more matching `_tag` values and returns a transformed client.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTag = /*#__PURE__*/dual(3, (self, tag, f) => transformResponse(self,\n// TypeScript 7.1 does not relate the error type `Effect.catchTag` returns\n// to the `ExcludeTag` declared here, because each declares its own copy\n// of the conditional on `K`. The assertion restates the declared type.\neffect => Effect.catchTag(effect, tag, f)));\n/**\n * Handles client failures by matching their `_tag` values against a case map.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const catchTags = /*#__PURE__*/dual(2, (self, cases) => transformResponse(self, Effect.catchTags(cases)));\n/**\n * Filters the result of a response, or runs an alternative effect if the predicate fails.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterOrElse = /*#__PURE__*/dual(3, (self, f, orElse) => transformResponse(self, Effect.filterOrElse(f, orElse)));\n/**\n * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterOrFail = /*#__PURE__*/dual(3, (self, f, orFailWith) => transformResponse(self, Effect.filterOrFail(f, orFailWith)));\n/**\n * Filters responses by HTTP status code.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatus = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.flatMap(HttpClientResponse.filterStatus(f))));\n/**\n * Filters responses that return a 2xx status code.\n *\n * @stability unstable\n * @category filtering\n * @since 4.0.0\n */\nexport const filterStatusOk = /*#__PURE__*/transformResponse(/*#__PURE__*/Effect.flatMap(HttpClientResponse.filterStatusOk));\n/**\n * Constructs an `HttpClient.With` from a preprocessing function and a postprocessing function.\n *\n * **Details**\n *\n * `execute` applies preprocessing to the request and then passes the resulting request effect to postprocessing.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWith = (postprocess, preprocess) => {\n const self = Object.create(Proto);\n self.preprocess = preprocess;\n self.postprocess = postprocess;\n self.execute = function (request) {\n return postprocess(preprocess(request));\n };\n return self;\n};\nconst Proto = {\n [TypeId]: TypeId,\n pipe() {\n return pipeArguments(this, arguments);\n },\n ...Inspectable.BaseProto,\n toJSON() {\n return {\n _id: \"effect/HttpClient\"\n };\n },\n ... /*#__PURE__*/Object.fromEntries(/*#__PURE__*/HttpMethod.allShort.map(([fullMethod, method]) => [method, function (url, options) {\n return this.execute(HttpClientRequest.make(fullMethod)(url, options));\n }]))\n};\n/**\n * Constructs an `HttpClient` from a low-level request runner.\n *\n * **Details**\n *\n * The runner receives the request, resolved URL, abort signal, and current fiber. The client wrapper handles URL construction failures, tracing and propagation, header redaction, aborting the signal when the request is interrupted before a response arrives, and attaching each request to the scope of an enclosing `withScope`.\n *\n * `HttpClientError` reasons redact their URL with the `UrlParams.CurrentRedactedNames` of the fiber that executed the request, even when a callback outside that fiber creates them. The client adds those names to the errors the runner fails with and to errors built later from the response. Rendering an error then adds the names of the rendering fiber. A runner that returns one response object to several executions gives its errors the names of all of them.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = f => makeWith(effect => Effect.flatMap(effect, request => Effect.withFiber(fiber => {\n const scope = fiber.getRef(RequestScope);\n const controller = new AbortController();\n const urlParamsRedactedNames = fiber.getRef(UrlParams.CurrentRedactedNames);\n const redactedPath = fiber.getRef(CurrentClientPath);\n const urlResult = Url.make(request.url, request.urlParams, Option.getOrUndefined(request.hash));\n if (Result.isFailure(urlResult)) {\n const cause = Cause.fail(new Error.HttpClientError({\n reason: new Error.InvalidUrlError({\n request,\n cause: urlResult.failure\n })\n }));\n Error.addFailureRedactedNames(cause, urlParamsRedactedNames, redactedPath);\n return Effect.failCause(cause);\n }\n const url = urlResult.success;\n const send = request => scope === undefined ? f(request, url, controller.signal, fiber)\n // Register the abort before dispatch, so a scope that is already\n // closed aborts the signal before the transport sees it\n : Effect.flatMap(Scope.addFinalizer(scope, Effect.sync(() => controller.abort())), () => f(request, url, controller.signal, fiber));\n const exchange = (request, onResponse) => Effect.uninterruptibleMask(restore => Effect.matchCauseEffect(restore(send(request)), {\n onSuccess: response => {\n response = trackResponse(response, controller, scope !== undefined, urlParamsRedactedNames, redactedPath);\n onResponse?.(response);\n return Effect.succeed(response);\n },\n onFailure: cause => {\n if (Cause.hasInterrupts(cause)) {\n controller.abort();\n }\n Error.addFailureRedactedNames(cause, urlParamsRedactedNames, redactedPath);\n return Effect.failCause(cause);\n }\n }));\n const tracerDisabled = !fiber.getRef(References.TracerEnabled) || fiber.getRef(Tracer.DisablePropagation) || fiber.getRef(TracerDisabledWhen)(request);\n if (tracerDisabled) {\n return exchange(request);\n }\n const template = urlTemplate(request.url, redactedPath);\n return Effect.useSpan(fiber.getRef(SpanNameGenerator)(request, {\n template\n }), {\n kind: \"client\"\n }, span => {\n span.attribute(\"http.request.method\", request.method);\n if (template !== undefined) {\n span.attribute(\"url.template\", template);\n }\n const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames);\n tracing.addUrlAttributes(span, url, tracing.redactedNames(request.urlParams, urlParamsRedactedNames), redactedPath);\n const headerFilter = fiber.getRef(TracerHeaderFilter);\n tracing.addHeaderAttributes(span, \"request\", request.headers, headerFilter, redactedHeaderNames);\n request = fiber.getRef(TracerPropagationEnabled) ? HttpClientRequest.setHeaders(request, TraceContext.toHeaders(span)) : request;\n return Effect.withParentSpan(exchange(request, response => {\n span.attribute(\"http.response.status_code\", response.status);\n tracing.addHeaderAttributes(span, \"response\", response.headers, headerFilter, redactedHeaderNames);\n // OpenTelemetry marks client spans as failed for 4xx and\n // 5xx responses, while the response itself still succeeds.\n if (response.status >= 400 && response.status < 600) {\n span.attribute(\"error.type\", String(response.status));\n endSpanWithStatusError(fiber, span, request, response);\n }\n }), span, {\n captureStackTrace: false\n });\n });\n})), Effect.succeed);\nconst endSpanWithStatusError = (fiber, span, request, response) => {\n const stackTraceLimit = getStackTraceLimit();\n setStackTraceLimit(0);\n let exit;\n try {\n exit = Exit.fail(new Error.HttpClientError({\n reason: new Error.StatusCodeError({\n request,\n response\n })\n }));\n } finally {\n setStackTraceLimit(stackTraceLimit);\n }\n span.end(fiber.getRef(References.TracerTimingEnabled) ? fiber.getRef(Clock).currentTimeNanosUnsafe() : BigInt(0), exit);\n};\n/**\n * Appends a transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequest = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.map(self.preprocess(request), f)));\n/**\n * Appends an effectful transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestEffect = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.flatMap(self.preprocess(request), f)));\n/**\n * Prepends a transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestInput = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => self.preprocess(f(request))));\n/**\n * Prepends an effectful transformation of the request object before sending it.\n *\n * @stability unstable\n * @category mapping\n * @since 4.0.0\n */\nexport const mapRequestInputEffect = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.flatMap(f(request), self.preprocess)));\n/**\n * Retries the request based on a provided schedule or policy.\n *\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const retry = /*#__PURE__*/dual(2, (self, policy) => transformResponse(self, Effect.retry(policy)));\n/**\n * Retries common transient errors, such as rate limiting, timeouts or network issues.\n *\n * **When to use**\n *\n * Use to focus on retrying errors, transient responses, or both.\n *\n * **Details**\n *\n * Specifying a `while` predicate allows you to consider other errors as\n * transient, and is ignored in \"response-only\" mode.\n *\n * A `Retry-After` header on a transient response, or on the response of a\n * status code error, sets the minimum delay before the next attempt. `times`\n * does not bound that wait; add `Schedule.while(retryAfterAtMost(max))` to the\n * `schedule` to stop when the server requests a delay greater than `max`.\n *\n * @see {@link retryAfterAtMost} for rejecting long server-requested delays\n * @stability unstable\n * @category error handling\n * @since 4.0.0\n */\nexport const retryTransient = /*#__PURE__*/dual(2, (self, options) => {\n const isOnlySchedule = Schedule.isSchedule(options);\n const retryOn = isOnlySchedule ? \"errors-and-responses\" : options.retryOn ?? \"errors-and-responses\";\n const schedule = withRetryAfter(isOnlySchedule ? options : options.schedule ?? Schedule.forever);\n const times = isOnlySchedule ? undefined : options.times;\n return transformResponse(self, flow(retryOn === \"errors-only\" ? identity : Effect.repeat({\n schedule,\n times,\n while: isTransientResponse\n }), retryOn === \"response-only\" ? identity : Effect.retry({\n while: isOnlySchedule || options.while === undefined ? isTransientError : Predicate.or(isTransientError, options.while),\n schedule,\n times\n })));\n});\n/**\n * Fails requests that do not receive a response within the given duration.\n *\n * **When to use**\n *\n * Use to configure a timeout once on the client, for example when providing\n * the `HttpClient` service, while keeping the standard `HttpClientError` error\n * model.\n *\n * **Details**\n *\n * A timed out request is interrupted and fails with an `HttpClientError` whose\n * reason is a `TransportError` with a `Cause.TimeoutError` cause.\n * `retryTransient` treats it as transient. Interrupting a request while it\n * waits for response headers aborts the underlying transport.\n *\n * The timer starts after request preprocessing and covers everything the\n * wrapped client does to produce a response. For a plain client this ends when\n * the response headers arrive, but response middleware applied before\n * `timeout`, such as `tap` or `retryTransient`, runs inside the budget,\n * including any body reads it performs. Composition order therefore decides\n * how it interacts with retries: applying `timeout` before `retryTransient`\n * gives each attempt its own budget, while applying it after bounds the whole\n * retry loop.\n *\n * **Gotchas**\n *\n * Body reads outside the timed client are not covered, including those made\n * by response middleware applied after `timeout` and by consumers of the\n * `HttpClient` service. Apply a separate timeout to body reads such as\n * `response.json` or `response.stream` when needed.\n *\n * For a client wrapped with `withScope`, a timeout that fires after the\n * response headers arrive, such as during a body read by response middleware,\n * does not abort the transport. The connection stays open until the scope\n * closes.\n *\n * **Example** (Timing out each attempt)\n *\n * ```ts\n * import { Effect, Layer } from \"effect\"\n * import { FetchHttpClient, HttpClient } from \"effect/http\"\n *\n * const TimedHttpClient = Layer.effect(\n * HttpClient.HttpClient,\n * Effect.map(\n * HttpClient.HttpClient,\n * HttpClient.timeout(\"5 seconds\")\n * )\n * ).pipe(Layer.provide(FetchHttpClient.layer))\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.retryTransient({ times: 3 })\n * )\n * return yield* client.get(\"https://example.com\")\n * }).pipe(Effect.provide(TimedHttpClient))\n * ```\n *\n * @stability unstable\n * @category error handling\n * @since 4.1.0\n */\nexport const timeout = /*#__PURE__*/dual(2, (self, duration) => {\n const decoded = Duration.fromInputUnsafe(duration);\n const description = `timed out after ${Duration.format(decoded)}`;\n return transform(self, (effect, request) => Effect.timeoutOrElse(effect, {\n duration: decoded,\n orElse: () => Effect.fail(new Error.HttpClientError({\n reason: new Error.TransportError({\n request,\n cause: new Cause.TimeoutError(`Operation ${description}`),\n description\n })\n }))\n }));\n});\n/**\n * Applies request rate limiting using the `RateLimiter` service.\n *\n * **Details**\n *\n * It can update limits by inspecting common rate limit response headers and\n * automatically retries HTTP `429` responses (or `HttpClientError` values\n * wrapping a `429` response) by forcing the retry back through the limiter.\n * When a response reports the remaining budget, requests wait for the\n * reported reset once that budget is exhausted.\n *\n * At runtime, omitting `failsWith` leaves limiter failures as `RateLimiterError`.\n * To narrow the inferred error type, specify `\"RateLimiterError\"` or\n * `\"HttpClientError\"` explicitly. Each literal adds only its corresponding\n * error type. Errors from the wrapped client pass through unchanged.\n *\n * **Gotchas**\n *\n * Automatic HTTP `429` retries are unlimited unless `times` is specified.\n * Disabling response inspection does not disable retries; set `times` to `0`\n * to return or fail with the first `429`.\n *\n * If the mode is omitted, hidden by an options type, or union-valued, the\n * inferred type includes both errors: a type without `failsWith` can still\n * describe an object that carries it at runtime. Use\n * `satisfies WithRateLimiter.Options` to preserve an explicit literal mode.\n *\n * With `\"HttpClientError\"`, an outer `retryTransient` can retry limiter\n * failures, and `circuitBreakerClassifier` counts them as transport failures.\n *\n * @stability unstable\n * @category rate limiting\n * @since 4.0.0\n */\nexport const withRateLimiter = /*#__PURE__*/dual(2, (self, options) => {\n const mapLimiterEffect = options.failsWith === \"HttpClientError\" ? (effect, request) => Effect.mapError(effect, cause => new Error.HttpClientError({\n reason: new Error.TransportError({\n request,\n cause\n })\n })) : identity;\n const initialState = {\n initial: true,\n limit: options.limit,\n window: Duration.max(Duration.fromInputUnsafe(options.window), Duration.millis(1))\n };\n const states = new Map();\n const keyOption = options.key;\n const resolveKey = typeof keyOption === \"function\" ? keyOption : constant(keyOption);\n const tokensOption = options.tokens;\n const resolveTokens = typeof tokensOption === \"function\" ? tokensOption : constant(tokensOption ?? 1);\n const adaptiveLearningEnabled = !options.disableAdaptiveLearning;\n const headerNames = resolveRateLimiterHeaderNames(options.responseHeaders);\n const getState = key => {\n const current = states.get(key);\n if (current !== undefined) {\n return current;\n }\n states.set(key, initialState);\n return initialState;\n };\n const budgets = new Map();\n const getBudget = key => {\n let budget = budgets.get(key);\n if (budget === undefined) {\n budget = {\n sent: 0,\n observed: 0,\n remaining: 0,\n resetAt: 0\n };\n budgets.set(key, budget);\n }\n return budget;\n };\n const onResponse = options.disableResponseInspection ? undefined : (clock, key, headers, tokens, sent) => {\n const current = getState(key);\n const next = parseRateLimiterState(current, clock, headers, tokens, headerNames);\n if (next.limit !== current.limit || !Duration.equals(next.window, current.window)) {\n states.set(key, next);\n }\n const remaining = parseRateLimitRemaining(headers, headerNames);\n const budget = getBudget(key);\n // responses to earlier requests carry stale counts\n if (remaining === undefined || sent <= budget.observed) {\n return;\n }\n const resetAfter = parseRateLimitWindow(clock, headers, headerNames);\n budget.observed = sent;\n budget.remaining = remaining;\n if (resetAfter !== undefined) {\n budget.resetAt = clock.currentTimeMillisUnsafe() + Duration.toMillis(resetAfter);\n }\n };\n return transform(self, function loop(effect, request, retries = 0) {\n const fiber = Fiber.getCurrent();\n const clock = fiber.getRef(Clock);\n const key = resolveKey(request);\n const tokens = Math.max(resolveTokens(request), 1);\n const budget = getBudget(key);\n const now = clock.currentTimeMillisUnsafe();\n // requests admitted after the observed one are not reflected in its count\n if (budget.resetAt > now && budget.remaining - (budget.sent - budget.observed) < tokens) {\n return Effect.flatMap(Effect.sleep(budget.resetAt - now), () => loop(effect, request, retries));\n }\n // counted at admission, so requests already admitted are sent even if a\n // later response exhausts the budget\n const sent = budget.sent += tokens;\n const current = getState(key);\n const canRetry = options.times === undefined || retries < options.times;\n function retry(retryAfter) {\n return retryAfter ? Effect.flatMap(Effect.sleep(retryAfter), () => loop(effect, request, retries + 1)) : loop(effect, request, retries + 1);\n }\n const inspectResponse = (response, adaptive) => {\n onResponse?.(clock, key, response.headers, tokens, sent);\n if (options.disableResponseInspection || response.status !== 429) {\n return Effect.succeed(undefined);\n }\n const retryAfter = parseRetryAfter(clock.currentTimeMillisUnsafe(), getHeader(response.headers, ...headerNames.retryAfter));\n if (retryAfter === undefined) {\n return Effect.succeed(undefined);\n }\n const delay = parseRateLimitWindow(clock, response.headers, headerNames) ?? retryAfter;\n if (adaptive === undefined) {\n return Effect.succeed(delay);\n }\n return Effect.as(mapLimiterEffect(options.limiter.adaptiveFeedback({\n key,\n epoch: adaptive.epoch,\n tokens,\n status: response.status,\n retryAfter: delay\n }), request), delay);\n };\n return Effect.flatMap(mapLimiterEffect(options.limiter.consume({\n algorithm: options.algorithm,\n onExceeded: \"delay\",\n key,\n limit: current.limit,\n window: current.window,\n tokens\n }), request), ({\n delay\n }) => {\n const runAdaptive = () => {\n const runRequest = adaptive => {\n const request = Effect.matchEffect(effect, {\n onSuccess(response) {\n return Effect.flatMap(inspectResponse(response, adaptive), retryAfter => {\n if (response.status !== 429 || !canRetry) return Effect.succeed(response);\n return retry(retryAfter);\n });\n },\n onFailure(error) {\n if (isTooManyRequestsHttpClientError(error)) {\n return Effect.flatMap(inspectResponse(error.reason.response, adaptive), retryAfter => canRetry ? retry(retryAfter) : Effect.fail(error));\n }\n return Effect.fail(error);\n }\n });\n return adaptive === undefined || Duration.isZero(adaptive.delay) ? request : Effect.delay(request, adaptive.delay);\n };\n if (!adaptiveLearningEnabled) {\n return runRequest(undefined);\n }\n return Effect.flatMap(mapLimiterEffect(options.limiter.adaptiveConsume({\n key,\n tokens,\n fallbackLimit: current.limit,\n fallbackWindow: current.window\n }), request), adaptive => {\n if (!Duration.isZero(adaptive.delay) && adaptive.phase === \"cooldown\") {\n return Effect.flatMap(Effect.sleep(adaptive.delay), runAdaptive);\n }\n return runRequest(adaptive);\n });\n };\n return Duration.isZero(delay) ? runAdaptive() : Effect.flatMap(Effect.sleep(delay), runAdaptive);\n });\n });\n});\n/**\n * Guards requests with a `CircuitBreaker`.\n *\n * **Details**\n *\n * Requests are keyed by origin unless `key` is set, and classified with\n * `circuitBreakerClassifier` unless `classify` is set. A rejected request\n * fails with `CircuitBreakerError` without reaching the wrapped client.\n *\n * Apply it after `withRateLimiter` and `retryTransient`, so the breaker sees\n * one outcome per call and an open circuit skips the retry loop.\n * `retryTransient` never retries a `CircuitBreakerError`. A custom `classify`\n * can delegate the cases it doesn't handle to `circuitBreakerClassifier`.\n *\n * **Gotchas**\n *\n * - The breaker only sees the response headers. To count an error in the\n * body, lift it into the error channel below the breaker with\n * `transformResponse` and count it in `classify`.\n * - `withRateLimiter` retries `429` without limit by default, which can hold\n * the probe slot for minutes. Set its `times`.\n * - A rejected request has no client span. The rejection fails the caller's\n * span instead.\n *\n * **Example** (Guarding an API in the recommended order)\n *\n * ```ts import.meta.vitest\n * import { Effect, Layer, Ref, Schedule } from \"effect\"\n * import { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\"\n * import { CircuitBreaker, RateLimiter } from \"effect/persistence\"\n *\n * const program = Effect.gen(function*() {\n * const requests = yield* Ref.make(0)\n * // A dependency that always answers 503.\n * const unavailable = HttpClient.make((request) =>\n * Effect.as(Ref.update(requests, (n) => n + 1), HttpClientResponse.fromWeb(request, new Response(null, { status: 503 })))\n * )\n *\n * const breaker = yield* CircuitBreaker.make({\n * tripPolicy: CircuitBreaker.consecutive(1),\n * openDuration: \"30 seconds\"\n * })\n * const client = unavailable.pipe(\n * HttpClient.withRateLimiter({\n * limiter: yield* RateLimiter.RateLimiter,\n * key: \"inventory\",\n * limit: 100,\n * window: \"1 second\",\n * times: 3\n * }),\n * HttpClient.retryTransient({ times: 2, schedule: Schedule.exponential(\"1 millis\") }),\n * HttpClient.withCircuitBreaker({ breaker })\n * )\n *\n * // Three attempts, then the breaker records one failure and opens.\n * yield* client.execute(HttpClientRequest.get(\"http://inventory.test/items\"))\n * // Rejected before the retry loop starts, so no further request is sent.\n * const rejected = yield* Effect.flip(client.execute(HttpClientRequest.get(\"http://inventory.test/items\")))\n *\n * return [yield* Ref.get(requests), rejected._tag]\n * }).pipe(\n * Effect.scoped,\n * Effect.provide(Layer.merge(\n * CircuitBreaker.layerStoreMemory(),\n * RateLimiter.layer.pipe(Layer.provide(RateLimiter.layerStoreMemory))\n * ))\n * )\n *\n * await Effect.runPromise(program) // => [3, \"CircuitBreakerError\"]\n * ```\n *\n * **Example** (Counting an error in the body as a failure)\n *\n * This API answers `200` with `{ \"status\": \"degraded\" }` when it is failing.\n *\n * ```ts import.meta.vitest\n * import { Data, Effect, Exit, Option } from \"effect\"\n * import { HttpClient, HttpClientRequest, HttpClientResponse } from \"effect/http\"\n * import { CircuitBreaker } from \"effect/persistence\"\n *\n * class Degraded extends Data.TaggedError(\"Degraded\") {}\n *\n * const degraded = HttpClient.make((request) =>\n * Effect.succeed(HttpClientResponse.fromWeb(request, Response.json({ status: \"degraded\" })))\n * )\n *\n * const program = Effect.gen(function*() {\n * const breaker = yield* CircuitBreaker.make({\n * tripPolicy: CircuitBreaker.consecutive(1),\n * openDuration: \"30 seconds\"\n * })\n * const client = degraded.pipe(\n * HttpClient.transformResponse(Effect.flatMap((response) =>\n * Effect.flatMap(response.json, (body) =>\n * typeof body === \"object\" && body !== null && \"status\" in body && body.status === \"degraded\"\n * ? Effect.fail(new Degraded())\n * : Effect.succeed(response))\n * )),\n * HttpClient.withCircuitBreaker({\n * breaker,\n * classify: (exit) =>\n * Option.exists(Exit.findErrorOption(exit), (error) => error._tag === \"Degraded\")\n * ? CircuitBreaker.failure()\n * : HttpClient.circuitBreakerClassifier(exit)\n * })\n * )\n *\n * yield* Effect.flip(client.get(\"http://status.test/\"))\n * const state = yield* breaker.state(\"http://status.test\")\n * return state._tag\n * }).pipe(Effect.scoped, Effect.provide(CircuitBreaker.layerStoreMemory()))\n *\n * await Effect.runPromise(program) // => \"Open\"\n * ```\n *\n * @stability experimental\n * @category circuit breaking\n * @since 4.0.7\n */\nexport const withCircuitBreaker = /*#__PURE__*/dual(2, (self, options) => {\n const keyOption = options.key;\n const resolveKey = typeof keyOption === \"function\" ? keyOption : keyOption === undefined ? requestOrigin : constant(keyOption);\n const classify = options.classify ?? circuitBreakerClassifier;\n return transform(self, (effect, request) => options.breaker.execute(effect, {\n key: resolveKey(request),\n classify\n }));\n});\nconst requestOrigin = request => Option.match(HttpClientRequest.toUrl(request), {\n onNone: () => request.url,\n onSome: url => url.origin\n});\n/**\n * The default `withCircuitBreaker` classifier.\n *\n * **Details**\n *\n * - Failure: status 408, 500, 502, 503 or 504, returned or wrapped in a\n * `StatusCodeError`, and any `TransportError` or `Cause.TimeoutError`.\n * - Success: any other response, including other 4xx, since the dependency\n * answered.\n * - Ignored: status 429 (left to `withRateLimiter`), `EncodeError`,\n * `InvalidUrlError`, `DecodeError`, `EmptyBodyError`, unknown typed errors\n * and defects. HttpClient errors are typed, so a defect here is a bug in\n * the caller.\n *\n * When a cause holds several errors, a failure beats a success and a success\n * beats an ignored outcome. A failure carries the longest `Retry-After` it\n * saw. The result is an `Effect` only because parsing an HTTP-date\n * `Retry-After` reads `Clock`.\n *\n * **Gotchas**\n *\n * `TransportError` also covers client-side refusals, which count as failures.\n *\n * @stability experimental\n * @category circuit breaking\n * @since 4.0.7\n */\nexport const circuitBreakerClassifier = exit => Effect.clockWith(clock => Effect.succeed(classifyCircuitBreakerExit(exit, clock.currentTimeMillisUnsafe())));\nconst classifyCircuitBreakerExit = (exit, nowMillis) => {\n if (Exit.isSuccess(exit)) {\n const outcome = circuitBreakerStatusOutcome(exit.value.status);\n return outcome === \"Failure\" ? circuitBreakerFailure(retryAfterOf(exit.value, nowMillis)) : {\n _tag: outcome\n };\n }\n let failed = false;\n let succeeded = false;\n let retryAfter;\n for (const reason of exit.cause.reasons) {\n if (!Cause.isFailReason(reason)) {\n continue;\n }\n const outcome = circuitBreakerErrorOutcome(reason.error);\n if (outcome === \"Failure\") {\n failed = true;\n const hint = retryAfterOf(reason.error, nowMillis);\n if (hint !== undefined) {\n retryAfter = retryAfter === undefined ? hint : Duration.max(retryAfter, hint);\n }\n } else if (outcome === \"Success\") {\n succeeded = true;\n }\n }\n return failed ? circuitBreakerFailure(retryAfter) : {\n _tag: succeeded ? \"Success\" : \"Ignored\"\n };\n};\nconst circuitBreakerFailure = retryAfter => ({\n _tag: \"Failure\",\n retryAfter\n});\nconst circuitBreakerErrorOutcome = error => {\n if (Cause.isTimeoutError(error)) {\n return \"Failure\";\n }\n if (!Error.isHttpClientError(error)) {\n return \"Ignored\";\n }\n switch (error.reason._tag) {\n case \"TransportError\":\n return \"Failure\";\n case \"StatusCodeError\":\n return circuitBreakerStatusOutcome(error.reason.response.status);\n default:\n return \"Ignored\";\n }\n};\nconst circuitBreakerStatusOutcome = status => status === 429 ? \"Ignored\" : status === 408 || status === 500 || status === 502 || status === 503 || status === 504 ? \"Failure\" : \"Success\";\nconst resolveRateLimiterHeaderNames = responseHeaders => ({\n limit: responseHeaders?.limit === undefined ? [\"ratelimit-limit\", \"x-ratelimit-limit\"] : [responseHeaders.limit.toLowerCase()],\n remaining: responseHeaders?.remaining === undefined ? [\"ratelimit-remaining\", \"x-ratelimit-remaining\"] : [responseHeaders.remaining.toLowerCase()],\n reset: responseHeaders?.reset === undefined ? [\"ratelimit-reset\", \"x-ratelimit-reset\"] : [responseHeaders.reset.toLowerCase()],\n resetAfter: responseHeaders?.resetAfter === undefined ? [\"ratelimit-reset-after\", \"x-ratelimit-reset-after\"] : [responseHeaders.resetAfter.toLowerCase()],\n retryAfter: responseHeaders?.retryAfter === undefined ? [\"retry-after\"] : [responseHeaders.retryAfter.toLowerCase()]\n});\nconst parseRateLimiterState = (state, clock, headers, tokens, headerNames) => {\n const limit = parseRateLimitLimit(state, headers, tokens, headerNames) ?? state.limit;\n const window = parseRateLimitWindow(clock, headers, headerNames) ?? state.window;\n if (limit === state.limit && Duration.equals(window, state.window)) {\n return state;\n }\n return {\n limit,\n window,\n initial: false\n };\n};\nconst parseRateLimitLimit = (state, headers, tokens, headerNames) => {\n const raw = getHeader(headers, ...headerNames.limit);\n const value = parseNumberHeader(raw);\n if (value !== undefined && value > 0) {\n return value;\n }\n const remaining = parseRateLimitRemaining(headers, headerNames);\n if (remaining === undefined) {\n return undefined;\n }\n return state.initial ? remaining + tokens : Math.max(remaining + tokens, state.limit);\n};\nconst parseRateLimitRemaining = (headers, headerNames) => {\n const raw = getHeader(headers, ...headerNames.remaining);\n const value = parseNumberHeader(raw);\n return value !== undefined && value >= 0 ? value : undefined;\n};\nconst parseRateLimitWindow = (clock, headers, headerNames) => {\n const resetAfter = parseResetAfter(getHeader(headers, ...headerNames.resetAfter));\n if (resetAfter !== undefined) {\n return resetAfter;\n }\n return parseResetHeader(clock, getHeader(headers, ...headerNames.reset));\n};\nconst retryAfterDelay = (nowMillis, value) => {\n if (value === undefined) {\n return undefined;\n }\n const retryAfter = Headers.parseRetryAfter(value);\n return Result.isSuccess(retryAfter) ? Headers.retryAfterDelay(retryAfter.success, nowMillis) : undefined;\n};\n// The one millisecond floor keeps a past date or `0` from retrying immediately.\nconst parseRetryAfter = (nowMillis, value) => {\n const delay = retryAfterDelay(nowMillis, value);\n return delay === undefined ? undefined : Duration.max(delay, Duration.millis(1));\n};\nconst parseResetAfter = value => {\n const numeric = parseNumberHeader(value);\n if (numeric === undefined || numeric <= 0) {\n return undefined;\n }\n return Duration.max(Duration.seconds(numeric), Duration.millis(1));\n};\nconst parseResetHeader = (clock, value) => {\n const numeric = parseNumberHeader(value);\n if (numeric === undefined || numeric <= 0) {\n return undefined;\n }\n const nowMillis = clock.currentTimeMillisUnsafe();\n if (numeric > 1_000_000_000_000) {\n return Duration.millis(Math.max(numeric - nowMillis, 1));\n }\n if (numeric > 1_000_000_000) {\n return Duration.millis(Math.max(numeric * 1_000 - nowMillis, 1));\n }\n return Duration.max(Duration.seconds(numeric), Duration.millis(1));\n};\nconst parseNumberHeader = value => {\n if (value === undefined) {\n return undefined;\n }\n const match = /-?\\d+(?:\\.\\d+)?/.exec(value);\n if (match === null) {\n return undefined;\n }\n const parsed = Number(match[0]);\n return Number.isFinite(parsed) ? parsed : undefined;\n};\nconst getHeader = (headers, ...keys) => {\n for (let i = 0; i < keys.length; i++) {\n const value = headers[keys[i]];\n if (value !== undefined) {\n return value;\n }\n }\n return undefined;\n};\n/**\n * Performs an additional effect after a successful request.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tap = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.tap(f)));\n/**\n * Performs an additional effect after an unsuccessful request.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapError = /*#__PURE__*/dual(2, (self, f) => transformResponse(self, Effect.tapError(f)));\n/**\n * Performs an additional effect on the request before sending it.\n *\n * @stability unstable\n * @category sequencing\n * @since 4.0.0\n */\nexport const tapRequest = /*#__PURE__*/dual(2, (self, f) => makeWith(self.postprocess, request => Effect.tap(self.preprocess(request), f)));\n/**\n * Adds a `Ref` of stored cookies to the client for handling cookies across\n * requests.\n *\n * **When to use**\n *\n * Use to add shared cookie storage to a client so response cookies are retained\n * and sent by later requests to a matching host, path, and scheme.\n *\n * **Details**\n *\n * Response cookies are merged into the ref with `Cookies.mergeIntoArray` for\n * the response URL. When a request is sent, `Cookies.toRequestCookieHeader`\n * selects the cookies for its final URL, after later transformations such as\n * `HttpClientRequest.prependUrl`, and sets them as the `cookie` header. With\n * `followRedirects` applied after `withCookiesRef`, this runs for every hop.\n * Expiry uses the current `Clock`.\n *\n * @stability unstable\n * @category cookies\n * @since 4.0.0\n */\nexport const withCookiesRef = /*#__PURE__*/dual(2, (self, ref) => {\n const now = () => Fiber.getCurrent().getRef(Clock).currentTimeMillisUnsafe();\n const addCookies = request => Effect.map(Ref.get(ref), cookies => {\n const header = Cookies.toRequestCookieHeader(cookies, request.url, now());\n if (header === undefined) return request;\n return HttpClientRequest.setHeader(request, \"cookie\", header);\n });\n return makeWith(request => Effect.tap(self.postprocess(Effect.flatMap(request, addCookies)), response => Ref.update(ref, Cookies.mergeIntoArray(response.url, response.cookies, now()))), self.preprocess);\n});\n/**\n * Attaches every request the client sends to the current `Scope`, and aborts\n * them when the scope closes.\n *\n * **When to use**\n *\n * Use when a response body, an upgraded socket or a `toWeb` hand-off must\n * stay open after the response effect completes, and close it by closing the\n * scope.\n *\n * **Details**\n *\n * Ownership follows the execution, not the request value. Each request the\n * transport sends while this client executes belongs to the scope: every\n * redirect hop, retry attempt and request rewritten by middleware, whichever\n * side of `followRedirects`, `withCookiesRef` or `retryTransient` the\n * `withScope` is on. Reusing one request, or one response effect,\n * concurrently under different scopes gives each execution its own owner.\n *\n * Closing the scope aborts pending requests and open response bodies. A\n * request sent after the scope has closed is aborted before the transport\n * starts it. Interrupting a request before its response arrives still aborts\n * it, so a `timeout` that fires before then releases the connection. Once a\n * response is returned, its body is released only when the scope closes.\n *\n * **Gotchas**\n *\n * Requests that middleware sends with another client while this client\n * executes, such as a token fetch in `mapRequestEffect`, are also attached to\n * the scope. When `withScope` is nested, the innermost one owns the requests,\n * so to give a helper request a different lifetime, apply `withScope` to the\n * helper client and run its request in its own scope, for example with\n * `Effect.scoped`.\n *\n * @stability unstable\n * @category resource management\n * @since 4.0.0\n */\nexport const withScope = self => transformResponse(self, Effect.provideServiceEffect(RequestScope, Effect.scope));\n/**\n * Adds `HttpTraceContext.CurrentBaggage` to outgoing requests as a W3C `baggage` header.\n *\n * **Details**\n *\n * Keeps an existing `baggage` header and adds none when the current baggage is empty.\n *\n * **Gotchas**\n *\n * Baggage can carry application data. Apply this only within your trust boundary.\n * `followRedirects` strips baggage on cross-origin redirects; Fetch's automatic\n * redirects can forward it. With `FetchHttpClient`, provide\n * `FetchHttpClient.RequestInit` with `{ redirect: \"manual\" }` and use\n * `followRedirects`, or disable redirects with `{ redirect: \"error\" }`.\n *\n * **Example** (Forwarding baggage to an internal service)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(HttpClient.withBaggage)\n * return yield* client.get(\"http://orders.internal/orders\")\n * })\n * ```\n *\n * @see {@link TraceContext.CurrentBaggage} for the baggage that is sent\n * @stability unstable\n * @category tracing\n * @since 4.1.8\n */\nexport const withBaggage = self => mapRequestEffect(self, request => request.headers.baggage !== undefined ? Effect.succeed(request) : Effect.map(TraceContext.CurrentBaggage, baggage => {\n const header = TraceContext.baggageToHeader(baggage);\n return header === \"\" ? request : HttpClientRequest.setHeader(request, \"baggage\", header);\n}));\nconst crossOriginHeaders = [\"authorization\", \"proxy-authorization\", \"cookie\", \"baggage\"];\n/**\n * Enables following HTTP redirects up to a specified number of times.\n *\n * **Details**\n *\n * Follows `3xx` responses that include a `Location` header, up to\n * `maxRedirects` (default `10`) times. When the limit is reached or the\n * `Location` header is not a valid URL, the last redirect response is returned.\n * Redirects to another origin drop the `authorization`,\n * `proxy-authorization`, `cookie` and `baggage` headers.\n *\n * **Gotchas**\n *\n * This only sees redirects that the underlying client returns. `fetch`\n * follows redirects itself by default, so with `FetchHttpClient` provide\n * `FetchHttpClient.RequestInit` with `{ redirect: \"manual\" }`. Browsers return\n * an opaque response without a `Location` header for manual redirects, so\n * this cannot follow them there.\n *\n * **Example** (Following redirects with FetchHttpClient)\n *\n * ```ts\n * import { Effect } from \"effect\"\n * import { FetchHttpClient, HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.followRedirects(5)\n * )\n * return yield* client.get(\"https://example.com/redirect\")\n * }).pipe(\n * Effect.provide(FetchHttpClient.layer),\n * Effect.provideService(FetchHttpClient.RequestInit, { redirect: \"manual\" })\n * )\n * ```\n *\n * @stability unstable\n * @category redirects\n * @since 4.0.0\n */\nexport const followRedirects = /*#__PURE__*/dual(args => isHttpClient(args[0]), (self, maxRedirects) => makeWith(request => {\n const loop = (request, redirects) => Effect.suspend(() => {\n let currentRequest;\n return Effect.flatMap(self.postprocess(Effect.map(request, request => {\n currentRequest = request;\n return request;\n })), response => {\n if (response.status < 300 || response.status >= 400 || !response.headers.location || redirects >= (maxRedirects ?? 10)) {\n return Effect.succeed(response);\n }\n const urlResult = Url.fromString(response.headers.location, response.request.url);\n if (Result.isFailure(urlResult)) {\n return Effect.succeed(response);\n }\n const url = urlResult.success;\n const request = currentRequest ?? response.request;\n let nextRequest = request;\n if ((response.status === 301 || response.status === 302) && request.method === \"POST\" || response.status === 303 && request.method !== \"GET\" && request.method !== \"HEAD\") {\n nextRequest = HttpClientRequest.setMethod(nextRequest, \"GET\");\n nextRequest = HttpClientRequest.setBody(nextRequest, HttpBody.empty);\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-encoding\");\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-language\");\n nextRequest = HttpClientRequest.removeHeader(nextRequest, \"content-location\");\n }\n // Request the Location as sent: setUrl with a URL object would re-encode its query\n const hash = url.hash === \"\" ? Option.none() : Option.some(url.hash.slice(1));\n url.hash = \"\";\n nextRequest = HttpClientRequest.makeWith(nextRequest.method, url.href, UrlParams.empty, hash, url.origin === new URL(response.request.url).origin ? nextRequest.headers : Headers.removeMany(nextRequest.headers, crossOriginHeaders), nextRequest.body);\n // Abort the discarded response to release its connection without reading the body\n return Effect.andThen(Effect.sync(() => responseControllers.get(response)?.abort()),\n // A redirect hop is a new request, so it does not get the endpoint's url.template\n Effect.updateService(loop(Effect.succeed(nextRequest), redirects + 1), CurrentClientPath, withoutTemplate));\n });\n });\n return loop(request, 0);\n}, self.preprocess));\n/**\n * Context reference for a predicate that disables client-side tracing for matching outgoing requests.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerDisabledWhen = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerDisabledWhen\", {\n defaultValue: () => constFalse\n});\n/**\n * Context reference for filtering request and response headers added to client spans.\n *\n * **Details**\n *\n * Header capture is opt-in: the default filter records no headers. Captured\n * headers listed in `Headers.CurrentRedactedNames` are recorded as `<redacted>`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerHeaderFilter = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerHeaderFilter\", {\n defaultValue: () => constFalse\n});\n/**\n * Context reference that controls whether outgoing client spans are propagated to request headers.\n *\n * **Details**\n *\n * When this is `true`, the client writes the compact B3 `b3` header and the\n * W3C `traceparent` header. The default is on. The client span is still\n * created when this is `false`.\n *\n * **Gotchas**\n *\n * A browser preflight fails when the target does not list `b3` and\n * `traceparent` in `Access-Control-Allow-Headers`. Set this to `false` for\n * those requests.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const TracerPropagationEnabled = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/TracerPropagationEnabled\", {\n defaultValue: constTrue\n});\n/**\n * Context reference for generating the span name used for outgoing client request spans.\n *\n * **Details**\n *\n * The second argument carries the request's `template`, the declared path of\n * an `HttpApiClient` endpoint request such as `/users/:id`, or `undefined`\n * for other requests. The default returns `GET /users/:id` when there is a\n * template and the method otherwise. Provide `(request) => request.method` to\n * use method-only names.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const SpanNameGenerator = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/SpanNameGenerator\", {\n defaultValue: () => (request, {\n template\n }) => template === undefined ? request.method : `${request.method} ${template}`\n});\n/**\n * Creates an `HttpClient` layer and merges the layer construction context into client response effects.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerMergedContext = effect => Layer.effect(HttpClient)(Effect.contextWith(context => Effect.map(effect, client => transformResponse(client, Effect.updateContext(input => Context.merge(context, input))))));\n// -----------------------------------------------------------------------------\n// internal\n// -----------------------------------------------------------------------------\nconst responseRegistry = /*#__PURE__*/(() => {\n if (\"FinalizationRegistry\" in globalThis && globalThis.FinalizationRegistry) {\n const registry = /*#__PURE__*/new FinalizationRegistry(controller => {\n try {\n controller.abort();\n } catch {\n // Runtimes such as workerd disallow aborting I/O outside its request context.\n }\n });\n return {\n register(response, controller) {\n registry.register(response, controller, response);\n },\n unregister(response) {\n registry.unregister(response);\n }\n };\n }\n const timers = /*#__PURE__*/new WeakMap();\n return {\n register(response, controller) {\n timers.set(response, setTimeout(() => controller.abort(), 5000));\n },\n unregister(response) {\n const timer = timers.get(response);\n if (timer === undefined) return;\n clearTimeout(timer);\n timers.delete(response);\n }\n };\n})();\nconst RequestScope = /*#__PURE__*/Context.Reference(\"effect/http/HttpClient/RequestScope\", {\n defaultValue: () => undefined\n});\nconst responseControllers = /*#__PURE__*/new WeakMap();\nconst trackResponse = (response, controller, scoped, urlParamsRedactedNames, redactedPath) => {\n // Body readers create errors with the runner's response, while callers hold\n // the wrapper, so both carry the names of the executing fiber.\n Error.addResponseRedactedNames(response, urlParamsRedactedNames, redactedPath);\n if (!scoped) {\n responseRegistry.register(response, controller);\n response = new InterruptibleResponse(response, controller);\n Error.addResponseRedactedNames(response, urlParamsRedactedNames, redactedPath);\n }\n responseControllers.set(response, controller);\n return response;\n};\nclass InterruptibleResponse {\n original;\n controller;\n constructor(original, controller) {\n this.original = original;\n this.controller = controller;\n }\n [HttpClientResponse.TypeId] = HttpClientResponse.TypeId;\n [HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId;\n applyInterrupt(effect) {\n return Effect.suspend(() => {\n responseRegistry.unregister(this.original);\n return Effect.onInterrupt(effect, () => Effect.sync(() => {\n this.controller.abort();\n }));\n });\n }\n get request() {\n return this.original.request;\n }\n get url() {\n return this.original.url;\n }\n get status() {\n return this.original.status;\n }\n get headers() {\n return this.original.headers;\n }\n get cookies() {\n return this.original.cookies;\n }\n get remoteAddress() {\n return this.original.remoteAddress;\n }\n get formData() {\n return this.applyInterrupt(this.original.formData);\n }\n get text() {\n return this.applyInterrupt(this.original.text);\n }\n get json() {\n return this.applyInterrupt(this.original.json);\n }\n get urlParamsBody() {\n return this.applyInterrupt(this.original.urlParamsBody);\n }\n get arrayBuffer() {\n return this.applyInterrupt(this.original.arrayBuffer);\n }\n get upgrade() {\n return this.applyInterrupt(this.original.upgrade);\n }\n [WebSourceSymbol]() {\n const source = getWebSource(this.original);\n // A handed-over Web body outlives this wrapper, so collecting it must not abort the request.\n if (source !== undefined) responseRegistry.unregister(this.original);\n return source;\n }\n get stream() {\n return Stream.suspend(() => {\n responseRegistry.unregister(this.original);\n return Stream.ensuring(this.original.stream, Effect.sync(() => {\n this.controller.abort();\n }));\n });\n }\n toJSON() {\n return this.original.toJSON();\n }\n [Inspectable.NodeInspectSymbol]() {\n return this.original[Inspectable.NodeInspectSymbol]();\n }\n pipe() {\n return pipeArguments(this, arguments);\n }\n}\n/**\n * Returns `true` for an error that `retryTransient` retries by default: a\n * timeout, a transport error, or a status code error with a transient response.\n *\n * **When to use**\n *\n * Use to classify failures the same way `retryTransient` does, for example in a\n * custom retry policy or a circuit breaker.\n *\n * **Example** (Classifying client errors)\n *\n * ```ts import.meta.vitest\n * import { Cause } from \"effect\"\n * import { HttpClient, HttpClientError, HttpClientRequest } from \"effect/http\"\n *\n * const request = HttpClientRequest.get(\"https://example.com\")\n * const transportError = new HttpClientError.HttpClientError({\n * reason: new HttpClientError.TransportError({ request })\n * })\n *\n * HttpClient.isTransientError(transportError) // => true\n * HttpClient.isTransientError(new Cause.TimeoutError()) // => true\n * HttpClient.isTransientError(new Error(\"boom\")) // => false\n * ```\n *\n * @see {@link isTransientResponse} for the response statuses it accepts\n * @see {@link retryTransient} for the retry policy that uses it\n * @stability unstable\n * @category predicates\n * @since 4.1.0\n */\nexport const isTransientError = error => Cause.isTimeoutError(error) || isTransientHttpError(error);\nconst isTransientHttpError = error => Error.isHttpClientError(error) && (error.reason._tag === \"TransportError\" || error.reason._tag === \"StatusCodeError\" && isTransientResponse(error.reason.response));\nconst retryAfterHeaderOf = input => {\n const response = Error.isHttpClientError(input) ? input.response : Predicate.hasProperty(input, HttpClientResponse.TypeId) ? input : undefined;\n return response?.headers[\"retry-after\"];\n};\nconst retryAfterOf = (input, nowMillis) => parseRetryAfter(nowMillis, retryAfterHeaderOf(input));\n/**\n * Creates a predicate for `Schedule.while` that returns `false` when the\n * server requests a `Retry-After` delay greater than `max`.\n *\n * **When to use**\n *\n * Use with `retryTransient` to stop retries before a long `Retry-After` sleep.\n *\n * **Details**\n *\n * Reads the header from an `HttpClientResponse` or the response of an\n * `HttpClientError`. Returns `true` for delays at or below `max` and for inputs\n * without a valid header, including application errors. HTTP dates are compared\n * with the schedule's `now`.\n *\n * When the predicate returns `false`, `Schedule.while` stops before sleeping.\n * `retryTransient` then returns the last response or fails with the original error.\n *\n * **Gotchas**\n *\n * `max` limits the delay requested by the server, not the schedule's delay or\n * total retry time. `retryTransient` honors the header's delay automatically;\n * with `HttpClient.retry` or `Effect.retry`, the schedule supplies the delay.\n *\n * **Example** (Giving up on a long Retry-After)\n *\n * ```ts\n * import { Effect, Schedule } from \"effect\"\n * import { HttpClient } from \"effect/http\"\n *\n * const program = Effect.gen(function*() {\n * const client = (yield* HttpClient.HttpClient).pipe(\n * HttpClient.retryTransient({\n * times: 3,\n * schedule: Schedule.exponential(\"100 millis\").pipe(\n * Schedule.while(HttpClient.retryAfterAtMost(\"30 seconds\"))\n * )\n * })\n * )\n * return yield* client.get(\"https://example.com\")\n * })\n * ```\n *\n * @see {@link retryTransient} for the retry policy that honors `Retry-After`\n * @stability unstable\n * @category predicates\n * @since 4.1.8\n */\nexport const retryAfterAtMost = max => {\n const limit = Duration.fromInputUnsafe(max);\n return ({\n input,\n now\n }) => {\n const delay = retryAfterDelay(now, retryAfterHeaderOf(input));\n return delay === undefined || Duration.isLessThanOrEqualTo(delay, limit);\n };\n};\nconst withRetryAfter = schedule => Schedule.fromStep(Effect.map(Schedule.toStep(schedule), step => (now, input) => {\n const retryAfter = retryAfterOf(input, now);\n if (retryAfter === undefined) {\n return step(now, input);\n }\n return Effect.map(step(now, input), ([output, delay]) => [output, Duration.max(delay, retryAfter)]);\n}));\nconst isTooManyRequestsHttpClientError = error => Error.isHttpClientError(error) && error.reason._tag === \"StatusCodeError\" && error.reason.response.status === 429;\n/**\n * Returns `true` for a response whose status `retryTransient` retries by\n * default: 408, 429, 500, 502, 503 or 504.\n *\n * **When to use**\n *\n * Use to retry the same responses as `retryTransient` in a custom retry policy.\n *\n * @see {@link isTransientError} for the matching error predicate\n * @see {@link retryTransient} for the retry policy that uses it\n * @stability unstable\n * @category predicates\n * @since 4.1.0\n */\nexport const isTransientResponse = response => response.status === 408 || response.status === 429 || response.status === 500 || response.status === 502 || response.status === 503 || response.status === 504;\n//# sourceMappingURL=HttpClient.js.map","/**\n * Service contract for servers that accept socket connections.\n *\n * `SocketServer` exposes the bound server `address` and a long-running `run`\n * loop that hands each accepted connection to a handler as a `Socket.Socket`.\n * Bound addresses use the shared `NetAddress.SocketAddress` model. This module also\n * defines server-level errors reported while opening or running a server.\n * Platform layers provide concrete implementations of this service.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Data from \"../Data.js\";\n/**\n * Context service for a socket server, exposing its bound address and a run\n * loop that handles each accepted `Socket`.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class SocketServer extends /*#__PURE__*/Context.Service()(\"@effect/platform/SocketServer\") {}\n/**\n * Runtime type identifier attached to `SocketServerError` values.\n *\n * @stability unstable\n * @category type IDs\n * @since 4.0.0\n */\nexport const ErrorTypeId = \"@effect/platform/SocketServer/SocketServerError\";\n/**\n * Error reason for failures that occur while opening a socket server.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerOpenError extends /*#__PURE__*/Data.TaggedError(\"SocketServerOpenError\") {\n get message() {\n return \"Open\";\n }\n}\n/**\n * Error reason for uncategorized socket server failures.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerUnknownError extends /*#__PURE__*/Data.TaggedError(\"SocketServerUnknownError\") {\n get message() {\n return \"Unknown\";\n }\n}\n/**\n * Tagged socket server error that wraps a server error reason and exposes its\n * cause.\n *\n * @stability unstable\n * @category errors\n * @since 4.0.0\n */\nexport class SocketServerError extends /*#__PURE__*/Data.TaggedError(\"SocketServerError\") {\n constructor(props) {\n super({\n ...props,\n cause: props.reason.cause\n });\n }\n /**\n * Marks this value as a socket server error for runtime guards.\n *\n * @stability unstable\n * @since 4.0.0\n */\n [ErrorTypeId] = ErrorTypeId;\n /**\n * Delegates the public message to the underlying socket server error reason.\n *\n * @stability unstable\n * @since 4.0.0\n */\n get message() {\n return this.reason.message;\n }\n}\n//# sourceMappingURL=SocketServer.js.map","import * as Bytes from \"../Bytes.js\";\nimport * as Cause from \"../Cause.js\";\nimport * as Context from \"../Context.js\";\nimport * as Deferred from \"../Deferred.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Exit from \"../Exit.js\";\nimport * as Fiber from \"../Fiber.js\";\nimport { constant, constTrue, constVoid, identity } from \"../Function.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpRouter from \"../http/HttpRouter.js\";\nimport * as HttpServerRequest from \"../http/HttpServerRequest.js\";\nimport * as HttpServerResponse from \"../http/HttpServerResponse.js\";\nimport { reportCauseUnsafe } from \"../internal/effect.js\";\nimport * as Latch from \"../Latch.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Predicate from \"../Predicate.js\";\nimport * as Pull from \"../Pull.js\";\nimport * as Queue from \"../Queue.js\";\nimport * as Runtime from \"../Runtime.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as SchemaIssue from \"../SchemaIssue.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Semaphore from \"../Semaphore.js\";\nimport * as Socket from \"../socket/Socket.js\";\nimport * as SocketServer from \"../socket/SocketServer.js\";\nimport { Stdio } from \"../Stdio.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Transferable from \"../workers/Transferable.js\";\nimport * as WorkerRunner from \"../workers/WorkerRunner.js\";\nimport * as RpcTracing from \"./internal/tracing.js\";\nimport * as Rpc from \"./Rpc.js\";\nimport { constEof, constPong, RequestId, ResponseDefectEncoded } from \"./RpcMessage.js\";\nimport * as RpcSchema from \"./RpcSchema.js\";\nimport * as RpcSerialization from \"./RpcSerialization.js\";\nimport { withRun } from \"./Utils.js\";\n/**\n * Creates an RPC server for an already-decoded message channel, running\n * handlers for a group and sending decoded server responses through\n * `onFromServer`.\n *\n * **Details**\n *\n * If writing a stream `Chunk` fails with anything other than an interruption,\n * the request fails with that cause. `onFromServer` is assumed to have already\n * answered the client and reported it, so nothing else is sent or reported.\n *\n * A request with `isNotification` set runs like any other, but no `Exit`,\n * `Chunk` or `Defect` is sent for it. Its failures are still reported.\n *\n * A request with `discard` set is acknowledged with a successful `Exit` once\n * its handler starts, after the concurrency permit is taken and the\n * middleware has run. Nothing else is sent for it after that, and its\n * failures are only reported. A failure before the acknowledgement is sent as\n * a failed `Exit` for that request.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeNoSerialization = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const enableTracing = options.disableTracing !== true;\n const enableSpanPropagation = options.disableSpanPropagation !== true;\n const supportsAck = options.disableClientAcks !== true;\n const spanPrefix = options.spanPrefix;\n const concurrency = options.concurrency ?? \"unbounded\";\n const disableFatalDefects = options.disableFatalDefects ?? false;\n const services = yield* Effect.context();\n const scope = Context.get(services, Scope.Scope);\n const trackFiber = Fiber.runIn(Scope.forkUnsafe(scope, \"parallel\"));\n const concurrencySemaphore = concurrency === \"unbounded\" ? undefined : yield* Semaphore.make(concurrency);\n const clients = new Map();\n let isShutdown = false;\n const shutdownLatch = Latch.makeUnsafe(false);\n yield* Scope.addFinalizer(scope, Effect.withFiber(parent => {\n isShutdown = true;\n for (const client of clients.values()) {\n client.ended = true;\n if (client.fibers.size === 0) {\n trackFiber(Effect.runForkWith(services)(endClient(client)));\n continue;\n }\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n }\n if (clients.size === 0) {\n return Effect.void;\n }\n return shutdownLatch.await;\n }));\n const disconnect = clientId => Effect.withFiber(parent => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n for (const fiber of client.fibers.values()) {\n fiber.interruptUnsafe(parent.id);\n }\n clients.delete(clientId);\n return Effect.void;\n });\n const write = (clientId, message, opts) => Effect.catchDefect(Effect.withFiber(requestFiber => {\n if (isShutdown) return Effect.interrupt;\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n latches: undefined,\n fibers: new Map(),\n ended: false,\n serverClient: new Rpc.ServerClient(clientId)\n };\n clients.set(clientId, client);\n } else if (client.ended && (message._tag !== \"Interrupt\" && message._tag !== \"Ack\" || !client.fibers.has(message.requestId))) {\n return Effect.interrupt;\n }\n switch (message._tag) {\n case \"Request\":\n {\n return handleRequest(requestFiber, client, message, opts);\n }\n case \"Ack\":\n {\n const latch = client.latches?.get(message.requestId);\n return latch ? Effect.asVoid(latch.open) : Effect.void;\n }\n case \"Interrupt\":\n {\n const fiber = client.fibers.get(message.requestId);\n if (fiber) {\n fiber.interruptUnsafe(requestFiber.id, RpcSchema.ClientAbort.annotation);\n return Effect.void;\n }\n return options.onFromServer({\n _tag: \"Exit\",\n clientId,\n requestId: message.requestId,\n exit: Exit.interrupt()\n });\n }\n case \"Eof\":\n {\n client.ended = true;\n if (client.fibers.size > 0) return Effect.void;\n return endClient(client);\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${message._tag}`);\n }\n }\n }), defect => sendDefect(clients.get(clientId), defect));\n const endClient = client => {\n clients.delete(client.id);\n const write = options.onFromServer({\n _tag: \"ClientEnd\",\n clientId: client.id\n });\n if (isShutdown && clients.size === 0) {\n return Effect.andThen(write, shutdownLatch.open);\n }\n return write;\n };\n const handleRequest = (requestFiber, client, request, opts) => {\n if (client.fibers.has(request.id)) {\n return Effect.interrupt;\n }\n const isNotification = request.isNotification === true;\n const isDiscard = !isNotification && request.discard === true;\n let acknowledged = false;\n // a notification, or a discarded call once it has been acknowledged, gets\n // no reply of any kind\n const respond = exit => isNotification || acknowledged ? Effect.void : options.onFromServer({\n _tag: \"Exit\",\n clientId: client.id,\n requestId: request.id,\n exit\n });\n const rpc = group.requests.get(request.tag);\n const entry = Context.getOrUndefinedUnsafe(services, rpc?.key);\n if (!rpc || !entry) {\n const write = Effect.catchDefect(respond(Exit.die(`Unknown request tag: ${request.tag}`)), defect => sendDefect(client, defect));\n if (!client.ended || client.fibers.size > 0) return write;\n return Effect.ensuring(write, endClient(client));\n }\n const isStream = RpcSchema.isStreamSchema(rpc.successSchema);\n const metadata = {\n rpc,\n client: client.serverClient,\n requestId: request.id,\n remoteParentSpan: enableSpanPropagation && request.traceId && request.spanId ? Tracer.externalSpan({\n traceId: request.traceId,\n spanId: request.spanId,\n sampled: request.sampled\n }) : undefined,\n headers: request.headers,\n payload: request.payload\n };\n let handlerResult;\n // a handler that throws while being constructed never starts, so it is\n // neither streamed nor acknowledged\n let constructionFailed = false;\n try {\n handlerResult = entry.handler(request.payload, metadata);\n } catch (defect) {\n handlerResult = Effect.die(defect);\n constructionFailed = true;\n }\n // a const, so that the narrowing below can be aliased\n const result = handlerResult;\n // if the handler requested forking, then we skip the concurrency control\n const isWrapper = Rpc.isWrapper(result);\n const isFork = isWrapper && result.fork;\n const isUninterruptible = isWrapper && result.uninterruptible;\n // unwrap the fork data type\n const streamOrEffect = isWrapper ? result.value : result;\n // set when a chunk could not be written; the writer has already responded\n let writeFailure;\n let handler = isStream && !constructionFailed ? streamEffect(client, request, streamOrEffect, cause => {\n writeFailure = cause;\n }) : streamOrEffect;\n if (isDiscard && !constructionFailed) {\n // the acknowledgement runs inside the middleware, so it is only sent\n // once the permit is held and the middleware has started the handler\n handler = Effect.andThen(Effect.suspend(() => {\n const ack = respond(Exit.void);\n acknowledged = true;\n return ack;\n }), handler);\n }\n const withMiddleware = rpc.middlewares.size === 0 ? handler : isStream\n // middleware may rewrite or swallow a chunk write failure, so restore it\n ? Effect.flatMap(Effect.exit(applyMiddleware(services, handler, metadata)), exit => writeFailure ? Effect.failCause(writeFailure) : exit) : applyMiddleware(services, handler, metadata);\n let responded = false;\n const scope = Scope.makeUnsafe();\n let deferred = undefined;\n let effect = Effect.onExit(withMiddleware, exit => {\n responded = true;\n let write;\n if (exit._tag === \"Success\") {\n if (Deferred.isDeferred(exit.value)) {\n deferred = exit.value;\n write = Effect.void;\n } else {\n write = respond(exit);\n }\n } else if (writeFailure) {\n // onFromServer has already answered the client and reported the failure\n return Scope.closeUnsafe(scope, exit) ?? Effect.void;\n } else if (!disableFatalDefects &&\n // a notification or a discarded call only ever fails itself\n !isNotification && !isDiscard && Cause.hasDies(exit.cause) && !Cause.hasInterrupts(exit.cause)) {\n write = sendDefect(client, Cause.squash(exit.cause));\n } else {\n write = respond(exit);\n }\n const close = Scope.closeUnsafe(scope, exit);\n if (exit._tag === \"Failure\") {\n reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n }\n return close ? Effect.ensuring(write, close) : write;\n });\n if (opts?.onRequest) {\n effect = opts.onRequest(effect, request);\n }\n const tracing = Context.get(rpc.annotations, Rpc.TracingEnabled);\n if (enableTracing && (tracing === \"both\" || tracing === \"server\")) {\n const parentSpan = Context.getOrUndefined(requestFiber.context, Tracer.ParentSpan);\n effect = Effect.withSpan(effect, RpcTracing.spanName(spanPrefix, request.tag), {\n captureStackTrace: false,\n kind: \"server\",\n attributes: RpcTracing.spanAttributes(request.tag, options.spanAttributes),\n parent: metadata.remoteParentSpan,\n links: enableSpanPropagation && parentSpan ? [{\n span: parentSpan,\n attributes: {}\n }] : undefined\n });\n }\n if (!isFork && concurrencySemaphore) {\n effect = concurrencySemaphore.withPermit(effect);\n }\n const runFork = Effect.runForkWith(Context.add(handlerContext(entry, requestFiber.context), Scope.Scope, scope));\n const fiber = trackFiber(runFork(\n // Register before the handler runs to catch synchronous cancellation.\n Effect.withFiber(fiber => {\n client.fibers.set(request.id, fiber);\n return effect;\n }), isUninterruptible ? {\n uninterruptible: true\n } : undefined));\n fiber.addObserver(function onExit(exit) {\n if (deferred) {\n const fiber = trackFiber(runFork(Effect.onExit(Deferred.await(deferred), exit => {\n // a failure with no reply to carry it is only reported\n if (exit._tag === \"Failure\" && (isNotification || acknowledged)) {\n reportCauseUnsafe(Fiber.getCurrent(), exit.cause);\n }\n return respond(exit);\n })));\n client.fibers.set(request.id, fiber);\n deferred = undefined;\n fiber.addObserver(onExit);\n return;\n }\n if (!responded && !isNotification && !acknowledged && exit._tag === \"Failure\") {\n trackFiber(runFork(respond(Exit.interrupt())));\n }\n client.fibers.delete(request.id);\n client.latches?.delete(request.id);\n if (client.ended && client.fibers.size === 0) {\n trackFiber(runFork(endClient(client)));\n }\n });\n return Effect.void;\n };\n const streamEffect = (client, request, stream, onWriteFailure) => {\n // the chunks of a notification or a discarded call have no reader, so they\n // are neither sent nor acknowledged\n const silent = request.isNotification === true || request.discard === true;\n const writeChunk = values => silent ? Effect.void : Effect.onError(options.onFromServer({\n _tag: \"Chunk\",\n clientId: client.id,\n requestId: request.id,\n values\n }), cause => {\n if (!Cause.hasInterruptsOnly(cause)) onWriteFailure(cause);\n return Effect.void;\n });\n let latch;\n if (supportsAck && !silent) {\n client.latches ??= new Map();\n latch = client.latches.get(request.id);\n if (!latch) {\n latch = Latch.makeUnsafe(false);\n client.latches.set(request.id, latch);\n }\n }\n if (Effect.isEffect(stream)) {\n return stream.pipe(Effect.flatMap(queue => Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.takeAll(queue), values => {\n const write = writeChunk(values);\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.flatMap(write, () => latch.await);\n })),\n step: constVoid\n })), Pull.catchDone(() => Effect.void), Effect.scoped);\n }\n return Stream.runForEachArray(stream, values => {\n const write = writeChunk(values);\n if (!latch) return write;\n latch.closeUnsafe();\n return Effect.andThen(write, latch.await);\n });\n };\n const sendDefect = (client, defect) => Effect.suspend(() => {\n const shouldEnd = client.ended && client.fibers.size === 0;\n const write = options.onFromServer({\n _tag: \"Defect\",\n clientId: client.id,\n defect\n });\n if (!shouldEnd) return write;\n return Effect.andThen(write, endClient(client));\n });\n return identity({\n write,\n disconnect\n });\n});\n// Built-in JSON codecs depend only on the RPC schemas and can be shared.\n// Other factories may capture state at construction, so keep them per server.\nconst isSharedCodecFor = codecFor => codecFor === RpcSerialization.json.codecFor;\nconst sharedRpcCodecs = /*#__PURE__*/new WeakMap();\nconst rpcCodecs = (codecFor, rpc) => {\n const shared = isSharedCodecFor(codecFor);\n let codecs = shared ? sharedRpcCodecs.get(rpc) : undefined;\n if (codecs === undefined) {\n const streamSchemas = RpcSchema.getStreamSchemas(rpc.successSchema);\n const parseOptions = Context.get(rpc.annotations, Rpc.ParseOptions);\n codecs = {\n decode: Schema.decodeUnknownEffect(codecFor(rpc.payloadSchema), parseOptions),\n encodeChunk: Schema.encodeUnknownEffect(codecFor(Schema.NonEmptyArray(Option.isSome(streamSchemas) ? streamSchemas.value.success : Schema.Any)), parseOptions),\n encodeExit: Schema.encodeUnknownEffect(codecFor(Rpc.exitSchema(rpc)), parseOptions)\n };\n if (shared) sharedRpcCodecs.set(rpc, codecs);\n }\n return codecs;\n};\nlet sharedDefectCodecs;\nconst makeDefectCodecs = codecFor => ({\n encodeDefectUnsafe: Schema.encodeSync(codecFor(Schema.Defect())),\n // Unknown tags have no RPC schema, so use a defect-only exit schema.\n encodeUnknownRequestExit: Schema.encodeUnknownEffect(codecFor(Schema.Exit(Schema.Never, Schema.Never, Schema.Defect())))\n});\nconst defectCodecs = codecFor => isSharedCodecFor(codecFor) ? sharedDefectCodecs ??= makeDefectCodecs(codecFor) : makeDefectCodecs(codecFor);\n// Merging the handler entry services with the request fiber services costs\n// O(services), so the merged context is cached per (entry, fiber context)\n// pair. Request fibers on persistent connections keep one context across\n// requests, leaving a single O(1) overlay per request for the request scope.\nconst handlerContextCache = /*#__PURE__*/new WeakMap();\nconst handlerContext = (entry, fiberContext) => {\n let cache = handlerContextCache.get(entry);\n if (cache === undefined) {\n cache = new WeakMap();\n handlerContextCache.set(entry, cache);\n }\n let merged = cache.get(fiberContext);\n if (merged === undefined) {\n merged = Context.merge(entry.context, fiberContext);\n cache.set(fiberContext, merged);\n }\n return merged;\n};\nconst applyMiddleware = (context, handler, options) => {\n for (const service of options.rpc.middlewares) {\n try {\n const middleware = Context.getUnsafe(context, service);\n handler = middleware(handler, options);\n } catch (defect) {\n handler = Effect.die(defect);\n }\n }\n return handler;\n};\n/**\n * Runs an RPC server for a group using the current server `Protocol`, decoding\n * requests, invoking handlers, encoding responses, and managing in-flight\n * request lifetime.\n *\n * **Details**\n *\n * The server consumes `Protocol.disconnects` to interrupt a disconnected\n * client's requests, so use the `onDisconnect` option to observe disconnects\n * instead of taking from that queue.\n *\n * `onRequest` wraps the effect that runs one decoded request: its middleware\n * and handler and, when the handler returns its result directly, the response\n * write. The wrapped effect is interrupted when the request is cancelled, its\n * client disconnects or the server stops. It runs inside the request's tracing\n * span unless tracing is disabled.\n *\n * `onDisconnect` is called for each disconnect reported by the `Protocol`,\n * after the server has requested interruption of that client's in-flight\n * requests. It does not wait for those requests to finish. It is not called\n * when a client ends its input normally, or for clients still connected when\n * the server stops.\n *\n * Each callback runs in its own fiber, so a slow callback does not delay\n * cleanup for other clients, and callbacks may run concurrently. Pending\n * callbacks are interrupted when the server stops. Failures are ignored and\n * logged at `References.UnhandledLogLevel`.\n *\n * `onInvalidRequest` observes unknown tags and invalid payloads, headers or ids\n * that never reach `onRequest` or middleware. It runs on the delivering\n * fiber before the rejection is sent or the notification is logged and dropped.\n * A slow callback delays subsequent messages on that fiber. Callback failures\n * and defects are ignored and logged at `References.UnhandledLogLevel`;\n * rejection responses and notification handling are unchanged.\n *\n * **Gotchas**\n *\n * When a handler succeeds with a `Deferred`, the effect wrapped by\n * `onRequest` ends at that point. The reply is sent once the `Deferred`\n * completes, outside the wrapped effect.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n codecFor,\n disconnects,\n end,\n run,\n send,\n supportsAck,\n supportsSpanPropagation,\n supportsTransferables\n } = yield* Protocol;\n const {\n encodeDefectUnsafe,\n encodeUnknownRequestExit\n } = defectCodecs(codecFor);\n const services = yield* Effect.context();\n const scope = yield* Scope.make();\n const writeOptions = options?.onRequest ? {\n onRequest: options.onRequest\n } : undefined;\n const server = yield* makeNoSerialization(group, {\n ...options,\n disableClientAcks: !supportsAck,\n disableSpanPropagation: !supportsSpanPropagation,\n onFromServer(response) {\n const client = clients.get(response.clientId);\n if (!client) return Effect.void;\n switch (response._tag) {\n case \"Chunk\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n return handleEncode(client, response.requestId, schemas, schemas.encodeChunk(response.values), \"Chunk\");\n }\n case \"Exit\":\n {\n const schemas = client.schemas.get(response.requestId);\n if (!schemas) return Effect.void;\n client.schemas.delete(response.requestId);\n return handleEncode(client, response.requestId, schemas, schemas.encodeExit(response.exit), \"Exit\");\n }\n case \"Defect\":\n {\n return sendDefect(client, response.defect);\n }\n case \"ClientEnd\":\n {\n clients.delete(response.clientId);\n return end(response.clientId);\n }\n }\n }\n }).pipe(Scope.provide(scope));\n // handle disconnects\n const onDisconnect = options?.onDisconnect;\n const handleDisconnect = onDisconnect ? clientId => Effect.andThen(server.disconnect(clientId), Effect.ignoreCause(Effect.suspend(() => onDisconnect(clientId)), {\n log: \"Unhandled\",\n message: \"RpcServer onDisconnect hook failed\"\n }).pipe(Effect.forkIn(scope))) : server.disconnect;\n yield* Effect.forkChild(Effect.whileLoop({\n while: constTrue,\n body: constant(Effect.flatMap(Queue.take(disconnects), clientId => {\n clients.delete(clientId);\n return handleDisconnect(clientId);\n })),\n step: constVoid\n }));\n const schemasCache = new WeakMap();\n const getSchemas = rpc => {\n let schemas = schemasCache.get(rpc);\n if (!schemas) {\n const entry = Context.getOrUndefinedUnsafe(services, rpc.key);\n schemas = {\n tag: rpc._tag,\n ...rpcCodecs(codecFor, rpc),\n context: entry.context\n };\n schemasCache.set(rpc, schemas);\n }\n return schemas;\n };\n // The only successful Exit sent for a discarded call is its acknowledgement,\n // which carries no value, so its Exits are encoded with a void success.\n const discardSchemasCache = new WeakMap();\n const getDiscardSchemas = (rpc, schemas) => {\n let discardSchemas = discardSchemasCache.get(rpc);\n if (!discardSchemas) {\n const exitSchema = Rpc.exitSchema(rpc);\n discardSchemas = {\n ...schemas,\n encodeExit: Schema.encodeUnknownEffect(codecFor(Schema.Exit(Schema.Void, exitSchema.error, exitSchema.defect)), Context.get(rpc.annotations, Rpc.ParseOptions))\n };\n discardSchemasCache.set(rpc, discardSchemas);\n }\n return discardSchemas;\n };\n const clients = new Map();\n const responseEnvelope = (requestId, tag, value) => tag === \"Chunk\" ? {\n _tag: \"Chunk\",\n requestId,\n values: value\n } : {\n _tag: \"Exit\",\n requestId,\n exit: value\n };\n const handleEncode = (client, requestId, schemas, effect, tag) => {\n const collector = schemas.collector;\n let encodeFailed = false;\n // The schema encoders evaluate eagerly, so an encode that needs no\n // services is already a resolved success and can skip the effect wrappers.\n const write = Exit.isExit(effect) && Exit.isSuccess(effect) ? send(client.id, responseEnvelope(requestId, tag, effect.value), collector && collector.clearUnsafe()) : Effect.flatMap(Effect.catch(Effect.provideContext(collector ? Effect.provideService(effect, Transferable.Collector, collector) : effect, schemas.context), error => Effect.withFiber(fiber => {\n const defect = Cause.die(`Failed to encode response for RPC \"${schemas.tag}\": ${SchemaIssue.defaultFormatter(error.issue)}`);\n reportCauseUnsafe(fiber, defect);\n encodeFailed = true;\n return Effect.failCause(defect);\n })), value => send(client.id, responseEnvelope(requestId, tag, value), collector && collector.clearUnsafe()));\n return Effect.catchCause(write, cause => {\n client.schemas.delete(requestId);\n // An encode failure ends the request with the defect, so the request\n // span records it. Other failures stop the request as a cancellation.\n return Effect.andThen(sendRequestDefect(client, requestId, schemas.encodeExit, Cause.squash(cause)), encodeFailed ? Effect.failCause(cause) : server.write(client.id, {\n _tag: \"Interrupt\",\n requestId,\n interruptors: []\n }));\n });\n };\n const sendRequestDefect = (client, requestId, encodeExit, defect) => Effect.catchCause(Effect.flatMap(encodeExit(Exit.die(defect)), exit => send(client.id, responseEnvelope(requestId, \"Exit\", exit))), cause => sendDefect(client, Cause.squash(cause)));\n const sendDefect = (client, defect) => Effect.catchCause(send(client.id, ResponseDefectEncoded(encodeDefectUnsafe(defect))), cause => Effect.annotateLogs(Effect.logDebug(cause), {\n module: \"RpcServer\",\n method: \"sendDefect\"\n }));\n // a notification has no reply to carry the error, so it is only logged\n const dropNotification = reason => Effect.annotateLogs(Effect.logDebug(`Dropped RPC notification: ${reason}`), {\n module: \"RpcServer\",\n method: \"dropNotification\"\n });\n const onInvalidRequest = options?.onInvalidRequest;\n // An invalid id requires a connection-level defect.\n const rejectRequest = (client, request, reason, message, requestId, encodeExit = encodeUnknownRequestExit) => {\n // Preserve the reply decision if the hook mutates the envelope.\n const isNotification = request.isNotification === true;\n // Defer sending until after the hook: `Protocol.send` may write eagerly.\n const reply = () => isNotification ? dropNotification(message) : requestId === undefined ? sendDefect(client, message) : sendRequestDefect(client, requestId, encodeExit, message);\n return onInvalidRequest ? Effect.andThen(Effect.ignoreCause(Effect.suspend(() => onInvalidRequest({\n reason,\n message,\n clientId: client.id,\n request\n })), {\n log: \"Unhandled\",\n message: \"RpcServer onInvalidRequest hook failed\"\n }), reply) : reply();\n };\n const writeDecodedRequest = (client, requestId, schemas, request, payload) => {\n // the headers come from the wire unvalidated, and malformed input makes\n // `Headers.fromInput` throw\n let headers;\n try {\n headers = Headers.fromInput(request.headers);\n } catch {\n return rejectRequest(client, request, \"InvalidHeaders\", \"Invalid request headers\", requestId, schemas.encodeExit);\n }\n // nothing is encoded for a notification, and only a reply would remove its schemas\n if (request.isNotification !== true) {\n client.schemas.set(requestId, supportsTransferables ? {\n ...schemas,\n collector: Transferable.makeCollectorUnsafe()\n } : schemas);\n }\n // the envelope is owned by this protocol loop, so it is decoded in place\n // instead of copied for every request\n const decoded = request;\n decoded.id = requestId;\n decoded.payload = payload;\n decoded.headers = headers;\n return server.write(client.id, decoded, writeOptions);\n };\n let notificationCount = 0;\n // main server loop\n return yield* run((clientId, request) => {\n let client = clients.get(clientId);\n if (!client) {\n client = {\n id: clientId,\n schemas: new Map()\n };\n clients.set(clientId, client);\n }\n switch (request._tag) {\n case \"Request\":\n {\n const tag = Object.hasOwn(request, \"tag\") ? request.tag : \"\";\n const isNotification = request.isNotification === true;\n let requestId;\n if (isNotification) {\n // JSON-RPC notifications share an empty id, and no reply ever names one\n requestId = RequestId(`@effect/rpc/notification/${notificationCount++}`);\n } else {\n switch (typeof request.id) {\n case \"number\":\n case \"string\":\n {\n requestId = RequestId(request.id);\n break;\n }\n default:\n {\n return rejectRequest(client, request, \"InvalidId\", `Invalid request id: ${request.id}`);\n }\n }\n }\n const rpc = group.requests.get(tag);\n if (!rpc) {\n return rejectRequest(client, request, \"UnknownTag\", `Unknown request tag: ${tag}`, requestId);\n }\n const schemas = getSchemas(rpc);\n const replySchemas = !isNotification && request.discard === true ? getDiscardSchemas(rpc, schemas) : schemas;\n const decoded = schemas.decode(request.payload);\n // The schema decoders evaluate eagerly, so a decode that needs no\n // services is already a resolved success and can skip the effect\n // wrappers.\n if (Exit.isExit(decoded) && Exit.isSuccess(decoded)) {\n return writeDecodedRequest(client, requestId, replySchemas, request, decoded.value);\n }\n return Effect.matchEffect(Effect.provideContext(decoded, schemas.context), {\n onFailure: error => rejectRequest(client, request, \"InvalidPayload\", SchemaIssue.defaultFormatter(error.issue), requestId, replySchemas.encodeExit),\n onSuccess: payload => writeDecodedRequest(client, requestId, replySchemas, request, payload)\n });\n }\n case \"Ping\":\n {\n return Effect.catchCause(send(client.id, constPong), cause => sendDefect(client, Cause.squash(cause)));\n }\n case \"Eof\":\n {\n return server.write(clientId, request);\n }\n case \"Ack\":\n {\n // the branded `RequestId` shares the runtime representation of the\n // encoded id, so the message can be forwarded as-is\n return server.write(clientId, request);\n }\n case \"Interrupt\":\n {\n return server.write(clientId, {\n ...request,\n requestId: RequestId(request.requestId),\n interruptors: []\n });\n }\n default:\n {\n return sendDefect(client, `Unknown request tag: ${request._tag}`);\n }\n }\n }).pipe(Effect.tapCause(cause => Effect.logFatal(\"BUG: RpcServer protocol crashed\", cause)), Effect.onExit(exit => Scope.close(scope, exit)));\n});\n/**\n * Provides a scoped layer that starts an RPC server for a group using the\n * current server `Protocol`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = (group, options) => Layer.effectDiscard(Effect.forkScoped(make(group, options)));\n/**\n * Creates a RPC server that registers a HTTP route with a `HttpRouter`.\n *\n * **Details**\n *\n * Defaults to using websockets for communication, but can be configured to use\n * HTTP.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerHttp = options => layer(options.group, options).pipe(Layer.provide(options.protocol === \"http\" ? layerProtocolHttp(options) : layerProtocolWebsocket(options)));\n/**\n * Defines the service interface for an RPC server transport, responsible for receiving\n * encoded client messages, sending encoded responses, tracking clients, and\n * declaring transport capabilities.\n *\n * **When to use**\n *\n * Use to provide the transport boundary for RPC servers over HTTP, WebSocket,\n * workers, sockets, or custom protocols.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class Protocol extends /*#__PURE__*/Context.Service()(\"effect/rpc/RpcServer/Protocol\") {\n /**\n * Creates a server protocol service from the supplied RPC implementation.\n *\n * @stability unstable\n * @since 4.0.0\n */\n static make = /*#__PURE__*/withRun();\n}\n/**\n * Creates a server `Protocol` backed by the current `SocketServer`, accepting\n * socket connections and routing decoded RPC messages.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolSocketServer = /*#__PURE__*/Effect.gen(function* () {\n const server = yield* SocketServer.SocketServer;\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n yield* Effect.forkScoped(server.run(socket => Effect.scoped(onSocket(socket))));\n return protocol;\n});\n/**\n * RPC protocol that uses `SocketServer` for communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolSocketServer = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolSocketServer);\n/**\n * Creates a websocket server `Protocol` together with an HTTP effect that\n * upgrades the current request to a websocket and attaches it to the protocol.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffectWebsocket = /*#__PURE__*/Effect.gen(function* () {\n const {\n onSocket,\n protocol\n } = yield* makeSocketProtocol;\n const httpEffect = Effect.gen(function* () {\n const request = yield* HttpServerRequest.HttpServerRequest;\n const socket = yield* Effect.orDie(request.upgrade);\n yield* onSocket(socket, Object.entries(request.headers));\n return HttpServerResponse.empty();\n });\n return {\n protocol,\n httpEffect\n };\n});\n/**\n * Creates a websocket server `Protocol` and registers its upgrade handler as a\n * GET route on the current `HttpRouter`.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"GET\", options.path, httpEffect);\n return protocol;\n});\n/**\n * RPC protocol that uses WebSockets for communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWebsocket = options => {\n return Layer.effect(Protocol)(makeProtocolWebsocket(options));\n};\n/**\n * Creates an HTTP request/response server `Protocol` together with an HTTP\n * effect that decodes the current request and streams or returns encoded RPC\n * responses.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWithHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (options = {}) {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n const includesFraming = serialization.includesFraming;\n const isBinary = !serialization.contentType.includes(\"json\");\n const disconnects = yield* Queue.make();\n let writeRequest;\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n const encoder = new TextEncoder();\n const httpEffect = Effect.gen(function* () {\n const fiber = Fiber.getCurrent();\n const request = Context.getUnsafe(fiber.context, HttpServerRequest.HttpServerRequest);\n const scope = Context.getUnsafe(fiber.context, Scope.Scope);\n const requestHeaders = Object.entries(request.headers);\n const data = yield* Effect.orDie(isBinary ? Effect.map(request.arrayBuffer, buf => new Uint8Array(buf)) : request.text);\n const id = clientId++;\n const queue = yield* Queue.make({\n capacity: includesFraming && options.streamBufferSize !== \"unbounded\" ? options.streamBufferSize ?? 16 : undefined\n });\n const parser = serialization.makeUnsafe();\n const requestIds = [];\n const offer = data => typeof data === \"string\" ? Queue.offer(queue, encoder.encode(data)) : Queue.offer(queue, data);\n const client = {\n write: !includesFraming ? response =>\n // buffered responses cannot carry notifications, so they are dropped\n response._tag === \"Request\" && response.isNotification === true ? Effect.void : Queue.offer(queue, response) : response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) return Effect.void;\n return offer(encoded);\n } catch (cause) {\n return offer(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause))));\n }\n },\n end: Effect.andThen(Queue.end(queue), Queue.flush(queue))\n };\n // Ends an unfinished response, failing it with `cause` when given, and interrupts its requests.\n const terminate = cause => Effect.suspend(() => {\n if (queue.state._tag === \"Done\") return Effect.void;\n if (cause) Queue.failCauseUnsafe(queue, cause);\n Queue.shutdownUnsafe(queue);\n return Effect.forEach(requestIds, requestId => writeRequest(id, {\n _tag: \"Interrupt\",\n requestId\n }), {\n discard: true\n });\n });\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n Queue.offerUnsafe(disconnects, id);\n return terminate();\n });\n clients.set(id, client);\n clientIds.add(id);\n const dispatch = Effect.gen(function* () {\n // @effect-diagnostics-next-line tryCatchInEffectGen:off\n try {\n const decoded = parser.decode(data);\n for (let i = 0; i < decoded.length; i++) {\n const message = decoded[i];\n if (message._tag === \"Request\") {\n requestIds.push(RequestId(message.id));\n message.headers = requestHeaders.concat(message.headers);\n }\n yield* writeRequest(id, message);\n }\n } catch (cause) {\n yield* client.write(ResponseDefectEncoded(encodeDefectUnsafe(cause)));\n }\n yield* writeRequest(id, constEof);\n });\n if (!includesFraming) {\n yield* dispatch;\n // Allow request aborts during response waits without unmasking response construction.\n const responses = yield* Effect.interruptible(Queue.collect(queue));\n // Notification-only batches encode without a response body.\n const encoded = parser.encode(responses);\n return HttpServerResponse.text(encoded === undefined ? \"\" : encoded, {\n contentType: serialization.contentType\n });\n }\n // Dispatch concurrently so the bounded queue can drain; a failed dispatch fails the response.\n yield* Effect.forkIn(Effect.onError(dispatch, terminate), scope, {\n startImmediately: true\n });\n const initialChunk = yield* Effect.interruptible(Pull.catchDone(Queue.takeAll(queue), () => Effect.succeed([])));\n if (queue.state._tag === \"Done\") {\n // A failed dispatch may have completed the queue after the initial chunk was taken.\n yield* Pull.doneExitFromCause(queue.state.exit.cause);\n return HttpServerResponse.uint8Array(initialChunk.length === 1 ? initialChunk[0] : Bytes.concat(initialChunk), {\n contentType: serialization.contentType\n });\n }\n return HttpServerResponse.stream(Stream.fromArray(initialChunk).pipe(Stream.concat(Stream.fromQueue(queue))), {\n contentType: serialization.contentType\n });\n });\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send(clientId, response) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.write(response);\n },\n end(clientId) {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return client.end;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: false,\n supportsTransferables: false,\n supportsSpanPropagation: false,\n supportsNotifications: includesFraming,\n codecFor: serialization.codecFor\n });\n });\n return {\n protocol,\n httpEffect\n };\n});\n/**\n * Creates an HTTP server `Protocol` and registers its request handler as a POST\n * route on the current `HttpRouter`.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolHttp = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect(options);\n const router = yield* HttpRouter.HttpRouter;\n yield* router.add(\"POST\", options.path, httpEffect);\n return protocol;\n});\n/**\n * Provides a server `Protocol` that uses HTTP POST requests for RPC\n * communication.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolHttp = options => {\n return Layer.effect(Protocol)(makeProtocolHttp(options));\n};\n/**\n * Starts an RPC server for a group and returns the HTTP request/response effect\n * that serves the non-websocket HTTP RPC protocol.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffect = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffect(options);\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Starts an RPC server for a group and returns the HTTP effect that upgrades\n * requests to the websocket RPC protocol.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const toHttpEffectWebsocket = /*#__PURE__*/Effect.fnUntraced(function* (group, options) {\n const {\n httpEffect,\n protocol\n } = yield* makeProtocolWithHttpEffectWebsocket;\n yield* make(group, options).pipe(Effect.provideService(Protocol, protocol), Effect.forkScoped);\n // @effect-diagnostics-next-line returnEffectInGen:off\n return httpEffect;\n});\n/**\n * Creates a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * **Details**\n *\n * The protocol serves a single client with id `0`. When stdout ends, the\n * fiber that created the protocol is interrupted.\n *\n * `onStdinEnd` controls what happens when stdin ends. With `\"drain\"`, the\n * default, in-flight requests run to completion and their responses are\n * written before stdout ends. With `\"interrupt\"`, queued output is flushed\n * and stdout ends, stopping the server and interrupting in-flight requests.\n * Shutdown waits for their finalizers without sending further responses or\n * remote cancellation notifications. This stops the server rather than\n * reporting a client disconnect, so `onDisconnect` is not called.\n *\n * **Gotchas**\n *\n * With `\"drain\"`, a request that never completes, such as a long-running\n * tool call, keeps stdout open and the process alive after stdin ends.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolStdio = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const stdio = yield* Stdio;\n const fiber = Fiber.getCurrent();\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n return yield* Protocol.make(Effect.fnUntraced(function* (writeRequest) {\n const queue = yield* Queue.bounded(8);\n const errors = [];\n const parser = serialization.makeUnsafe({\n onDecodeError: error => errors.push(error)\n });\n const write = response => {\n const encoded = parser.encode(response);\n return encoded === undefined ? Effect.void : Queue.offer(queue, encoded);\n };\n yield* stdio.stdin.pipe(Stream.runForEach(data => {\n let decoded = [];\n try {\n decoded = parser.decode(data);\n } catch (cause) {\n errors.push(cause);\n }\n let i = 0;\n const requests = decoded.length === 0 ? Effect.void : Effect.whileLoop({\n while: () => i < decoded.length,\n body: () => writeRequest(0, decoded[i++]),\n step: constVoid\n });\n if (errors.length === 0) return requests;\n // Answer decode failures instead of failing, which would resubscribe to stdin and lose input.\n return Effect.andThen(Effect.forEach(errors.splice(0), error => write(ResponseDefectEncoded(encodeDefectUnsafe(error))), {\n discard: true\n }), requests);\n }), Effect.sandbox, Effect.tapError(Effect.logError), Effect.retry(Schedule.spaced(500)), Effect.andThen(() => options?.onStdinEnd === \"interrupt\" ? Queue.end(queue) : writeRequest(0, constEof)), Effect.forkScoped);\n yield* Stream.fromQueue(queue).pipe(Stream.run(stdio.stdout()), Effect.retry(Schedule.spaced(500)), Effect.onExit(exit => {\n if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) return Effect.void;\n return Effect.forkDetach(Exit.isSuccess(exit) ? Fiber.interruptAs(fiber, undefined, Context.make(Runtime.InterruptExitCode, 0)) : Fiber.interrupt(fiber), {\n startImmediately: true\n });\n }), Effect.forkScoped);\n return {\n disconnects: yield* Queue.make(),\n send: (_clientId, response) => write(response),\n end(_clientId) {\n return Queue.end(queue);\n },\n clientIds: Effect.succeed(new Set([0])),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n codecFor: serialization.codecFor\n };\n }));\n});\n/**\n * Provides a server `Protocol` that reads RPC messages from `Stdio.stdin` and\n * writes encoded responses to `Stdio.stdout`.\n *\n * **Details**\n *\n * `onStdinEnd` selects whether in-flight requests are drained (the default)\n * or interrupted when stdin ends. See {@link makeProtocolStdio} for the\n * shutdown sequence of each mode.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolStdio = options => Layer.effect(Protocol, makeProtocolStdio(options));\n/**\n * Creates a server `Protocol` backed by `WorkerRunnerPlatform`, routing worker\n * messages to the RPC server and server responses back to workers.\n *\n * @stability unstable\n * @category protocols\n * @since 4.0.0\n */\nexport const makeProtocolWorkerRunner = /*#__PURE__*/Protocol.make(/*#__PURE__*/Effect.fnUntraced(function* (writeRequest) {\n const fiber = Fiber.getCurrent();\n const runner = yield* WorkerRunner.WorkerRunnerPlatform;\n const backing = yield* runner.start();\n const initialMessage = yield* Deferred.make();\n const clientIds = new Set();\n const disconnects = yield* Queue.make();\n yield* backing.run((clientId, message) => {\n clientIds.add(clientId);\n if (message._tag === \"InitialMessage\") {\n return Deferred.succeed(initialMessage, message.value);\n }\n return writeRequest(clientId, message);\n }).pipe(Effect.tapCause(Effect.logError), Effect.onExit(() => Effect.sync(() => {\n fiber.currentDispatcher.scheduleTask(() => fiber.interruptUnsafe(fiber.id), 0);\n })), Effect.forkScoped);\n if (backing.disconnects) {\n yield* Queue.take(backing.disconnects).pipe(Effect.tap(clientId => {\n clientIds.delete(clientId);\n return Queue.offer(disconnects, clientId);\n }), Effect.forever, Effect.forkScoped);\n }\n return {\n disconnects,\n send: backing.send,\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.asSome(Deferred.await(initialMessage)),\n supportsAck: true,\n supportsTransferables: true,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n // Worker protocols use structured clone, so they do not depend on\n // `RpcSerialization`. A binary worker protocol is a separate protocol.\n codecFor: Schema.toCodecJson\n };\n}));\n/**\n * Provides a server `Protocol` backed by the current `WorkerRunnerPlatform`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtocolWorkerRunner = /*#__PURE__*/Layer.effect(Protocol)(makeProtocolWorkerRunner);\n// internal\nconst makeSocketProtocol = /*#__PURE__*/Effect.gen(function* () {\n const serialization = yield* RpcSerialization.RpcSerialization;\n const {\n encodeDefectUnsafe\n } = defectCodecs(serialization.codecFor);\n const disconnects = yield* Queue.make();\n let clientId = 0;\n const clients = new Map();\n const clientIds = new Set();\n let writeRequest;\n const onSocket = Effect.fnUntraced(function* (socket, headers) {\n const scope = yield* Effect.scope;\n const parser = serialization.makeUnsafe();\n const id = clientId++;\n yield* Scope.addFinalizerExit(scope, () => {\n clients.delete(id);\n clientIds.delete(id);\n return Queue.offer(disconnects, id);\n });\n const writer = yield* socket.writer;\n const write = response => {\n try {\n const encoded = parser.encode(response);\n if (encoded === undefined) {\n return Effect.void;\n }\n return Effect.orDie(writer.write(encoded));\n } catch (cause) {\n return Effect.orDie(writer.write(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause)))));\n }\n };\n clients.set(id, {\n write\n });\n clientIds.add(id);\n const processData = data => {\n try {\n const decoded = parser.decode(data);\n if (decoded.length === 0) return Effect.void;\n let i = 0;\n return Effect.whileLoop({\n while: () => i < decoded.length,\n body() {\n const message = decoded[i++];\n if (message._tag === \"Request\" && headers) {\n ;\n message.headers = headers.concat(message.headers);\n }\n return writeRequest(id, message);\n },\n step: constVoid\n });\n } catch (cause) {\n if (Predicate.isTagged(cause, \"MaxBufferSizeExceeded\")) {\n return writer.write(new Socket.CloseEvent(1009, String(cause)));\n }\n return writer.write(parser.encode(ResponseDefectEncoded(encodeDefectUnsafe(cause))));\n }\n };\n yield* Effect.gen(function* () {\n const {\n pull\n } = yield* socket.reader;\n while (true) {\n const frames = yield* pull;\n for (let i = 0; i < frames.length; i++) {\n yield* processData(frames[i]);\n }\n }\n }).pipe(Effect.catchReason(\"SocketError\", \"SocketCloseError\", _ => Effect.void), Effect.orDie);\n });\n const protocol = yield* Protocol.make(writeRequest_ => {\n writeRequest = writeRequest_;\n return Effect.succeed({\n disconnects,\n send: (clientId, response) => {\n const client = clients.get(clientId);\n if (!client) return Effect.void;\n return Effect.orDie(client.write(response));\n },\n end(_clientId) {\n return Effect.void;\n },\n clientIds: Effect.sync(() => clientIds),\n initialMessage: Effect.succeedNone,\n supportsAck: true,\n supportsTransferables: false,\n supportsSpanPropagation: true,\n supportsNotifications: true,\n codecFor: serialization.codecFor\n });\n });\n return {\n protocol,\n onSocket\n };\n});\n//# sourceMappingURL=RpcServer.js.map","/**\n * Node socket server adapters for Effect's unstable socket server API.\n *\n * This module turns `node:net` TCP or Unix-domain servers, `node:tls` servers,\n * and `ws` WebSocket servers into scoped `SocketServer.SocketServer` services.\n * Use the TCP and TLS constructors when handlers should receive a\n * `Socket.Socket` backed by a Node `net.Socket`; use the WebSocket\n * constructors when handlers should receive a `Socket.Socket` backed by `ws`\n * and have access to the per-connection WebSocket and `IncomingMessage`\n * services.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"effect/Context\";\nimport * as Deferred from \"effect/Deferred\";\nimport * as Effect from \"effect/Effect\";\nimport * as Exit from \"effect/Exit\";\nimport * as Fiber from \"effect/Fiber\";\nimport { pipe } from \"effect/Function\";\nimport * as Function from \"effect/Function\";\nimport * as Layer from \"effect/Layer\";\nimport * as NetAddress from \"effect/net/NetAddress\";\nimport * as Scope from \"effect/Scope\";\nimport * as Socket from \"effect/socket/Socket\";\nimport * as SocketServer from \"effect/socket/SocketServer\";\nimport * as Net from \"node:net\";\nimport * as Tls from \"node:tls\";\nimport * as NodeSocket from \"./NodeSocket.js\";\nimport * as NodeWS from \"./NodeWS.js\";\nconst isDeno = \"Deno\" in globalThis;\nconst socketAddressFromNode = address => typeof address === \"string\" ? Effect.succeed(NetAddress.unixPathAddress(address)) : Effect.fromResult(NetAddress.inetAddressFromIpString(address.address, address.port)).pipe(Effect.mapError(cause => new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause\n })\n})));\n/**\n * Service tag for the Node `IncomingMessage` associated with the current\n * WebSocket server connection.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class IncomingMessage extends /*#__PURE__*/Context.Service()(\"@effect/platform-node-shared/NodeSocketServer/IncomingMessage\") {}\n/**\n * Creates a scoped TCP `SocketServer` from a Node `net.Server`, starts\n * listening with the supplied options, queues pending connections until `run`\n * is called, and closes the server when the scope ends.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => makeNetServer({\n listenOptions: options,\n connectionEvent: \"connection\",\n createServer: () => Net.createServer(options)\n});\n/**\n * Provides a TCP `SocketServer` by creating and managing a scoped Node\n * `net.Server` with the supplied server and listen options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/Function.flow(make, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\n/**\n * Creates a scoped TLS `SocketServer` from a Node `tls.Server`, starts\n * listening with the supplied options, queues pending connections until `run`\n * is called, and closes the server when the scope ends.\n *\n * **Details**\n *\n * Connections reach `run` only once their handshake has completed, and the\n * handler receives a `Socket.Socket` backed by the `tls.TLSSocket`, which is\n * also provided as `NodeSocket.NetSocket`. Connections that fail the handshake\n * are destroyed and the server keeps listening.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeTls = options => makeNetServer({\n listenOptions: options,\n connectionEvent: \"secureConnection\",\n createServer: () => {\n const server = Tls.createServer(options);\n server.on(\"tlsClientError\", (_error, socket) => {\n socket.destroy();\n });\n return server;\n }\n});\n/**\n * Provides a TLS `SocketServer` by creating and managing a scoped Node\n * `tls.Server` with the supplied TLS and listen options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerTls = /*#__PURE__*/Function.flow(makeTls, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\n/**\n * Creates a scoped WebSocket `SocketServer` backed by the `ws` package,\n * providing the WebSocket and its Node `IncomingMessage` to connection\n * handlers and closing the server when the scope ends.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const makeWebSocket = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const pendingConnections = new Map();\n const server = yield* Effect.acquireRelease(Effect.sync(() => new NodeWS.WebSocketServer(options)), server => Effect.callback(resume => {\n pendingConnections.forEach(([, remove], conn) => {\n remove();\n conn.terminate();\n });\n server.close(() => resume(Effect.void));\n }));\n function defaultHandler(conn, req) {\n const remove = () => {\n pendingConnections.delete(conn);\n conn.removeEventListener(\"close\", remove);\n };\n pendingConnections.set(conn, [req, remove]);\n conn.addEventListener(\"close\", remove);\n }\n let onConnection = defaultHandler;\n server.on(\"connection\", (conn, req) => {\n // pause immediately so nothing is dropped before a handler acquires the\n // socket's reader\n conn.pause();\n onConnection(conn, req);\n });\n yield* Effect.callback(resume => {\n server.once(\"error\", error => {\n resume(Effect.fail(new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause: error\n })\n })));\n });\n server.once(\"listening\", () => {\n resume(Effect.void);\n });\n });\n const run = Effect.fnUntraced(function* (handler) {\n const scope = yield* Scope.make();\n const services = Context.omit(Scope.Scope)(yield* Effect.context());\n const trackFiber = Fiber.runIn(scope);\n const prevOnConnection = onConnection;\n onConnection = function (conn, req) {\n let context = services;\n context = Context.add(context, IncomingMessage, req);\n context = Context.add(context, Socket.WebSocket, conn);\n pipe(Socket.fromWebSocket(Effect.acquireRelease(Effect.succeed(conn), conn => Effect.sync(() => {\n conn.close();\n })), {\n disableReconnects: true\n }), Effect.flatMap(handler), Effect.ignoreCause({\n log: \"Unhandled\",\n message: \"Unhandled error in SocketServer\"\n }), Effect.runForkWith(context), trackFiber);\n };\n pendingConnections.forEach(([req, remove], conn) => {\n remove();\n onConnection(conn, req);\n });\n return yield* Effect.callback(_resume => {\n return Effect.sync(() => {\n onConnection = prevOnConnection;\n });\n }).pipe(Effect.ensuring(Scope.close(scope, Exit.void)));\n });\n const boundAddress = yield* socketAddressFromNode(server.address());\n return SocketServer.SocketServer.of({\n address: boundAddress,\n run\n });\n});\n/**\n * Provides a WebSocket `SocketServer` backed by the `ws` package and managed\n * with the supplied server options.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerWebSocket = /*#__PURE__*/Function.flow(makeWebSocket, /*#__PURE__*/Layer.effect(SocketServer.SocketServer));\nconst makeNetServer = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const errorDeferred = Deferred.makeUnsafe();\n const pending = new Map();\n function defaultOnConnection(conn) {\n const remove = () => {\n pending.delete(conn);\n conn.off(\"close\", remove);\n conn.off(\"error\", remove);\n };\n pending.set(conn, remove);\n conn.on(\"close\", remove);\n conn.on(\"error\", remove);\n }\n let onConnection = defaultOnConnection;\n // oxlint-disable-next-line prefer-const\n let server;\n yield* Effect.addFinalizer(() => Effect.callback(resume => {\n pending.forEach((remove, conn) => {\n remove();\n conn.destroy();\n });\n server?.close(() => resume(Effect.void));\n }));\n server = options.createServer();\n server.on(options.connectionEvent, conn => {\n // pause immediately so nothing is dropped before a handler acquires the\n // socket's reader. Deno's node:net compatibility layer leaves the socket\n // non-flowing but breaks `readable` events after an explicit pause.\n if (!isDeno) conn.pause();\n onConnection(conn);\n });\n server.on(\"error\", err => Deferred.doneUnsafe(errorDeferred, Exit.fail(err)));\n yield* Effect.callback(resume => {\n server.listen(options.listenOptions, () => resume(Effect.void));\n }).pipe(Effect.raceFirst(Effect.mapError(Deferred.await(errorDeferred), err => new SocketServer.SocketServerError({\n reason: new SocketServer.SocketServerOpenError({\n cause: err\n })\n }))));\n const run = Effect.fnUntraced(function* (handler) {\n const scope = yield* Scope.make();\n const services = Context.omit(Scope.Scope)(yield* Effect.context());\n const trackFiber = Fiber.runIn(scope);\n const prevOnConnection = onConnection;\n onConnection = function (conn) {\n let error;\n conn.on(\"error\", err => {\n error = err;\n });\n pipe(NodeSocket.fromDuplex(Effect.acquireRelease(Effect.suspend(() => {\n if (error) {\n return Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketOpenError({\n kind: \"Unknown\",\n cause: error\n })\n }));\n } else if (conn.closed) {\n return Effect.fail(new Socket.SocketError({\n reason: new Socket.SocketCloseError({\n code: 1000\n })\n }));\n }\n return Effect.succeed(conn);\n }), conn => Effect.sync(() => {\n if (conn.closed === false) {\n conn.destroySoon();\n }\n })), {\n tlsServer: true,\n disableReconnects: true\n }), Effect.flatMap(handler), Effect.ignoreCause({\n log: \"Unhandled\",\n message: \"Unhandled error in SocketServer\"\n }), Effect.runForkWith(Context.add(services, NodeSocket.NetSocket, conn)), trackFiber);\n };\n pending.forEach((remove, conn) => {\n remove();\n onConnection(conn);\n });\n return yield* Effect.callback(_resume => {\n return Effect.suspend(() => {\n onConnection = prevOnConnection;\n return Scope.close(scope, Exit.void);\n });\n });\n });\n const boundAddress = yield* socketAddressFromNode(server.address());\n return SocketServer.SocketServer.of({\n address: boundAddress,\n run\n });\n});\n//# sourceMappingURL=NodeSocketServer.js.map","import * as Runtime from \"effect/Runtime\";\n/**\n * Runs an Effect as the Node process main program, interrupting the fiber on\n * `SIGINT` or `SIGTERM` and invoking the configured teardown to determine the\n * process exit code.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = /*#__PURE__*/Runtime.makeRunMain(({\n fiber,\n teardown\n}) => {\n let receivedSignal = false;\n fiber.addObserver(exit => {\n process.removeListener(\"SIGINT\", onSigint);\n process.removeListener(\"SIGTERM\", onSigint);\n teardown(exit, code => {\n if (receivedSignal || code !== 0) {\n process.exit(code);\n }\n });\n });\n function onSigint() {\n receivedSignal = true;\n fiber.interruptUnsafe(fiber.id);\n }\n process.on(\"SIGINT\", onSigint);\n process.on(\"SIGTERM\", onSigint);\n});\n//# sourceMappingURL=NodeRuntime.js.map","import { Context } from \"effect\";\nimport type { Effect } from \"effect\";\n\nimport type {\n EmbedPayload,\n ModelKey,\n ModelServerError,\n Vectors,\n} from \"#/shared/api/model-server/index.ts\";\n\nexport class Engine extends Context.Service<\n Engine,\n {\n readonly load: (key: ModelKey) => Effect.Effect<void, ModelServerError>;\n readonly embed: (payload: EmbedPayload) => Effect.Effect<Vectors, ModelServerError>;\n }\n>()(\"@r_masseater/masseater-utils/entities/model-engine/model/engine\") {}\n","","","import { Effect, FileSystem, Hash, Path, Schema } from \"effect\";\nimport type { PlatformError } from \"effect\";\nimport { ChildProcess, ChildProcessSpawner } from \"effect/process\";\n\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nimport runtimeLock from \"./runtime-lock.json\" with { type: \"json\" };\nimport runtimeManifest from \"./runtime-manifest.json\" with { type: \"json\" };\n\nconst READY_MARKER = \".ready\";\nconst SUCCESS = 0;\nconst HEX = 16;\n\n/** @internal */\nexport type Services = FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner;\n/** @internal */\nexport type Failure = ModelServerError | PlatformError.PlatformError | Schema.SchemaError;\n\nconst encodeJson = Schema.encodeEffect(Schema.fromJsonString(Schema.Json));\n\nconst npmCi = (directory: string): ChildProcess.Command =>\n ChildProcess.make(\"npm\", [\"ci\", \"--ignore-scripts\", \"--no-audit\", \"--no-fund\"], {\n cwd: directory,\n stdin: \"ignore\",\n stdout: \"inherit\",\n stderr: \"inherit\",\n });\n\nconst writeManifests = Effect.fnUntraced(function* writeManifests(staging: string) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const manifest = yield* encodeJson(runtimeManifest);\n const lock = yield* encodeJson(runtimeLock);\n yield* fs.remove(staging, { recursive: true, force: true });\n yield* fs.makeDirectory(staging, { recursive: true });\n yield* fs.writeFileString(path.join(staging, \"package.json\"), manifest);\n yield* fs.writeFileString(path.join(staging, \"package-lock.json\"), lock);\n});\n\nconst install = Effect.fnUntraced(function* install(\n staging: string,\n): Effect.fn.Return<void, Failure, Services> {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;\n yield* writeManifests(staging);\n yield* spawner.exitCode(npmCi(staging)).pipe(\n Effect.filterOrFail(\n (code) => code === SUCCESS,\n (code) => ModelServerError.make({ message: `npm ci exited with ${code} in ${staging}` }),\n ),\n );\n yield* fs.writeFileString(path.join(staging, READY_MARKER), \"\");\n});\n\nconst runtimeDirectory = Effect.fnUntraced(function* runtimeDirectory(cache: string) {\n const path = yield* Path.Path;\n const lock = yield* encodeJson(runtimeLock);\n return path.join(cache, \"runtime\", Hash.string(lock).toString(HEX));\n});\n\nconst installInto = Effect.fnUntraced(function* installInto(directory: string) {\n const fs = yield* FileSystem.FileSystem;\n const staging = `${directory}.staging-${globalThis.process.pid}`;\n yield* install(staging);\n yield* fs.remove(directory, { recursive: true, force: true });\n yield* fs.rename(staging, directory);\n});\n\n/** @internal */\nexport const ensureRuntime = Effect.fnUntraced(function* ensureRuntime(\n cache: string,\n): Effect.fn.Return<string, Failure, Services> {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const directory = yield* runtimeDirectory(cache);\n const ready = yield* fs.exists(path.join(directory, READY_MARKER));\n if (!ready) {\n yield* installInto(directory);\n }\n return directory;\n});\n","import { Cache, Duration, Effect, Exit, Layer, Path, Predicate, Schema } from \"effect\";\n\nimport { Engine } from \"#/entities/model-engine/index.ts\";\nimport { ModelServerError, VectorsSchema, modelName } from \"#/shared/api/model-server/index.ts\";\nimport type { EmbedPayload, ModelKey, Vectors } from \"#/shared/api/model-server/index.ts\";\n\nimport { ensureRuntime } from \"./runtime.ts\";\nimport type { Services } from \"./runtime.ts\";\n\nconst ENTRY = \"node_modules/@huggingface/transformers/dist/transformers.node.mjs\";\nconst MODEL_CAPACITY = 4;\nconst LIBRARY_CAPACITY = 1;\nconst LIBRARY_KEY = \"transformers\";\n\ninterface Tensor {\n readonly tolist: () => unknown;\n}\n\ninterface TokenizeOptions {\n readonly padding: boolean;\n readonly truncation: boolean;\n readonly max_length: number;\n}\n\ntype Tokenize = (texts: readonly string[], options: TokenizeOptions) => unknown;\n\ntype Run = (inputs: unknown) => Promise<{ readonly sentence_embedding?: Tensor }>;\n\ninterface ModelOptions {\n readonly config: object;\n readonly device: string;\n readonly dtype: string;\n}\n\ninterface Transformers {\n readonly env: object;\n readonly AutoConfig: { readonly from_pretrained: (model: string) => Promise<object> };\n readonly AutoModel: {\n readonly from_pretrained: (model: string, options: ModelOptions) => Promise<Run>;\n };\n readonly AutoTokenizer: { readonly from_pretrained: (model: string) => Promise<Tokenize> };\n}\n\ninterface Loaded {\n readonly run: Run;\n readonly tokenize: Tokenize;\n}\n\nconst isTransformers = (value: unknown): value is Transformers =>\n Predicate.hasProperty(value, \"env\") &&\n Predicate.hasProperty(value, \"AutoConfig\") &&\n Predicate.hasProperty(value, \"AutoModel\") &&\n Predicate.hasProperty(value, \"AutoTokenizer\");\n\nconst failure =\n (doing: string) =>\n (cause: unknown): ModelServerError =>\n ModelServerError.make({ message: `${doing} failed: ${String(cause)}` });\n\nconst attempt = <Value>(\n doing: string,\n run: () => Promise<Value>,\n): Effect.Effect<Value, ModelServerError> => Effect.tryPromise({ try: run, catch: failure(doing) });\n\nconst keepSuccess = (exit: Exit.Exit<unknown, unknown>): Duration.Duration =>\n Exit.match(exit, { onFailure: () => Duration.zero, onSuccess: () => Duration.infinity });\n\nconst importModule = (href: string): Promise<unknown> => import(href);\n\nconst importLibrary = Effect.fnUntraced(function* importLibrary(cache: string) {\n const path = yield* Path.Path;\n const directory = yield* ensureRuntime(cache).pipe(\n Effect.mapError(failure(\"installing the runtime\")),\n );\n const url = yield* path\n .toFileUrl(path.join(directory, ENTRY))\n .pipe(Effect.mapError(failure(\"locating the runtime\")));\n const loaded = yield* attempt(\"importing the runtime\", () => importModule(url.href));\n if (!isTransformers(loaded)) {\n return yield* ModelServerError.make({ message: `${ENTRY} is not transformers.js` });\n }\n Reflect.set(loaded.env, \"cacheDir\", path.join(cache, \"models\"));\n return loaded;\n});\n\nconst textOnly = (config: object): object => {\n Reflect.set(config, \"vision_config\", false);\n Reflect.set(config, \"audio_config\", false);\n return config;\n};\n\nconst loadModel = Effect.fnUntraced(function* loadModel(library: Transformers, key: ModelKey) {\n const config = yield* attempt(\"reading the config\", () =>\n library.AutoConfig.from_pretrained(key.model),\n );\n const options = { config: textOnly(config), device: \"cpu\", dtype: key.dtype };\n const [run, tokenize] = yield* Effect.all(\n [\n attempt(`loading ${modelName(key)}`, () =>\n library.AutoModel.from_pretrained(key.model, options),\n ),\n attempt(\"loading the tokenizer\", () => library.AutoTokenizer.from_pretrained(key.model)),\n ],\n { concurrency: \"unbounded\" },\n );\n return { run, tokenize } satisfies Loaded;\n});\n\nconst decodeVectors = Schema.decodeUnknownEffect(VectorsSchema);\n\nconst embedWith = Effect.fnUntraced(function* embedWith(\n loaded: Loaded,\n payload: EmbedPayload,\n): Effect.fn.Return<Vectors, ModelServerError> {\n const options = { padding: true, truncation: true, max_length: payload.maxTokens };\n const inputs = yield* Effect.try({\n try: () => loaded.tokenize(payload.texts, options),\n catch: failure(\"tokenizing\"),\n });\n const output = yield* attempt(\"embedding\", () => loaded.run(inputs));\n if (!Predicate.isNotUndefined(output.sentence_embedding)) {\n return yield* ModelServerError.make({\n message: `${payload.model} returns no sentence_embedding`,\n });\n }\n return yield* decodeVectors(output.sentence_embedding.tolist()).pipe(\n Effect.mapError(failure(\"reading the embeddings\")),\n );\n});\n\nconst makeEngine = Effect.fnUntraced(function* makeEngine(cache: string) {\n const libraries = yield* Cache.makeWith(\n (key: typeof LIBRARY_KEY) =>\n importLibrary(cache).pipe(Effect.withSpan(\"model-server.runtime\", { attributes: { key } })),\n { capacity: LIBRARY_CAPACITY, timeToLive: keepSuccess, requireServicesAt: \"construction\" },\n );\n const models = yield* Cache.makeWith(\n (key: ModelKey) =>\n Cache.get(libraries, LIBRARY_KEY).pipe(Effect.flatMap((library) => loadModel(library, key))),\n { capacity: MODEL_CAPACITY, timeToLive: keepSuccess },\n );\n const loaded = ({ model, dtype }: ModelKey): Effect.Effect<Loaded, ModelServerError> =>\n Cache.get(models, { model, dtype });\n return Engine.of({\n load: (key) => Effect.asVoid(loaded(key)),\n embed: (payload) => loaded(payload).pipe(Effect.flatMap((model) => embedWith(model, payload))),\n });\n});\n\n/** @internal */\nexport const transformersEngine = (cache: string): Layer.Layer<Engine, never, Services> =>\n Layer.effect(Engine, makeEngine(cache));\n","/**\n * Node.js process runner for Effect programs.\n *\n * This module exports `runMain`, which runs one Effect as the main process\n * fiber in Node.js. It reuses the shared Node runtime runner, including its\n * error reporting, `SIGINT` / `SIGTERM` interruption, and optional teardown\n * behavior.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as NodeRuntime from \"@effect/platform-node-shared/NodeRuntime\";\n/**\n * Helps you run a main effect with built-in error handling, logging, and signal management.\n *\n * **When to use**\n *\n * Use to run a Node.js application's main Effect with structured error\n * handling, log management, interrupt support, or advanced teardown\n * capabilities.\n *\n * **Details**\n *\n * This function launches an Effect as the main entry point, setting exit codes\n * based on success or failure, handling interrupts (e.g., Ctrl+C), and optionally\n * logging errors. By default, it logs errors and uses a \"pretty\" format, but both\n * behaviors can be turned off. You can also provide custom teardown logic to\n * finalize resources or produce different exit codes.\n *\n * The optional configuration object can include:\n * - `disableErrorReporting`: Turn off automatic error logging.\n * - `teardown`: Provide custom finalization logic.\n *\n * @stability unstable\n * @category running\n * @since 4.0.0\n */\nexport const runMain = NodeRuntime.runMain;\n//# sourceMappingURL=NodeRuntime.js.map","/**\n * Fetch-based implementation of the Effect HTTP client service.\n *\n * This module provides an `HttpClient` layer that executes requests through a\n * Web Fetch API implementation. It is the transport to use in browsers, edge\n * runtimes, and Node.js environments where `globalThis.fetch` is available, or\n * anywhere a compatible fetch function can be supplied.\n *\n * Requests with an `Upgrade` header fail with `TransportError` before anything\n * is sent because fetch cannot hand over the connection.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Stream from \"../Stream.js\";\nimport * as Headers from \"./Headers.js\";\nimport * as HttpClient from \"./HttpClient.js\";\nimport * as HttpClientError from \"./HttpClientError.js\";\nimport * as HttpClientResponse from \"./HttpClientResponse.js\";\n/**\n * Context reference for the `fetch` implementation used by the fetch-based HTTP client.\n *\n * **Details**\n *\n * Defaults to `globalThis.fetch`. When not explicitly provided in context,\n * `FetchHttpClient` uses the current `globalThis.fetch` on each request.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const Fetch = /*#__PURE__*/Context.Reference(\"effect/http/FetchHttpClient/Fetch\", {\n defaultValue: () => globalThis.fetch\n});\n/**\n * Context reference controlling stream bodies when the runtime does not support streaming requests.\n *\n * **Details**\n *\n * Defaults to `\"error\"`, which fails with an `EncodeError` without sending the\n * request. Set to `\"buffer\"` to collect the entire stream in memory and send it\n * as a single body instead. Runtimes with streaming support always send the stream.\n *\n * **Gotchas**\n *\n * Buffering keeps the entire upload in memory and can exhaust memory for large\n * or unbounded uploads. Support is detected once, on the first stream body sent,\n * using the global `Request` implementation even when a custom `Fetch` is provided.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport const StreamBodyFallback = /*#__PURE__*/Context.Reference(\"effect/http/FetchHttpClient/StreamBodyFallback\", {\n defaultValue: () => \"error\"\n});\n/**\n * Service that contains default fetch options for the fetch-based HTTP client.\n *\n * **When to use**\n *\n * Use to provide default credentials, cache, redirect, integrity, or other\n * fetch options for outgoing HTTP requests.\n *\n * **Details**\n *\n * Request-specific method, headers, body, and abort signal are supplied by the client when a request is executed.\n *\n * @see {@link HttpClient.followRedirects} for following redirects in the client, which needs `{ redirect: \"manual\" }` here\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class RequestInit extends /*#__PURE__*/Context.Service()(\"effect/http/FetchHttpClient/RequestInit\") {}\n// https://developer.chrome.com/docs/capabilities/web-apis/fetch-streaming-requests\nlet supportsStreamBody;\nconst detectStreamBodySupport = () => {\n try {\n let duplexAccessed = false;\n const body = new ReadableStream();\n const request = new Request(\"https://example.com\", {\n method: \"POST\",\n body,\n get duplex() {\n duplexAccessed = true;\n return \"half\";\n }\n });\n // Bun and Deno preserve the stream without reading the duplex option.\n return (duplexAccessed || request.body === body) && !request.headers.has(\"Content-Type\");\n } catch {\n return false;\n }\n};\nconst fetch = /*#__PURE__*/HttpClient.make((request, url, signal, fiber) => {\n if (request.headers.upgrade !== undefined) {\n return Effect.fail(new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n description: \"fetch cannot send an HTTP upgrade request\"\n })\n }));\n }\n const fetch = Context.getOrUndefined(fiber.context, Fetch);\n const options = Context.getOrUndefined(fiber.context, RequestInit) ?? {};\n let headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers;\n if (headers[\"content-length\"]) {\n headers = Headers.remove(headers, \"content-length\");\n }\n let uploadController;\n const stopUpload = Effect.sync(() => uploadController?.abort());\n const send = body => Effect.map(Effect.tryPromise({\n try: () => {\n const init = {\n ...options,\n method: request.method,\n headers,\n body,\n duplex: typeof ReadableStream !== \"undefined\" && body instanceof ReadableStream ? \"half\" : undefined,\n signal: uploadController ? AbortSignal.any([signal, uploadController.signal]) : signal\n };\n return fetch ? fetch(url, init) : globalThis.fetch(url, init);\n },\n catch: cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.TransportError({\n request,\n cause\n })\n })\n }), response => {\n const original = HttpClientResponse.fromWeb(request, response);\n if (!uploadController) return original;\n if (response.body === null) uploadController.abort();\n // Finishing or releasing either response reader ends the upload, not\n // merely receiving headers. Keep the original response and its caches,\n // and inherit its Web source so `toWeb` hands over the original body.\n return Object.create(original, {\n ...Object.fromEntries([\"arrayBuffer\", \"text\", \"json\", \"formData\", \"urlParamsBody\"].map(key => [key, {\n get: () => Effect.ensuring(original[key], stopUpload)\n }])),\n stream: {\n get: () => Stream.ensuring(original.stream, stopUpload)\n }\n });\n }).pipe(Effect.onError(() => stopUpload));\n switch (request.body._tag) {\n case \"Raw\":\n case \"Uint8Array\":\n return send(request.body.body);\n case \"FormData\":\n return send(request.body.formData);\n case \"Stream\":\n {\n supportsStreamBody ??= detectStreamBodySupport();\n if (supportsStreamBody) {\n uploadController = new AbortController();\n const uploadSignal = AbortSignal.any([signal, uploadController.signal]);\n const stopped = Effect.callback(resume => {\n const onAbort = () => resume(Effect.interrupt);\n if (uploadSignal.aborted) {\n onAbort();\n return;\n }\n uploadSignal.addEventListener(\"abort\", onAbort, {\n once: true\n });\n return Effect.sync(() => uploadSignal.removeEventListener(\"abort\", onAbort));\n });\n return Effect.flatMap(Stream.toReadableStreamEffect(Stream.interruptWhen(request.body.stream, stopped)), send);\n }\n if (fiber.getRef(StreamBodyFallback) === \"error\") {\n return Effect.fail(new HttpClientError.HttpClientError({\n reason: new HttpClientError.EncodeError({\n request,\n description: \"Streaming request bodies are not supported in this runtime\"\n })\n }));\n }\n return Stream.mkArrayBuffer(request.body.stream).pipe(Effect.mapError(cause => new HttpClientError.HttpClientError({\n reason: new HttpClientError.EncodeError({\n request,\n cause\n })\n })), Effect.flatMap(send));\n }\n }\n return send(undefined);\n});\n/**\n * Layer that provides an `HttpClient` implementation backed by the configured\n * `Fetch` function.\n *\n * **When to use**\n *\n * Use when an Effect program should execute `HttpClient` requests through the\n * platform `fetch` implementation, especially in browser, edge, or Node.js\n * runtimes with `globalThis.fetch`.\n *\n * **Details**\n *\n * The layer uses the current `Fetch` reference and optional `RequestInit`\n * service for each request. Request-specific method, headers, body, and abort\n * signal are supplied by the client and override matching `RequestInit` fields.\n *\n * **Gotchas**\n *\n * Fetch behavior comes from the runtime's implementation, so CORS, cookies,\n * redirects, abort handling, and streaming support can vary by platform.\n * `fetch` follows redirects itself by default, so `HttpClient.followRedirects`\n * has no effect unless `RequestInit` sets `redirect: \"manual\"`. Trace\n * propagation is on by default, and a browser preflight fails unless the\n * target allows `b3` and `traceparent`. Stream request bodies are sent as Web\n * streams with `duplex: \"half\"` when the runtime supports it; see\n * `StreamBodyFallback` for the unsupported case. Any `content-length` header is\n * removed before calling `fetch`. Chrome passes the support check but rejects\n * streaming uploads over HTTP/1.1, which surfaces as a `TransportError`, and\n * browsers only deliver the response after the entire request body has been sent.\n *\n * @see {@link Fetch} for supplying the fetch implementation used by this layer\n * @see {@link RequestInit} for default `RequestInit` options applied before request-specific fields\n * @see {@link StreamBodyFallback} for opting into buffering on unsupported runtimes\n * @see {@link HttpClient.TracerPropagationEnabled} for leaving `b3` and `traceparent` off a browser request\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/HttpClient.layerMergedContext(/*#__PURE__*/Effect.succeed(fetch));\n//# sourceMappingURL=FetchHttpClient.js.map","import * as Config from \"../../Config.js\";\nimport * as Schema from \"../../Schema.js\";\nconst exporterList = path => Config.Array(Schema.String, path).pipe(Config.map(_ => _.map(_ => _.toLowerCase().trim()).filter(_ => _ !== \"\")));\nconst headersRecord = path => Config.Record(Schema.String, Schema.StringFromUriComponent, path);\nexport const headers = signal => headersRecord(`OTEL_EXPORTER_OTLP_${signal}_HEADERS`).pipe(Config.orElse(() => headersRecord(\"OTEL_EXPORTER_OTLP_HEADERS\")), Config.withDefault(undefined));\nexport const endpoint = signal => Config.URL(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`).pipe(Config.orElse(() => Config.URL(\"OTEL_EXPORTER_OTLP_ENDPOINT\").pipe(Config.map(url => {\n const slash = url.pathname.endsWith(\"/\") ? \"\" : \"/\";\n url.pathname += `${slash}v1/${signal.toLowerCase()}`;\n return url;\n}))), Config.withDefault(undefined));\nexport const exporters = signal => exporterList(`OTEL_${signal}_EXPORTER`).pipe(Config.withDefault([]));\n//# sourceMappingURL=otlpEnv.js.map","/**\n * Shared batch exporter for OTLP/HTTP observability modules.\n *\n * Signal modules use this exporter to buffer already-encoded telemetry and post\n * it to a configured OTLP endpoint. It owns the scoped transport loop, batching,\n * retry behavior, temporary disabling after repeated failures, and final flush\n * during shutdown.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport { Clock } from \"../Clock.js\";\nimport * as Context from \"../Context.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport { identity } from \"../Function.js\";\nimport * as Headers from \"../http/Headers.js\";\nimport * as HttpClient from \"../http/HttpClient.js\";\nimport * as HttpClientError from \"../http/HttpClientError.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Count from \"../internal/count.js\";\nimport * as Latch from \"../Latch.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as MutableList from \"../MutableList.js\";\nimport * as Result from \"../Result.js\";\nimport * as Schedule from \"../Schedule.js\";\nimport * as Scope from \"../Scope.js\";\nimport * as Version from \"../Version.js\";\n// A missing or invalid Retry-After falls back to a fixed delay.\nconst retryAfterDelay = value => {\n const retryAfter = value === undefined ? undefined : Headers.parseRetryAfter(value);\n if (retryAfter === undefined || Result.isFailure(retryAfter)) {\n return Effect.succeed(Duration.seconds(5));\n }\n return Effect.map(Clock, clock => Headers.retryAfterDelay(retryAfter.success, clock.currentTimeMillisUnsafe()));\n};\nconst policy = /*#__PURE__*/Schedule.forever.pipe(Schedule.passthrough, /*#__PURE__*/Schedule.addDelay(({\n output: error\n}) => {\n if (HttpClientError.isHttpClientError(error) && error.reason._tag === \"StatusCodeError\" && error.reason.response.status === 429) {\n return retryAfterDelay(error.reason.response.headers[\"retry-after\"]);\n }\n return Effect.succeed(Duration.seconds(1));\n}));\n/**\n * Registry of exporter flush operations, used to manually drain buffered\n * telemetry before the surrounding scope closes.\n *\n * **Details**\n *\n * Every exporter created by `make` registers its flush operation here, so a\n * single `flush` drains all signals sharing the registry concurrently while\n * each exporter respects its own `concurrency` limit. For each exporter,\n * `flush` returns once every export already in flight when it was called has\n * settled and every item accepted before the call has been sent or discarded by\n * a failed export (or after one fresh snapshot settles when `exportEmpty` is\n * enabled). `flush` cannot fail and respects each exporter's temporary-disable\n * window. Wrap it with `Effect.timeoutOption` to bound its duration at the call\n * site.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class Flusher extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpExporter/Flusher\") {}\n/**\n * Provides a `Flusher` backed by a fresh registry.\n *\n * **Details**\n *\n * This is intentionally a single module-level constant rather than a factory:\n * layer memoization is keyed by layer instance, so every signal layer\n * referencing this same constant shares one registry per layer build, and one\n * `flush` drains traces, logs and metrics together. A factory returning a new\n * layer per call would silently create one registry per signal.\n *\n * Registration is scoped — an exporter is removed from the registry when its\n * own scope closes. Flushing with an empty registry is a no-op.\n *\n * For each registered exporter, `flush` awaits all exports already in flight\n * when it was called and drains every item accepted before the call (or sends\n * one fresh snapshot when `exportEmpty` is enabled). Interrupting `flush` only\n * stops waiting and does not cancel in-flight exports or drop queued items.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFlusher = /*#__PURE__*/Layer.sync(Flusher, () => {\n const registry = new Set();\n return {\n flush: Effect.suspend(() => {\n if (registry.size === 0) {\n return Effect.void;\n }\n return Effect.forEach(registry, identity, {\n concurrency: \"unbounded\",\n discard: true\n });\n }),\n register: run => Effect.flatMap(Scope.Scope, scope => {\n registry.add(run);\n return Scope.addFinalizer(scope, Effect.sync(() => registry.delete(run)));\n })\n };\n});\n/**\n * Creates a scoped OTLP batch exporter.\n *\n * **Details**\n *\n * The exporter buffers pending pushed items up to `maxQueueSize` (dropping new\n * arrivals on overflow and notifying `onDrop`), sends FIFO batches of at most\n * `maxBatchSize` with up to `concurrency` exports (including retries) in flight\n * at a time, temporarily disables exporting after unhandled failures, and\n * drains remaining items during scope finalization up to `shutdownTimeout`.\n * `maxQueueSize` bounds only pending queued items, not batches already in\n * flight.\n *\n * The export interval starts with the first push and stops once an export\n * empties the buffer, so an idle exporter keeps no timer pending. With\n * `exportEmpty` and batching disabled, it exports on every interval instead.\n *\n * Optional gzip compression uses `HttpClientRequest.compressBody` before the\n * retry loop, so retries reuse the compressed bytes. Bodies smaller than 1KB\n * remain uncompressed. Compression requires runtime `CompressionStream` support;\n * compression failures follow the same temporary-disable behavior as transport\n * failures and do not fail flushing or shutdown.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const services = yield* Effect.context();\n const clock = Context.get(services, Clock);\n const scope = Context.get(services, Scope.Scope);\n const exportInterval = Duration.max(Duration.fromInputUnsafe(options.exportInterval), Duration.zero);\n const batchLimit = options.maxBatchSize === \"disabled\" ? Infinity : Count.normalizeNonEmpty(options.maxBatchSize);\n const maxQueueSize = options.maxQueueSize === undefined || Number.isNaN(options.maxQueueSize) ? Number.isFinite(batchLimit) ? Math.max(2048, batchLimit) : 2048 : Count.normalize(options.maxQueueSize);\n const concurrency = options.concurrency === \"unbounded\" ? Infinity : options.concurrency === undefined || Number.isNaN(options.concurrency) ? 4 : Count.normalizeNonEmpty(options.concurrency);\n const client = Context.get(services, HttpClient.HttpClient).pipe(HttpClient.tap(response => Effect.ignore(response.arrayBuffer)), HttpClient.tapError(error => error.response ? Effect.ignore(error.response.arrayBuffer) : Effect.void), HttpClient.filterStatusOk, HttpClient.transformResponse(Effect.provideService(HttpClient.TracerPropagationEnabled, false)), HttpClient.retryTransient({\n schedule: policy,\n times: 3\n }));\n const exporterUserAgent = `OTel-OTLP-Exporter-JavaScript-Effect-${options.label}/${Version.getCurrentVersion()}`;\n const userHeaders = Headers.fromInput(options.headers);\n const userAgent = userHeaders[\"user-agent\"];\n const headers = Headers.set(userHeaders, \"user-agent\", userAgent ? `${userAgent} ${exporterUserAgent}` : exporterUserAgent);\n const request = HttpClientRequest.post(options.url, {\n headers\n });\n const exportsEmpty = options.maxBatchSize === \"disabled\" && options.exportEmpty === true;\n const queue = MutableList.make();\n let disabledUntil = undefined;\n let closed = false;\n const isDisabled = () => {\n if (disabledUntil === undefined) return false;\n if (clock.currentTimeMillisUnsafe() < disabledUntil) return true;\n disabledUntil = undefined;\n return false;\n };\n const isStopped = () => closed || isDisabled();\n // Progress is counted in items, or in snapshots when `exportsEmpty` is set:\n // `requested` is how far callers asked to drain and `started` is how far the\n // batches dequeued so far reach. `inFlight` maps each working fiber to the\n // offset its batch starts at. Offsets only grow and a `Map` keeps insertion\n // order, so its first entry is the earliest export in flight and everything\n // before it has settled, even when batches complete out of order.\n let requested = 0;\n let started = 0;\n const inFlight = new Map();\n const settled = () => closed ? Infinity : inFlight.values().next().value ?? started;\n const waiters = new Set();\n const notifyWaiters = () => {\n const reached = settled();\n for (const waiter of waiters) {\n if (reached >= waiter.target) {\n waiters.delete(waiter);\n waiter.resume(Effect.void);\n }\n }\n };\n const awaitSettled = target => Effect.callback(resume => {\n if (settled() >= target) return resume(Effect.void);\n const waiter = {\n target,\n resume\n };\n waiters.add(waiter);\n return Effect.sync(() => {\n waiters.delete(waiter);\n });\n });\n // `armed` is open while there is something to export. It changes in the\n // same synchronous step as the queue check, so a push is never stranded.\n const armed = yield* Latch.make(exportsEmpty);\n const wake = yield* Latch.make();\n const exportBatch = items => Effect.suspend(() => {\n const [body, onSuccess] = options.body(items);\n const batchRequest = HttpClientRequest.setBody(request, body);\n // Compress before client.execute so transient retries reuse the encoded bytes.\n const response = options.compression === \"gzip\" ? HttpClientRequest.compressBody(batchRequest, \"gzip\").pipe(Effect.flatMap(client.execute)) : client.execute(batchRequest);\n return response.pipe(Effect.andThen(onSuccess), Effect.withTracerEnabled(false));\n }).pipe(Effect.catchCause(cause => {\n MutableList.clear(queue);\n // Nothing queued or requested will start now. Count it as started so\n // waiters only wait for the exports still in flight.\n requested = started = Math.max(started, requested);\n if (isDisabled()) return Effect.void;\n disabledUntil = clock.currentTimeMillisUnsafe() + 60_000;\n return Effect.logWarning(\"Disabling exporter for 60 seconds\", cause);\n }), Effect.annotateLogs({\n package: \"@effect/opentelemetry\",\n module: options.label\n }));\n // Up to `concurrency` workers run on demand while there is work. The\n // exporter owns them, so interrupting a flush never cancels a request.\n const canStart = () => inFlight.size < concurrency && !isStopped() && (requested > started || queue.length >= batchLimit);\n const workerLoop = Effect.withFiber(fiber => {\n if (!canStart()) return Effect.void;\n const items = MutableList.takeN(queue, batchLimit);\n inFlight.set(fiber, started);\n started += exportsEmpty ? 1 : items.length;\n // `exit` keeps the worker alive if the failure handler itself dies, for\n // example when a logger throws.\n return Effect.exit(exportBatch(items)).pipe(Effect.ensuring(Effect.sync(() => {\n inFlight.delete(fiber);\n if (inFlight.size === 0 && !exportsEmpty && queue.length === 0 && armed.closeUnsafe()) {\n wake.openUnsafe();\n }\n notifyWaiters();\n })), Effect.andThen(workerLoop));\n });\n const runFork = Effect.runForkWith(services);\n // A worker normally claims its batch before `runFork` returns. Stop when it\n // has not, so a scheduler that yields first cannot make this loop spin.\n const startWorkers = () => {\n while (canStart() && inFlight.has(runFork(workerLoop))) {\n // keep starting workers\n }\n };\n // Exports everything accepted so far, or one fresh snapshot, and waits for\n // it to settle together with every export already in flight. During cooldown,\n // no new export starts, but any surviving in-flight export is still awaited.\n const drain = Effect.suspend(() => {\n if (isStopped()) return awaitSettled(started);\n const target = started + (exportsEmpty ? 1 : queue.length);\n requested = Math.max(requested, target);\n startWorkers();\n return awaitSettled(target);\n });\n const timer = Duration.isFinite(exportInterval) ? runFork(Effect.gen(function* () {\n while (true) {\n wake.closeUnsafe();\n yield* armed.await;\n const expired = yield* Effect.race(Effect.as(Effect.sleep(exportInterval), true), Effect.as(wake.await, false));\n if (expired) yield* drain;\n }\n })) : undefined;\n // A single finalizer stops the timer, drains, then stops active workers in\n // that order even in a parallel scope. Workers are interrupted without\n // waiting for them, so shutdown ends at `shutdownTimeout` even if the HTTP\n // client is uninterruptible.\n yield* Scope.addFinalizer(scope, Effect.suspend(() => {\n timer?.interruptUnsafe();\n return drain.pipe(Effect.interruptible, Effect.timeoutOption(options.shutdownTimeout), Effect.andThen(Effect.sync(() => {\n closed = true;\n MutableList.clear(queue);\n notifyWaiters();\n for (const fiber of inFlight.keys()) {\n fiber.interruptUnsafe();\n }\n })));\n }));\n const flusher = yield* Flusher;\n yield* flusher.register(drain);\n return {\n push(data) {\n // With no idle timer, the next push ends the disabled window.\n if (isStopped()) return;\n if (queue.length >= maxQueueSize) {\n options.onDrop?.(1);\n return;\n }\n MutableList.append(queue, data);\n if (queue.length >= batchLimit) {\n startWorkers();\n } else {\n armed.openUnsafe();\n }\n }\n };\n});\n//# sourceMappingURL=OtlpExporter.js.map","/**\n * Builds OTLP resource metadata shared by exported telemetry.\n *\n * An OTLP resource describes the service and other attributes attached to every\n * exported log, metric, or trace. This module builds resources from explicit\n * options or OpenTelemetry environment variables and converts JavaScript values\n * into OTLP attribute values.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Config from \"../Config.js\";\nimport * as Effect from \"../Effect.js\";\nimport { format } from \"../Formatter.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Version from \"../Version.js\";\nconst isBrowser = \"window\" in globalThis || \"importScripts\" in globalThis;\n/**\n * Creates an OTLP resource from service metadata and additional attributes.\n *\n * **Details**\n *\n * Adds `telemetry.sdk.*` defaults and converts custom attributes to OTLP values.\n * Custom attributes override SDK defaults; service options override matching\n * attributes. Omitted service options add no service attributes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = options => ({\n attributes: entriesToAttributes(Object.entries({\n \"telemetry.sdk.name\": \"effect\",\n \"telemetry.sdk.language\": isBrowser ? \"webjs\" : \"nodejs\",\n \"telemetry.sdk.version\": Version.getCurrentVersion(),\n ...options.attributes,\n ...(options.serviceName ? {\n \"service.name\": options.serviceName\n } : undefined),\n ...(options.serviceVersion ? {\n \"service.version\": options.serviceVersion\n } : undefined)\n })),\n droppedAttributesCount: 0\n});\n/**\n * Creates an OTLP resource from explicit options and OpenTelemetry\n * configuration.\n *\n * **When to use**\n *\n * Use when resource metadata may be configured in code or by the deployment\n * environment. To let operators set the service identity, omit `serviceName`,\n * `serviceVersion`, and their matching attributes, then use\n * `OTEL_SERVICE_NAME` and `OTEL_RESOURCE_ATTRIBUTES`.\n *\n * **Details**\n *\n * Explicit `serviceName` and `serviceVersion` options take precedence over\n * matching explicit attributes. Explicit attributes take precedence over\n * environment variables. `OTEL_SERVICE_NAME` and `OTEL_SERVICE_VERSION` take\n * precedence over matching attributes in `OTEL_RESOURCE_ATTRIBUTES`. Missing\n * required configuration is converted to a defect.\n *\n * Keys and values in `OTEL_RESOURCE_ATTRIBUTES` are trimmed, then\n * percent-decoded. Entries with an empty value are kept as `\"\"`; entries\n * without `=` or with an empty key are skipped. When a key is repeated as\n * written, the last entry wins and the earlier ones are not decoded. Invalid\n * percent-encoding in the remaining entries is a `ConfigError` and is\n * converted to a defect.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const fromConfig = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const env = yield* Config.Record(Schema.StringFromUriComponent, Schema.StringFromUriComponent, \"OTEL_RESOURCE_ATTRIBUTES\", {\n trim: true,\n keepEmptyValues: true\n }).pipe(Config.withDefault(undefined));\n const serviceName = options?.serviceName ?? options?.attributes?.[\"service.name\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_NAME\")) ?? env?.[\"service.name\"] ?? (yield* Config.String(\"OTEL_SERVICE_NAME\"));\n const serviceVersion = options?.serviceVersion ?? options?.attributes?.[\"service.version\"] ?? (yield* Config.schema(Schema.UndefinedOr(Schema.String), \"OTEL_SERVICE_VERSION\")) ?? env?.[\"service.version\"];\n const attributes = {\n ...env,\n ...options?.attributes\n };\n delete attributes[\"service.name\"];\n delete attributes[\"service.version\"];\n return make({\n serviceName,\n serviceVersion,\n attributes\n });\n}, Effect.orDie);\n/**\n * Returns the `service.name` attribute from an OTLP resource.\n *\n * **When to use**\n *\n * Use when an OTLP resource is known to contain a string `service.name` and\n * throwing is acceptable if that invariant is broken.\n *\n * **Gotchas**\n *\n * Throws if the resource does not contain a string `service.name` attribute.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const serviceNameUnsafe = resource => {\n const serviceNameAttribute = resource.attributes.find(attr => attr.key === \"service.name\");\n if (!serviceNameAttribute || !serviceNameAttribute.value.stringValue) {\n throw new Error(\"Resource does not contain a service name\");\n }\n return serviceNameAttribute.value.stringValue;\n};\n/**\n * Converts key/value entries into OTLP `KeyValue` attributes.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const entriesToAttributes = entries => {\n const attributes = [];\n for (const [key, value] of entries) {\n attributes.push({\n key,\n value: unknownToAttributeValue(value)\n });\n }\n return attributes;\n};\n// OTLP `intValue` is a signed 64-bit integer\nconst int64Bound = 2 ** 63;\n/**\n * Converts an arbitrary JavaScript value into an OTLP `AnyValue`.\n *\n * **Details**\n *\n * Arrays are converted recursively, primitive values use their matching OTLP\n * fields, and unsupported values are formatted as strings. Integers outside the\n * signed 64-bit range fall back to `doubleValue` for numbers and `stringValue`\n * for bigints.\n *\n * @stability unstable\n * @category attributes\n * @since 4.0.0\n */\nexport const unknownToAttributeValue = value => {\n if (Array.isArray(value)) {\n return {\n arrayValue: {\n values: value.map(unknownToAttributeValue)\n }\n };\n }\n switch (typeof value) {\n case \"string\":\n return {\n stringValue: value\n };\n case \"bigint\":\n return BigInt.asIntN(64, value) === value ? {\n intValue: String(value)\n } : {\n stringValue: String(value)\n };\n case \"number\":\n return Number.isInteger(value) && value >= -int64Bound && value < int64Bound ? {\n // Unsafe integers would be rounded when written as JSON numbers\n intValue: Number.isSafeInteger(value) ? value : String(BigInt(value))\n } : {\n doubleValue: value\n };\n case \"boolean\":\n return {\n boolValue: value\n };\n default:\n return {\n stringValue: format(value)\n };\n }\n};\n//# sourceMappingURL=OtlpResource.js.map","/**\n * Serializes OTLP payloads into HTTP request bodies.\n *\n * Signal exporters build trace, metric, and log data structures in memory. This\n * module provides the service that turns those structures into JSON or protobuf\n * HTTP bodies before they are posted to an OTLP collector.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Context from \"../Context.js\";\nimport * as Base64 from \"../encoding/Base64.js\";\nimport * as HttpBody from \"../http/HttpBody.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as otlpProtobuf from \"./internal/otlpProtobuf.js\";\n/**\n * Service for serializing OTLP traces, metrics, and logs into HTTP request\n * bodies.\n *\n * @stability unstable\n * @category services\n * @since 4.0.0\n */\nexport class OtlpSerialization extends /*#__PURE__*/Context.Service()(\"effect/observability/OtlpSerialization\") {}\n// OTLP/JSON writes non-finite numbers as strings and bytes as base64.\n// The holder is read because Buffer#toJSON runs before the replacer.\nfunction jsonReplacer(key, value) {\n if (typeof value === \"number\" && !Number.isFinite(value)) return String(value);\n if (key === \"bytesValue\" && this[key] instanceof Uint8Array) return Base64.encode(this[key]);\n return value;\n}\nconst jsonBody = data => {\n const json = JSON.stringify(data);\n return HttpBody.text(json.includes(\"null\") || json.includes(\"\\\"bytesValue\\\":\") ? JSON.stringify(data, jsonReplacer) : json, \"application/json\");\n};\n/**\n * Provides `OtlpSerialization` using OTLP/HTTP JSON bodies.\n *\n * **Details**\n *\n * `NaN`, `Infinity` and `-Infinity` are written as the strings OTLP/JSON\n * expects, not as `null`. `bytesValue` data is written as a base64 string.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n traces: spans => jsonBody(spans),\n metrics: metrics => jsonBody(metrics),\n logs: logs => jsonBody(logs)\n});\n/**\n * Provides `OtlpSerialization` using protobuf-encoded OTLP bodies with the\n * `application/x-protobuf` content type.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtobuf = /*#__PURE__*/Layer.succeed(OtlpSerialization, {\n traces: spans => HttpBody.uint8Array(otlpProtobuf.encodeTracesData(spans), \"application/x-protobuf\"),\n metrics: metrics => HttpBody.uint8Array(otlpProtobuf.encodeMetricsData(metrics), \"application/x-protobuf\"),\n logs: logs => HttpBody.uint8Array(otlpProtobuf.encodeLogsData(logs), \"application/x-protobuf\")\n});\n//# sourceMappingURL=OtlpSerialization.js.map","/**\n * Exports Effect log entries over OTLP/HTTP.\n *\n * The logger turns Effect log entries into OTLP log records and sends them to a\n * logs endpoint, such as an OpenTelemetry Collector or vendor OTLP endpoint. It\n * includes log levels, messages, annotations, causes, fiber ids, optional log\n * spans, and current trace/span ids when they are present.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Arr from \"../Array.js\";\nimport * as Cause from \"../Cause.js\";\nimport { Clock } from \"../Clock.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport { filterDisablePropagation } from \"../internal/effect.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Logger from \"../Logger.js\";\nimport * as Option from \"../Option.js\";\nimport { CurrentLogAnnotations, CurrentLogSpans } from \"../References.js\";\nimport * as Version from \"../Version.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Creates an Effect `Logger` that exports log records through OTLP.\n *\n * **Details**\n *\n * The logger serializes records with the configured resource, sends them\n * through the OTLP exporter, and requires `Scope` so pending records can be\n * flushed on shutdown.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const serialization = yield* OtlpSerialization;\n const otelResource = yield* OtlpResource.fromConfig(options.resource);\n const scope = {\n name: \"effect\",\n version: Version.getCurrentVersion()\n };\n const exporter = yield* Exporter.make({\n label: \"OtlpLogger\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n maxBatchSize: options.maxBatchSize ?? 1000,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n exportInterval: options.exportInterval ?? Duration.seconds(1),\n body: data => [serialization.logs({\n resourceLogs: [{\n resource: otelResource,\n scopeLogs: [{\n scope,\n logRecords: data\n }]\n }]\n }), Effect.void],\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n const opts = {\n excludeLogSpans: options.excludeLogSpans ?? false,\n clock: yield* Clock\n };\n return Logger.make(options => {\n exporter.push(makeLogRecord(options, opts));\n });\n});\n/**\n * Layer that installs the OTLP logger created by `make`.\n *\n * **Details**\n *\n * By default the OTLP logger is merged with any existing loggers.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Logger.layer([make(options)], {\n mergeWithExisting: options.mergeWithExisting ?? true\n}).pipe(Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP logs layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Logs are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_LOGS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_LOGS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_LOGS_EXPORTER` has no default, so leaving it unset\n * disables logs.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_LOGS_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"LOGS\"),\n exporters: OtlpEnv.exporters(\"LOGS\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n logsTimeout,\n exportTimeout,\n scheduleDelay,\n maxBatchSize,\n maxQueueSize\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_LOGS_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n logsTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_LOGS_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_BLRP_EXPORT_TIMEOUT\")),\n scheduleDelay: Config.option(Config.Int(\"OTEL_BLRP_SCHEDULE_DELAY\")),\n maxBatchSize: Config.option(Config.Int(\"OTEL_BLRP_MAX_EXPORT_BATCH_SIZE\")),\n maxQueueSize: Config.option(Config.Int(\"OTEL_BLRP_MAX_QUEUE_SIZE\"))\n });\n const shutdownTimeout = Option.firstSomeOf([logsTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n const exportInterval = Option.map(scheduleDelay, _ => Duration.millis(_));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"LOGS\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(exportInterval),\n maxBatchSize: Option.getOrUndefined(maxBatchSize),\n maxQueueSize: Option.getOrUndefined(maxQueueSize),\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n excludeLogSpans: options?.excludeLogSpans,\n mergeWithExisting: options?.mergeWithExisting\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\nconst nanosPerMilli = /*#__PURE__*/BigInt(1_000_000);\nconst makeLogRecord = (options, opts) => {\n const observedTime = opts.clock.currentTimeNanosUnsafe().toString();\n const eventMillis = options.date.getTime();\n const eventTime = (BigInt(eventMillis) * nanosPerMilli).toString();\n const attributes = {\n ...options.fiber.getRef(CurrentLogAnnotations)\n };\n attributes[\"effect.fiberId\"] = options.fiber.id;\n if (!opts.excludeLogSpans) {\n // Outermost spans win duplicate labels.\n for (const [label, startTime] of options.fiber.getRef(CurrentLogSpans)) {\n attributes[`effect.log_span.${label}`] = eventMillis - startTime;\n }\n }\n const errors = Cause.prettyErrors(options.cause, {\n includeCauseInStack: true\n });\n if (errors.length > 0) {\n attributes[\"exception.type\"] = errors[0].name;\n attributes[\"exception.message\"] = errors[0].message;\n attributes[\"exception.stacktrace\"] = errors.map(error => error.stack).join(\"\\n\");\n }\n const message = Arr.ensure(options.message);\n const logRecord = {\n severityNumber: logLevelToSeverityNumber(options.logLevel),\n severityText: options.logLevel,\n timeUnixNano: eventTime,\n observedTimeUnixNano: observedTime,\n attributes: OtlpResource.entriesToAttributes(Object.entries(attributes)),\n body: OtlpResource.unknownToAttributeValue(message.length === 1 ? message[0] : message),\n droppedAttributesCount: 0\n };\n const span = filterDisablePropagation(options.fiber.cache.span);\n if (Option.isSome(span)) {\n logRecord.traceId = span.value.traceId.padStart(32, \"0\");\n logRecord.spanId = span.value.spanId;\n }\n return logRecord;\n};\nconst logLevelToSeverityNumber = logLevel => {\n switch (logLevel) {\n case \"Trace\":\n return ESeverityNumber.SEVERITY_NUMBER_TRACE;\n case \"Debug\":\n return ESeverityNumber.SEVERITY_NUMBER_DEBUG;\n case \"Info\":\n return ESeverityNumber.SEVERITY_NUMBER_INFO;\n case \"Warn\":\n return ESeverityNumber.SEVERITY_NUMBER_WARN;\n case \"Error\":\n return ESeverityNumber.SEVERITY_NUMBER_ERROR;\n case \"Fatal\":\n return ESeverityNumber.SEVERITY_NUMBER_FATAL;\n default:\n return ESeverityNumber.SEVERITY_NUMBER_UNSPECIFIED;\n }\n};\n/**\n * Numerical value of the severity, normalized to values described in Log Data Model.\n */\nconst ESeverityNumber = {\n /** Unspecified. Do NOT use as default */\n SEVERITY_NUMBER_UNSPECIFIED: 0,\n SEVERITY_NUMBER_TRACE: 1,\n SEVERITY_NUMBER_TRACE2: 2,\n SEVERITY_NUMBER_TRACE3: 3,\n SEVERITY_NUMBER_TRACE4: 4,\n SEVERITY_NUMBER_DEBUG: 5,\n SEVERITY_NUMBER_DEBUG2: 6,\n SEVERITY_NUMBER_DEBUG3: 7,\n SEVERITY_NUMBER_DEBUG4: 8,\n SEVERITY_NUMBER_INFO: 9,\n SEVERITY_NUMBER_INFO2: 10,\n SEVERITY_NUMBER_INFO3: 11,\n SEVERITY_NUMBER_INFO4: 12,\n SEVERITY_NUMBER_WARN: 13,\n SEVERITY_NUMBER_WARN2: 14,\n SEVERITY_NUMBER_WARN3: 15,\n SEVERITY_NUMBER_WARN4: 16,\n SEVERITY_NUMBER_ERROR: 17,\n SEVERITY_NUMBER_ERROR2: 18,\n SEVERITY_NUMBER_ERROR3: 19,\n SEVERITY_NUMBER_ERROR4: 20,\n SEVERITY_NUMBER_FATAL: 21,\n SEVERITY_NUMBER_FATAL2: 22,\n SEVERITY_NUMBER_FATAL3: 23,\n SEVERITY_NUMBER_FATAL4: 24\n};\n//# sourceMappingURL=OtlpLogger.js.map","/**\n * Exports Effect metrics over OTLP/HTTP.\n *\n * This module periodically snapshots metrics from the current Effect context,\n * serializes them as OTLP resource metrics, and posts them to a metrics\n * endpoint such as an OpenTelemetry Collector or vendor intake. It is meant for\n * long-running services that already update `Metric` counters, gauges,\n * histograms, frequencies, or summaries. The exporter supports cumulative\n * reporting from a fixed start time and delta reporting from the previous\n * export.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport { Clock } from \"../Clock.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Metric from \"../Metric.js\";\nimport * as Option from \"../Option.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Starts a scoped OTLP metrics exporter.\n *\n * **Details**\n *\n * The exporter snapshots registered Effect metrics on the configured interval, serializes them with the selected aggregation temporality, and flushes during scope finalization up to `shutdownTimeout`.\n * Manual flushing also triggers a snapshot. With delta temporality, each\n * successful export advances the previous-export state, so frequent successful\n * flushes narrow the delta aggregation windows.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const clock = yield* Clock;\n const serialization = yield* OtlpSerialization;\n const startTimeNanos = yield* clock.currentTimeNanos;\n const startTime = String(startTimeNanos);\n const temporality = options.temporality ?? \"cumulative\";\n const resource = yield* OtlpResource.fromConfig(options.resource);\n const metricsScope = {\n name: OtlpResource.serviceNameUnsafe(resource)\n };\n const services = yield* Effect.context();\n // State for delta temporality tracking\n let previousExportTimeNanos = startTimeNanos;\n let previousCounterState = new Map();\n let previousHistogramState = new Map();\n let previousFrequencyState = new Map();\n let snapshotSequence = 0;\n let committedSnapshotSequence = -1;\n const snapshot = () => {\n const snapshot = Metric.snapshotUnsafe(services);\n const currentSnapshotSequence = snapshotSequence++;\n const nowNanos = clock.currentTimeNanosUnsafe();\n const nowTime = String(nowNanos);\n // Only series in this snapshot carry their delta state forward, so removed\n // series do not leak state or report a negative delta when recreated.\n const nextCounterState = new Map();\n const nextHistogramState = new Map();\n const nextFrequencyState = new Map();\n const metricData = [];\n const metricDataByName = new Map();\n const addMetricData = data => {\n metricData.push(data);\n metricDataByName.set(data.name, data);\n };\n const isDelta = temporality === \"delta\";\n const aggregationTemporalityEnum = isDelta ? EAggregationTemporality.AGGREGATION_TEMPORALITY_DELTA : EAggregationTemporality.AGGREGATION_TEMPORALITY_CUMULATIVE;\n const intervalStartTime = isDelta ? String(previousExportTimeNanos) : startTime;\n for (let i = 0, len = snapshot.length; i < len; i++) {\n const state = snapshot[i];\n const unit = toUcumUnit(state.attributes?.unit ?? state.attributes?.time_unit);\n const attributes = state.attributes ? OtlpResource.entriesToAttributes(Object.entries(state.attributes)) : [];\n const metricKey = makeMetricKey(state.id, state.attributes);\n switch (state.type) {\n case \"Counter\":\n {\n const currentCount = state.state.count;\n let reportValue = currentCount;\n if (isDelta) {\n const previousCount = previousCounterState.get(metricKey);\n if (previousCount !== undefined) {\n if (typeof currentCount === \"bigint\" && typeof previousCount === \"bigint\") {\n reportValue = currentCount - previousCount;\n // Handle reset: if current < previous, report current value\n if (state.state.incremental && reportValue < BigInt(0)) {\n reportValue = currentCount;\n }\n } else {\n const curr = Number(currentCount);\n const prev = Number(previousCount);\n reportValue = curr - prev;\n // Handle reset\n if (state.state.incremental && reportValue < 0) {\n reportValue = curr;\n }\n }\n }\n nextCounterState.set(metricKey, currentCount);\n }\n const dataPoint = {\n attributes,\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime\n };\n if (typeof reportValue === \"bigint\") {\n dataPoint.asInt = bigintToInt64(reportValue);\n } else {\n dataPoint.asDouble = reportValue;\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).sum.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n sum: {\n aggregationTemporality: aggregationTemporalityEnum,\n isMonotonic: state.state.incremental,\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Gauge\":\n {\n // Gauges don't have temporality - they always report current value\n const dataPoint = {\n attributes,\n startTimeUnixNano: startTime,\n timeUnixNano: nowTime\n };\n if (typeof state.state.value === \"bigint\") {\n dataPoint.asInt = bigintToInt64(state.state.value);\n } else {\n dataPoint.asDouble = state.state.value;\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).gauge.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n gauge: {\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Histogram\":\n {\n const currentBuckets = {\n boundaries: [],\n counts: []\n };\n let prev = 0;\n for (const [boundary, value] of state.state.buckets) {\n if (boundary === Number.POSITIVE_INFINITY) break;\n currentBuckets.boundaries.push(boundary);\n currentBuckets.counts.push(value - prev);\n prev = value;\n }\n // Derive overflow from the total count, whether or not boundaries include Infinity.\n currentBuckets.counts.push(state.state.count - prev);\n let reportCount = state.state.count;\n let reportSum = state.state.sum;\n let reportBucketCounts = currentBuckets.counts;\n let reportExtrema = true;\n if (isDelta) {\n const previousState = previousHistogramState.get(metricKey);\n if (previousState !== undefined) {\n reportCount = state.state.count - previousState.count;\n reportSum = state.state.sum - previousState.sum;\n reportBucketCounts = currentBuckets.counts.map((c, i) => Math.max(0, c - (previousState.bucketCounts[i] ?? 0)));\n // Cumulative extrema cannot describe a later delta interval.\n reportExtrema = false;\n }\n nextHistogramState.set(metricKey, {\n count: state.state.count,\n sum: state.state.sum,\n bucketCounts: currentBuckets.counts.slice()\n });\n }\n const dataPoint = {\n attributes,\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime,\n count: reportCount,\n ...(reportExtrema ? {\n min: state.state.min,\n max: state.state.max\n } : undefined),\n sum: reportSum,\n bucketCounts: reportBucketCounts,\n explicitBounds: currentBuckets.boundaries\n };\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).histogram.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n histogram: {\n aggregationTemporality: aggregationTemporalityEnum,\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n case \"Frequency\":\n {\n const dataPoints = [];\n const currentOccurrences = new Map();\n for (const [freqKey, value] of state.state.occurrences) {\n currentOccurrences.set(freqKey, value);\n let reportValue = value;\n if (isDelta) {\n const previousOccurrences = previousFrequencyState.get(metricKey);\n if (previousOccurrences !== undefined) {\n const previousValue = previousOccurrences.get(freqKey) ?? 0;\n reportValue = Math.max(0, value - previousValue);\n }\n }\n dataPoints.push({\n attributes: [...attributes, {\n key: \"key\",\n value: {\n stringValue: freqKey\n }\n }],\n startTimeUnixNano: intervalStartTime,\n timeUnixNano: nowTime,\n asInt: reportValue\n });\n }\n if (isDelta) {\n nextFrequencyState.set(metricKey, currentOccurrences);\n }\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).sum.dataPoints.push(...dataPoints);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n sum: {\n aggregationTemporality: aggregationTemporalityEnum,\n isMonotonic: true,\n dataPoints\n }\n });\n }\n break;\n }\n case \"Summary\":\n {\n // Count and sum are lifetime totals, so summaries are always cumulative\n const dataPoint = {\n attributes,\n startTimeUnixNano: startTime,\n timeUnixNano: nowTime,\n count: state.state.count,\n sum: state.state.sum,\n quantileValues: state.state.quantiles.flatMap(([quantile, value]) => value === undefined ? [] : [{\n quantile,\n value\n }])\n };\n if (metricDataByName.has(state.id)) {\n metricDataByName.get(state.id).summary.dataPoints.push(dataPoint);\n } else {\n addMetricData({\n name: state.id,\n description: state.description,\n unit,\n summary: {\n dataPoints: [dataPoint]\n }\n });\n }\n break;\n }\n }\n }\n const body = serialization.metrics({\n resourceMetrics: [{\n resource,\n scopeMetrics: [{\n scope: metricsScope,\n metrics: metricData\n }]\n }]\n });\n const onSuccess = isDelta ? Effect.sync(() => {\n if (currentSnapshotSequence < committedSnapshotSequence) return;\n previousCounterState = nextCounterState;\n previousHistogramState = nextHistogramState;\n previousFrequencyState = nextFrequencyState;\n previousExportTimeNanos = nowNanos;\n committedSnapshotSequence = currentSnapshotSequence;\n }) : Effect.void;\n return [body, onSuccess];\n };\n yield* Exporter.make({\n label: \"OtlpMetrics\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n maxBatchSize: \"disabled\",\n // Each snapshot builds on the last one committed, so they go out one at a time.\n concurrency: 1,\n exportEmpty: true,\n exportInterval: options.exportInterval ?? Duration.seconds(10),\n body: snapshot,\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n});\n/**\n * Layer that starts the OTLP metrics exporter created by `make`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => Layer.effectDiscard(make(options)).pipe(Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP metrics layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Metrics are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_METRICS_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_METRICS_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_METRICS_EXPORTER` has no default, so leaving it unset\n * disables metrics.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_METRICS_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"METRICS\"),\n exporters: OtlpEnv.exporters(\"METRICS\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n metricsTimeout,\n exportTimeout,\n exportInterval,\n temporalityPreference\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_METRICS_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n metricsTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_METRICS_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_METRIC_EXPORT_TIMEOUT\")),\n exportInterval: Config.option(Config.Int(\"OTEL_METRIC_EXPORT_INTERVAL\").pipe(Config.map(Duration.millis))),\n temporalityPreference: Config.option(Config.Literals([\"delta\", \"cumulative\"], \"OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE\"))\n });\n const shutdownTimeout = Option.firstSomeOf([metricsTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"METRICS\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(exportInterval),\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n temporality: Option.getOrUndefined(temporalityPreference)\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\n/** Creates a unique key for a metric including its attributes */\nconst makeMetricKey = (id, attributes) => {\n if (attributes === undefined || Object.keys(attributes).length === 0) {\n return id;\n }\n const sortedEntries = Object.entries(attributes).sort((a, b) => a[0].localeCompare(b[0]));\n return `${id}:${JSON.stringify(sortedEntries)}`;\n};\nconst ucumUnits = /*#__PURE__*/new Map([[\"nanoseconds\", \"ns\"], [\"microseconds\", \"us\"], [\"milliseconds\", \"ms\"], [\"seconds\", \"s\"], [\"bytes\", \"By\"]]);\nconst toUcumUnit = (unit = \"\") => ucumUnits.get(unit) ?? unit;\n/** OTLP/JSON accepts int64 as a decimal string, which keeps values beyond 2^53 exact */\nconst bigintToInt64 = value => Number.isSafeInteger(Number(value)) ? Number(value) : value.toString();\n/**\n * AggregationTemporality defines how a metric aggregator reports aggregated\n * values. It describes how those values relate to the time interval over\n * which they are aggregated.\n */\nconst EAggregationTemporality = {\n AGGREGATION_TEMPORALITY_UNSPECIFIED: 0,\n /** DELTA is an AggregationTemporality for a metric aggregator which reports\n changes since last report time. Successive metrics contain aggregation of\n values from continuous and non-overlapping intervals.\n The values for a DELTA metric are based only on the time interval\n associated with one measurement cycle. There is no dependency on\n previous measurements like is the case for CUMULATIVE metrics.\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n DELTA metric:\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0+1 to\n t_0+2 with a value of 2. */\n AGGREGATION_TEMPORALITY_DELTA: 1,\n /** CUMULATIVE is an AggregationTemporality for a metric aggregator which\n reports changes since a fixed start time. This means that current values\n of a CUMULATIVE metric depend on all previous measurements since the\n start time. Because of this, the sender is required to retain this state\n in some form. If this state is lost or invalidated, the CUMULATIVE metric\n values MUST be reset and a new fixed start time following the last\n reported measurement time sent MUST be used.\n For example, consider a system measuring the number of requests that\n it receives and reports the sum of these requests every second as a\n CUMULATIVE metric:\n 1. The system starts receiving at time=t_0.\n 2. A request is received, the system measures 1 request.\n 3. A request is received, the system measures 1 request.\n 4. A request is received, the system measures 1 request.\n 5. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+1 with a value of 3.\n 6. A request is received, the system measures 1 request.\n 7. A request is received, the system measures 1 request.\n 8. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_0 to\n t_0+2 with a value of 5.\n 9. The system experiences a fault and loses state.\n 10. The system recovers and resumes receiving at time=t_1.\n 11. A request is received, the system measures 1 request.\n 12. The 1 second collection cycle ends. A metric is exported for the\n number of requests received over the interval of time t_1 to\n t_0+1 with a value of 1.\n Note: Even though, when reporting changes since last report time, using\n CUMULATIVE is valid, it is not recommended. This may cause problems for\n systems that do not use start_time to determine when the aggregation\n value was reset (e.g. Prometheus). */\n AGGREGATION_TEMPORALITY_CUMULATIVE: 2\n};\n//# sourceMappingURL=OtlpMetrics.js.map","/**\n * Exports Effect tracing spans over OTLP/HTTP.\n *\n * This module creates a `Tracer.Tracer` backed by the shared OTLP batch\n * exporter, so spans created by Effect tracing APIs can be sent to an\n * OpenTelemetry Collector, vendor endpoint, or local collector. Exported spans\n * include identifiers, parent links, attributes, events, timing, kind, and\n * status information. Use the constructor directly or install it through the\n * provided layer.\n *\n * @stability unstable\n * @since 4.0.0\n */\nimport * as Cause from \"../Cause.js\";\nimport * as Config from \"../Config.js\";\nimport * as Duration from \"../Duration.js\";\nimport * as Effect from \"../Effect.js\";\nimport * as Hex from \"../encoding/Hex.js\";\nimport { flow } from \"../Function.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as Option from \"../Option.js\";\nimport * as Schema from \"../Schema.js\";\nimport * as Tracer from \"../Tracer.js\";\nimport * as Version from \"../Version.js\";\nimport * as OtlpEnv from \"./internal/otlpEnv.js\";\nimport * as Exporter from \"./OtlpExporter.js\";\nimport { entriesToAttributes } from \"./OtlpResource.js\";\nimport * as OtlpResource from \"./OtlpResource.js\";\nimport { OtlpSerialization } from \"./OtlpSerialization.js\";\n/**\n * Creates a `Tracer` that exports ended sampled spans to an OTLP traces endpoint.\n *\n * **Details**\n *\n * Spans are batched using the configured interval and batch size, serialized\n * with `OtlpSerialization`, and flushed when the surrounding `Scope` closes.\n *\n * @stability unstable\n * @category constructors\n * @since 4.0.0\n */\nexport const make = /*#__PURE__*/Effect.fnUntraced(function* (options) {\n const otelResource = yield* OtlpResource.fromConfig(options.resource);\n const serialization = yield* OtlpSerialization;\n const scope = {\n name: \"effect\",\n version: Version.getCurrentVersion()\n };\n const exporter = yield* Exporter.make({\n label: \"OtlpTracer\",\n url: options.url,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.exportInterval ?? Duration.seconds(5),\n maxBatchSize: options.maxBatchSize ?? 1000,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n body(spans) {\n const data = {\n resourceSpans: [{\n resource: otelResource,\n scopeSpans: [{\n scope,\n spans\n }]\n }]\n };\n return [serialization.traces(data), Effect.void];\n },\n shutdownTimeout: options.shutdownTimeout ?? Duration.seconds(3)\n });\n function exportFn(span) {\n if (!span.sampled) return;\n exporter.push(makeOtlpSpan(span));\n }\n const sampler = options.sampler;\n const parentBased = sampler?.parentBased ?? true;\n const isSampled = sampler === undefined ? undefined : span => {\n if (parentBased && Option.isSome(span.parent)) {\n return span.parent.value.sampled;\n }\n if (sampler.ratio >= 1) return true;\n if (sampler.ratio <= 0) return false;\n // Like the OpenTelemetry probability sampler, a trace is kept when the last\n // 56 bits of its ID reach `(1 - ratio) * 2^56`, so every span of a trace\n // gets the same decision. Only the top 52 of those bits are compared, which\n // a double holds exactly. A trace ID without hex digits there is kept.\n const randomness = Number(`0x${span.traceId.slice(-14, -1)}`);\n return Number.isNaN(randomness) || randomness >= (1 - sampler.ratio) * 2 ** 52;\n };\n return Tracer.make({\n span(options) {\n return new SpanImpl(options, exportFn, isSampled);\n },\n context: options.context ? function (primitive, fiber) {\n if (fiber.cache.span === undefined) {\n return primitive[\"~effect/Effect/evaluate\"](fiber);\n }\n return options.context(primitive, fiber.cache.span);\n } : undefined\n });\n});\n/**\n * Provides `Tracer.Tracer` using the OTLP tracer created by `make`.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = /*#__PURE__*/flow(make, /*#__PURE__*/Layer.effect(Tracer.Tracer), /*#__PURE__*/Layer.provideMerge(Exporter.layerFlusher));\n/**\n * Creates an OTLP traces layer from OpenTelemetry configuration.\n *\n * **Details**\n *\n * Traces are exported only when an endpoint is set, through\n * `OTEL_EXPORTER_OTLP_TRACES_ENDPOINT` or `OTEL_EXPORTER_OTLP_ENDPOINT`, and\n * `OTEL_TRACES_EXPORTER` includes `otlp`. Unlike the OpenTelemetry SDK\n * specification, `OTEL_TRACES_EXPORTER` has no default, so leaving it unset\n * disables traces.\n *\n * Compression accepts \"gzip\" or \"none\".\n * `OTEL_EXPORTER_OTLP_TRACES_COMPRESSION` takes precedence over\n * `OTEL_EXPORTER_OTLP_COMPRESSION`, defaulting to \"none\". Gzip uses\n * HttpClientRequest's default minimum body size of 1KB.\n *\n * `OTEL_TRACES_SAMPLER` accepts \"always_on\", \"always_off\", \"traceidratio\",\n * \"parentbased_always_on\", \"parentbased_always_off\" and\n * \"parentbased_traceidratio\", and sets the `sampler` option of `make`. The\n * `traceidratio` samplers keep the share of traces set by\n * `OTEL_TRACES_SAMPLER_ARG`, from 0 to 1, defaulting to 1. Other values, such\n * as \"jaeger_remote\", fail the layer. When `OTEL_TRACES_SAMPLER` is unset, no\n * sampler is used.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Effect.gen(function* () {\n const {\n disabled,\n endpoint,\n exporters\n } = yield* Config.all({\n disabled: Config.Boolean(\"OTEL_SDK_DISABLED\").pipe(Config.withDefault(false)),\n endpoint: OtlpEnv.endpoint(\"TRACES\"),\n exporters: OtlpEnv.exporters(\"TRACES\")\n });\n if (disabled || !endpoint || !exporters.includes(\"otlp\")) {\n return Exporter.layerFlusher;\n }\n const {\n baseCompression,\n compression,\n baseTimeout,\n tracesTimeout,\n exportTimeout,\n scheduleDelay,\n maxBatchSize,\n maxQueueSize,\n samplerName\n } = yield* Config.all({\n baseCompression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_COMPRESSION\")),\n compression: Config.option(Config.Literals([\"gzip\", \"none\"], \"OTEL_EXPORTER_OTLP_TRACES_COMPRESSION\")),\n baseTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TIMEOUT\")),\n tracesTimeout: Config.option(Config.Int(\"OTEL_EXPORTER_OTLP_TRACES_TIMEOUT\")),\n exportTimeout: Config.option(Config.Int(\"OTEL_BSP_EXPORT_TIMEOUT\")),\n scheduleDelay: Config.option(Config.Int(\"OTEL_BSP_SCHEDULE_DELAY\").pipe(Config.map(Duration.millis))),\n maxBatchSize: Config.option(Config.Int(\"OTEL_BSP_MAX_EXPORT_BATCH_SIZE\")),\n maxQueueSize: Config.option(Config.Int(\"OTEL_BSP_MAX_QUEUE_SIZE\")),\n samplerName: Config.option(Config.Literals([\"always_on\", \"always_off\", \"traceidratio\", \"parentbased_always_on\", \"parentbased_always_off\", \"parentbased_traceidratio\"], \"OTEL_TRACES_SAMPLER\"))\n });\n const sampler = Option.isNone(samplerName) ? undefined : {\n ratio: samplerName.value.endsWith(\"traceidratio\") ? yield* Config.schema(Schema.Finite.check(Schema.isBetween({\n minimum: 0,\n maximum: 1\n })), \"OTEL_TRACES_SAMPLER_ARG\").pipe(Config.withDefault(1)) : samplerName.value.endsWith(\"always_on\") ? 1 : 0,\n parentBased: samplerName.value.startsWith(\"parentbased_\")\n };\n const shutdownTimeout = Option.firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe(Option.map(_ => Duration.millis(_)));\n return layer({\n url: endpoint.toString(),\n resource: options?.resource,\n headers: options?.headers ?? (yield* OtlpEnv.headers(\"TRACES\")),\n compression: Option.getOrElse(Option.firstSomeOf([compression, baseCompression]), () => \"none\"),\n exportInterval: Option.getOrUndefined(scheduleDelay),\n maxBatchSize: Option.getOrUndefined(maxBatchSize),\n maxQueueSize: Option.getOrUndefined(maxQueueSize),\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n context: options?.context,\n shutdownTimeout: Option.getOrUndefined(shutdownTimeout),\n sampler\n });\n}).pipe(Effect.orDie, Layer.unwrap);\n// internal\nclass SpanImpl {\n _tag = \"Span\";\n name;\n parent;\n annotations;\n links;\n kind;\n sampled;\n export;\n status;\n _traceId = undefined;\n _spanId = undefined;\n _attributes = undefined;\n _events = undefined;\n constructor(options, exportFn, isSampled) {\n this.name = options.name;\n this.parent = options.parent;\n this.annotations = options.annotations;\n this.links = options.links;\n this.kind = options.kind;\n this.export = exportFn;\n this.sampled = options.sampled && (isSampled === undefined || isSampled(this));\n this.status = {\n _tag: \"Started\",\n startTime: options.startTime\n };\n }\n get traceId() {\n return this._traceId ??= Option.isSome(this.parent) ? this.parent.value.traceId : Hex.random(32);\n }\n get spanId() {\n return this._spanId ??= Hex.random(16);\n }\n get attributes() {\n return this._attributes ??= new Map();\n }\n get events() {\n return this._events ??= [];\n }\n end(endTime, exit) {\n if (this.status._tag === \"Ended\") return;\n this.status = {\n _tag: \"Ended\",\n startTime: this.status.startTime,\n endTime,\n exit\n };\n this.export(this);\n }\n attribute(key, value) {\n if (this.status._tag === \"Ended\") return;\n this.attributes.set(key, value);\n }\n event(name, startTime, attributes) {\n if (this.status._tag === \"Ended\") return;\n this.events.push([name, startTime, attributes]);\n }\n addLinks(links) {\n if (this.status._tag === \"Ended\") return;\n // oxlint-disable-next-line no-restricted-syntax\n this.links.push(...links);\n }\n}\nconst makeOtlpSpan = self => {\n const status = self.status;\n const attributes = self._attributes === undefined ? [] : entriesToAttributes(self._attributes);\n const events = [];\n if (self._events !== undefined) {\n for (let i = 0; i < self._events.length; i++) {\n const [name, startTime, attributes] = self._events[i];\n events.push({\n name,\n timeUnixNano: String(startTime),\n attributes: attributes ? entriesToAttributes(Object.entries(attributes)) : [],\n droppedAttributesCount: 0\n });\n }\n }\n let otelStatus;\n if (status.exit._tag === \"Success\") {\n otelStatus = {\n code: StatusCode.Unset\n };\n } else if (Cause.hasInterruptsOnly(status.exit.cause)) {\n otelStatus = {\n code: StatusCode.Unset\n };\n attributes.push({\n key: \"effect.fiber.interrupted\",\n value: {\n boolValue: true\n }\n });\n } else {\n const errors = Cause.prettyErrors(status.exit.cause, {\n includeCauseInStack: true\n });\n otelStatus = errors.length > 0 ? {\n code: StatusCode.Error,\n message: errors[0].message\n } : {\n code: StatusCode.Unset\n };\n for (const error of errors) {\n events.push({\n name: \"exception\",\n timeUnixNano: String(status.endTime),\n droppedAttributesCount: 0,\n attributes: [{\n \"key\": \"exception.type\",\n \"value\": {\n \"stringValue\": error.name\n }\n }, {\n \"key\": \"exception.message\",\n \"value\": {\n \"stringValue\": error.message\n }\n }, {\n \"key\": \"exception.stacktrace\",\n \"value\": {\n \"stringValue\": error.stack ?? \"No stack trace available\"\n }\n }]\n });\n }\n }\n const links = [];\n for (let i = 0; i < self.links.length; i++) {\n const link = self.links[i];\n links.push({\n traceId: link.span.traceId.padStart(32, \"0\"),\n spanId: link.span.spanId,\n attributes: entriesToAttributes(Object.entries(link.attributes)),\n droppedAttributesCount: 0\n });\n }\n return {\n traceId: self.traceId.padStart(32, \"0\"),\n spanId: self.spanId,\n parentSpanId: Option.isSome(self.parent) ? self.parent.value.spanId : undefined,\n name: self.name,\n kind: SpanKind[self.kind],\n startTimeUnixNano: String(status.startTime),\n endTimeUnixNano: String(status.endTime),\n attributes,\n droppedAttributesCount: 0,\n events,\n droppedEventsCount: 0,\n status: otelStatus,\n links,\n droppedLinksCount: 0\n };\n};\nconst StatusCode = {\n Unset: 0,\n Ok: 1,\n Error: 2\n};\nconst SpanKind = {\n unspecified: 0,\n internal: 1,\n server: 2,\n client: 3,\n producer: 4,\n consumer: 5\n};\n//# sourceMappingURL=OtlpTracer.js.map","import { flow } from \"../Function.js\";\nimport * as HttpClientRequest from \"../http/HttpClientRequest.js\";\nimport * as Layer from \"../Layer.js\";\nimport * as OtlpLogger from \"./OtlpLogger.js\";\nimport * as OtlpMetrics from \"./OtlpMetrics.js\";\nimport * as OtlpSerialization from \"./OtlpSerialization.js\";\nimport * as OtlpTracer from \"./OtlpTracer.js\";\n/**\n * Creates a combined OTLP layer for logs, metrics, and traces.\n *\n * **Details**\n *\n * The layer sends data to `/v1/logs`, `/v1/metrics`, and `/v1/traces` below\n * `baseUrl` and requires an `OtlpSerialization` implementation.\n *\n * The layer provides the `OtlpExporter.Flusher` shared by all three signals,\n * so one `flush` exports their buffered telemetry, for example before a\n * serverless instance is suspended.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layer = options => {\n const base = HttpClientRequest.get(options.baseUrl);\n const url = path => HttpClientRequest.appendUrl(base, path).url;\n return Layer.mergeAll(OtlpLogger.layer({\n url: url(\"/v1/logs\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.loggerExportInterval,\n maxBatchSize: options.maxBatchSize,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n shutdownTimeout: options.shutdownTimeout,\n excludeLogSpans: options.loggerExcludeLogSpans,\n mergeWithExisting: options.loggerMergeWithExisting\n }), OtlpMetrics.layer({\n url: url(\"/v1/metrics\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.metricsExportInterval,\n shutdownTimeout: options.shutdownTimeout,\n temporality: options.metricsTemporality\n }), OtlpTracer.layer({\n url: url(\"/v1/traces\"),\n resource: options.resource,\n headers: options.headers,\n compression: options.compression,\n exportInterval: options.tracerExportInterval,\n maxBatchSize: options.maxBatchSize,\n maxQueueSize: options.maxQueueSize,\n concurrency: options.concurrency,\n onDrop: options.onDrop,\n context: options.tracerContext,\n shutdownTimeout: options.shutdownTimeout,\n sampler: options.tracerSampler\n }));\n};\n/**\n * Creates a combined OTLP layer for logs, metrics, and traces from\n * OpenTelemetry configuration.\n *\n * **Details**\n *\n * Each signal is exported only when an endpoint is set and its own exporter\n * variable includes `otlp`. Unlike the OpenTelemetry SDK specification, the\n * exporter variables have no default, so an endpoint alone exports nothing.\n * To export all three signals:\n *\n * ```sh\n * export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318\n * export OTEL_TRACES_EXPORTER=otlp\n * export OTEL_METRICS_EXPORTER=otlp\n * export OTEL_LOGS_EXPORTER=otlp\n * ```\n *\n * The layer provides the `OtlpExporter.Flusher` shared by all enabled signals.\n * It is provided even when configuration disables every signal, in which case\n * `flush` is a no-op.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerFromConfig = options => Layer.mergeAll(OtlpLogger.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers,\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n excludeLogSpans: options?.loggerExcludeLogSpans,\n mergeWithExisting: options?.loggerMergeWithExisting\n}), OtlpMetrics.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers\n}), OtlpTracer.layerFromConfig({\n resource: options?.resource,\n headers: options?.headers,\n concurrency: options?.concurrency,\n onDrop: options?.onDrop,\n context: options?.tracerContext\n}));\n/**\n * Creates the combined OTLP logs, metrics, and traces layer using JSON\n * serialization.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerJson = /*#__PURE__*/flow(layer, /*#__PURE__*/Layer.provide(OtlpSerialization.layerJson));\n/**\n * Creates the combined OTLP logs, metrics, and traces layer using protobuf\n * serialization.\n *\n * @stability unstable\n * @category layers\n * @since 4.0.0\n */\nexport const layerProtobuf = /*#__PURE__*/flow(layer, /*#__PURE__*/Layer.provide(OtlpSerialization.layerProtobuf));\n//# sourceMappingURL=Otlp.js.map","import { Schema } from \"effect\";\n\nconst TallyFields = Schema.Struct({\n library: Schema.String,\n version: Schema.String,\n kind: Schema.String,\n name: Schema.String,\n calls: Schema.Finite,\n});\n\nexport type Tally = typeof TallyFields.Type;\n\nexport const TallyList = Schema.Array(TallyFields);\n\nexport const SPOOL_ENV = \"USAGE_METER_SPOOL\";\n\nexport const CALLS_METRIC = \"code.usage.calls\";\n\nexport const NO_CALLS = 0;\n","import {\n Array as Arr,\n Effect,\n FileSystem,\n Layer,\n Option,\n Path,\n Random,\n Schema,\n pipe,\n} from \"effect\";\nimport type { Context } from \"effect\";\n\nimport { TallyList } from \"./usage-tally.ts\";\nimport type { Tally } from \"./usage-tally.ts\";\n\nexport interface Seen {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n readonly calls: number;\n}\n\nconst ManifestFields = Schema.Struct({ name: Schema.String, version: Schema.String });\n\ntype Manifest = typeof ManifestFields.Type;\n\ntype Services = FileSystem.FileSystem | Path.Path;\n\nconst MANIFEST = \"package.json\";\n\nconst decodeManifest = Schema.decodeUnknownOption(Schema.fromJsonString(ManifestFields));\n\nconst encodeTallies = Schema.encodeEffect(Schema.fromJsonString(TallyList));\n\nconst manifestAbove = (\n directory: string,\n): Effect.Effect<Option.Option<Manifest>, never, Services> =>\n Effect.gen(function* manifestAboveDirectory() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const text = yield* fs.readFileString(path.join(directory, MANIFEST)).pipe(Effect.option);\n const found = pipe(text, Option.flatMap(decodeManifest));\n const parent = path.dirname(directory);\n if (Option.isSome(found) || parent === directory) {\n return found;\n }\n return yield* manifestAbove(parent);\n });\n\nconst tallyOf = ({\n moduleUrl,\n kind,\n name,\n calls,\n}: Seen): Effect.Effect<Option.Option<Tally>, never, Services> =>\n Effect.gen(function* tallyOfSeen() {\n const path = yield* Path.Path;\n const file = yield* path.fromFileUrl(new URL(moduleUrl)).pipe(Effect.option);\n if (Option.isNone(file)) {\n return Option.none<Tally>();\n }\n const manifest = yield* manifestAbove(path.dirname(file.value));\n return pipe(\n manifest,\n Option.map(({ name: library, version }): Tally => ({ library, version, kind, name, calls })),\n );\n });\n\nconst written = (spool: string, seen: readonly Seen[]): Effect.Effect<void, never, Services> =>\n Effect.gen(function* writeSpool() {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const tallies = yield* Effect.forEach(seen, tallyOf, { concurrency: \"unbounded\" }).pipe(\n Effect.map(Arr.getSomes),\n );\n const text = yield* encodeTallies(tallies);\n const suffix = yield* Random.nextInt;\n yield* fs.makeDirectory(spool, { recursive: true });\n yield* fs.writeFileString(\n path.join(spool, `${String(process.pid)}-${String(suffix)}.json`),\n text,\n );\n }).pipe(Effect.ignore);\n\nconst taggedError = Schema.TaggedError;\n\nclass NodeServicesMissing extends taggedError<\n NodeServicesMissing,\n { readonly brand: unique symbol }\n>()(\"NodeServicesMissing\", { message: Schema.String }) {}\n\nconst nodeServices = Effect.tryPromise({\n try: () => import(\"@effect/platform-node/NodeServices\"),\n catch: () => NodeServicesMissing.make({ message: \"@effect/platform-node could not be loaded\" }),\n}).pipe(Effect.flatMap(({ layer }) => Layer.build(layer)));\n\nexport const spoolWritten =\n (spool: string) =>\n (seen: readonly Seen[]): Effect.Effect<void> =>\n nodeServices.pipe(\n Effect.flatMap((services: Context.Context<Services>) =>\n Effect.provideContext(written(spool, seen), services),\n ),\n Effect.scoped,\n Effect.ignore,\n );\n","import {\n Array as Arr,\n Config,\n Effect,\n Exit,\n Option,\n Predicate,\n Record as Rec,\n String as Str,\n pipe,\n} from \"effect\";\n\nimport { spoolWritten } from \"./usage-spool.ts\";\nimport type { Seen } from \"./usage-spool.ts\";\nimport { NO_CALLS, SPOOL_ENV } from \"./usage-tally.ts\";\n\nexport interface UsageMeter {\n readonly rules: <Name extends string, Rule>(\n rules: Readonly<Record<Name, Rule>>,\n ) => Readonly<Record<Name, Rule>>;\n readonly functions: <Name extends string, Value>(\n functions: Readonly<Record<Name, Value>>,\n ) => Readonly<Record<Name, Value>>;\n readonly plugins: <Plugin extends RulePlugin>(\n plugins: Readonly<Record<string, Plugin>>,\n ) => Readonly<Record<string, Plugin>>;\n readonly within: (prefix: string) => UsageMeter;\n}\n\nexport interface RulePlugin {\n readonly rules?: Readonly<Record<string, unknown>> | undefined;\n}\n\ninterface Declared {\n readonly moduleUrl: string;\n readonly kind: string;\n readonly name: string;\n}\n\ntype Callable = (...args: readonly unknown[]) => unknown;\n\nconst RULE_ENTRIES = [\"create\", \"createOnce\", \"check\", \"linter\", \"fixer\"] as const;\n\nconst RULE = \"rule\";\n\nconst FUNCTION = \"function\";\n\nconst ONE_CALL = 1;\n\nconst PREFIX_SEPARATOR = \"/\";\n\nconst KEY_SEPARATOR = \"\\u0000\";\n\nconst idle: UsageMeter = {\n rules: (rules) => rules,\n functions: (functions) => functions,\n plugins: (plugins) => plugins,\n within: () => idle,\n};\n\nconst declared = new Map<string, Declared>();\n\nconst calls = new Map<string, number>();\n\nconst state = { flushed: false, scheduled: false };\n\nconst spoolSetting = Config.NonEmptyString(SPOOL_ENV).pipe(\n Config.option,\n Effect.runSyncExit,\n Exit.match({\n onSuccess: (value) => value,\n onFailure: () => Option.none<string>(),\n }),\n);\n\nconst isCallable = (value: unknown): value is Callable => Predicate.isFunction(value);\n\nconst keyOf = ({ moduleUrl, kind, name }: Declared): string =>\n Arr.join([moduleUrl, kind, name], KEY_SEPARATOR);\n\nconst countCall = (key: string): void => {\n const next = (calls.get(key) ?? NO_CALLS) + ONE_CALL;\n calls.set(key, next);\n};\n\nconst counted = <Value extends Callable>(key: string, callable: Value): Value =>\n Object.assign(function countedCall(this: unknown, ...args: readonly unknown[]): unknown {\n countCall(key);\n return callable.call(this, ...args);\n }, callable);\n\nconst ruleCounted = <Rule>(key: string, rule: Rule): Rule => {\n if (isCallable(rule)) {\n return counted(key, rule);\n }\n if (!Predicate.isObject(rule)) {\n return rule;\n }\n const entries = pipe(\n RULE_ENTRIES,\n Arr.flatMap((entry) =>\n pipe(\n Option.liftPredicate(Rec.get({ ...rule }, entry), Option.isSome),\n Option.flatMap((found) => Option.liftPredicate(found.value, isCallable)),\n Option.map((callable) => [entry, counted(key, callable)] as const),\n Option.toArray,\n ),\n ),\n );\n if (Arr.isReadonlyArrayEmpty(entries)) {\n return rule;\n }\n return { ...rule, ...Rec.fromEntries(entries) };\n};\n\nconst functionCounted = <Value>(key: string, value: Value): Value => {\n if (isCallable(value)) {\n return counted(key, value);\n }\n return value;\n};\n\nexport const flushUsage: Effect.Effect<void> = Effect.suspend(() => {\n if (state.flushed || Option.isNone(spoolSetting)) {\n return Effect.void;\n }\n state.flushed = true;\n const seen = pipe(\n [...declared],\n Arr.map(([key, exported]): Seen => ({ ...exported, calls: calls.get(key) ?? NO_CALLS })),\n );\n return spoolWritten(spoolSetting.value)(seen);\n});\n\nconst flushOnExit = (): void => {\n if (state.scheduled) {\n return;\n }\n state.scheduled = true;\n process.once(\"beforeExit\", () => {\n Effect.runFork(flushUsage);\n });\n};\n\nconst qualified = (prefix: string, name: string): string =>\n pipe([prefix, name], Arr.filter(Str.isNonEmpty), Arr.join(PREFIX_SEPARATOR));\n\nconst wrapped =\n (moduleUrl: string, prefix: string, kind: string) =>\n <Name extends string, Value>(\n wrap: (key: string, value: Value) => Value,\n ): ((names: Readonly<Record<Name, Value>>) => Readonly<Record<Name, Value>>) =>\n (names) => {\n flushOnExit();\n return pipe(\n names,\n Rec.map((value: Value, name: Name) => {\n const exported: Declared = { moduleUrl, kind, name: qualified(prefix, name) };\n declared.set(keyOf(exported), exported);\n return wrap(keyOf(exported), value);\n }),\n );\n };\n\nconst meterOf = (moduleUrl: string, prefix: string): UsageMeter => {\n const rules: UsageMeter[\"rules\"] = (named) =>\n wrapped(moduleUrl, prefix, RULE)(ruleCounted)(named);\n const plugins: UsageMeter[\"plugins\"] = (named) =>\n pipe(\n named,\n Rec.map((plugin, name) =>\n pipe(\n Option.fromUndefinedOr(plugin.rules),\n Option.match({\n onNone: () => plugin,\n onSome: (pluginRules) => ({\n ...plugin,\n rules: meterOf(moduleUrl, qualified(prefix, name)).rules(pluginRules),\n }),\n }),\n ),\n ),\n );\n return {\n rules,\n functions: (named) => wrapped(moduleUrl, prefix, FUNCTION)(functionCounted)(named),\n plugins,\n within: (inner) => meterOf(moduleUrl, qualified(prefix, inner)),\n };\n};\n\nexport const usageMeter = (moduleUrl: string): UsageMeter =>\n pipe(\n spoolSetting,\n Option.match({\n onNone: () => idle,\n onSome: () => meterOf(moduleUrl, \"\"),\n }),\n );\n","import {\n Array as Arr,\n Cause,\n Option,\n Predicate,\n Record as Rec,\n Runtime,\n String as Str,\n pipe,\n} from \"effect\";\n\nconst TAG = \"_tag\";\n\nconst fieldsOf = (failure: unknown): string =>\n pipe(\n Option.liftPredicate(failure, Predicate.isObject),\n Option.map((object): readonly (readonly [string, unknown])[] => Rec.toEntries({ ...object })),\n Option.getOrElse((): readonly (readonly [string, unknown])[] => []),\n Arr.flatMap(([key, value]) =>\n pipe(\n Option.liftPredicate(value, Predicate.isString),\n Option.filter(() => key !== TAG),\n Option.map((text) => `${key}: ${text}`),\n Option.toArray,\n ),\n ),\n Arr.join(\", \"),\n );\n\nconst describedOf = <Failure>(reason: Cause.Reason<Failure>, name: string): string =>\n pipe(\n Option.liftPredicate(reason, Cause.isFailReason),\n Option.map((failed) => fieldsOf(failed.error)),\n Option.filter(Str.isNonEmpty),\n Option.match({ onNone: () => name, onSome: (fields) => `${name} (${fields})` }),\n );\n\nconst linesOf =\n (serviceName: string) =>\n <Failure>(reason: Cause.Reason<Failure>): readonly string[] =>\n pipe(\n Cause.prettyErrors(Cause.fromReasons([reason])),\n Arr.map((error) => {\n if (Str.isEmpty(error.message)) {\n return `${serviceName}: ${describedOf(reason, error.name)}`;\n }\n if (Cause.isDieReason(reason)) {\n return `${serviceName}: ${error.name}: ${error.message}`;\n }\n return `${serviceName}: ${error.message}`;\n }),\n );\n\n/** @internal */\nexport const reportOf =\n (serviceName: string) =>\n <Failure>(cause: Cause.Cause<Failure>): readonly string[] => {\n if (Cause.hasInterruptsOnly(cause) || !cause.pipe(Cause.squash, Runtime.getErrorReported)) {\n return [];\n }\n return pipe(\n cause.reasons,\n Arr.filter((reason) => !Cause.isInterruptReason(reason)),\n Arr.flatMap(linesOf(serviceName)),\n );\n };\n","import { runMain as nodeRuntimeRunMain } from \"@effect/platform-node/NodeRuntime\";\nimport { layer as nodeServices } from \"@effect/platform-node/NodeServices\";\nimport type { NodeServices } from \"@effect/platform-node/NodeServices\";\nimport { Console, Effect, Layer } from \"effect\";\nimport { FetchHttpClient } from \"effect/http\";\nimport type { HttpClient } from \"effect/http\";\nimport { Otlp, OtlpSerialization } from \"effect/observability\";\n\nimport { flushUsage } from \"#/shared/lib/usage-meter.ts\";\n\nimport { reportOf } from \"./report.ts\";\n\n/** @internal */\nexport type Platform = NodeServices | HttpClient.HttpClient;\n\n/** @internal */\nexport type Run<Provided> = <Success, Failure>(\n program: Effect.Effect<Success, Failure, Platform | Provided>,\n) => void;\n\nconst platform = Layer.mergeAll(nodeServices, FetchHttpClient.layer);\n\nconst runWithTracingAnd =\n <Provided, LayerFailure>({\n serviceName,\n services,\n }: Readonly<{\n serviceName: string;\n services: Layer.Layer<Provided, LayerFailure, Platform>;\n }>): Run<Provided> =>\n (program) => {\n const tracing = Otlp.layerFromConfig({ resource: { serviceName } }).pipe(\n Layer.provide(OtlpSerialization.layerJson),\n Layer.provide(FetchHttpClient.layer),\n );\n const provided = Layer.provideMerge(services, platform);\n const report = reportOf(serviceName);\n nodeRuntimeRunMain(\n Layer.mergeAll(tracing, provided).pipe(\n Layer.build,\n Effect.flatMap((context) => Effect.provideContext(program, context)),\n Effect.scoped,\n Effect.ensuring(flushUsage),\n Effect.tapCause((cause) => {\n const lines = report(cause);\n return Effect.forEach(lines, (line) => Console.error(line), {\n concurrency: 1,\n discard: true,\n });\n }),\n ),\n { disableErrorReporting: true },\n );\n };\n\nconst runWithTracing = (serviceName: string): Run<never> =>\n runWithTracingAnd({ serviceName, services: Layer.empty });\n\n/** @internal */\nexport const runMainWith = runWithTracingAnd;\n\n/** @internal */\nexport const runMain = runWithTracing;\n","import { Clock, Duration, Effect, Ref, Schedule } from \"effect\";\n\nimport { modelName } from \"#/shared/api/model-server/index.ts\";\nimport type { ModelKey } from \"#/shared/api/model-server/index.ts\";\n\nconst IDLE_CHECK_MILLIS = 100;\nconst IDLE_CHECK = Duration.millis(IDLE_CHECK_MILLIS);\nconst STEP = 1;\nconst NONE = 0;\n\n/** @internal */\nexport interface Activity {\n readonly active: Ref.Ref<number>;\n readonly last: Ref.Ref<number>;\n readonly models: Ref.Ref<ReadonlySet<string>>;\n}\n\n/** @internal */\nexport const makeActivity = Effect.fnUntraced(function* makeActivity() {\n const now = yield* Clock.currentTimeMillis;\n const active = yield* Ref.make(NONE);\n const last = yield* Ref.make(now);\n const models = yield* Ref.make<ReadonlySet<string>>(new Set());\n return { active, last, models } satisfies Activity;\n});\n\nconst touch = (activity: Activity): Effect.Effect<void> =>\n Clock.currentTimeMillis.pipe(\n Effect.flatMap((now) => Ref.set(activity.last, now)),\n Effect.andThen(Ref.update(activity.active, (count) => count - STEP)),\n );\n\n/** @internal */\nexport const tracked =\n (activity: Activity) =>\n <Value, Failure>(effect: Effect.Effect<Value, Failure>): Effect.Effect<Value, Failure> =>\n Effect.acquireUseRelease(\n Ref.update(activity.active, (count) => count + STEP),\n () => effect,\n () => touch(activity),\n );\n\n/** @internal */\nexport const remember =\n (activity: Activity) =>\n (key: ModelKey): Effect.Effect<void> =>\n Ref.update(activity.models, (models) => new Set([...models, modelName(key)]));\n\nconst isIdle = (activity: Activity, idle: Duration.Duration): Effect.Effect<boolean> =>\n Effect.all([Ref.get(activity.active), Ref.get(activity.last), Clock.currentTimeMillis], {\n concurrency: 1,\n }).pipe(\n Effect.map(([active, last, now]) => active === NONE && now - last >= Duration.toMillis(idle)),\n );\n\n/** @internal */\nexport const untilIdle =\n (idle: Duration.Duration) =>\n (activity: Activity): Effect.Effect<void> =>\n isIdle(activity, idle).pipe(\n Effect.repeat({ schedule: Schedule.spaced(IDLE_CHECK), until: (done) => done }),\n Effect.asVoid,\n );\n","import { Duration, Effect, FileSystem, Option, Schedule, Schema, pipe } from \"effect\";\nimport type { Scope } from \"effect\";\n\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nconst RETRY_MILLIS = 50;\nconst RETRY = Duration.millis(RETRY_MILLIS);\nconst SIGNAL_PROBE = 0;\nconst UNKNOWN_HOLDER = \"unknown\";\n\nconst isAlive = (pid: number): boolean => {\n try {\n return globalThis.process.kill(pid, SIGNAL_PROBE);\n } catch {\n return false;\n }\n};\n\nconst decodePid = Schema.decodeUnknownOption(\n Schema.FiniteFromString.pipe(Schema.decodeTo(Schema.Int)),\n);\n\nconst holderOf = (\n path: string,\n): Effect.Effect<Option.Option<number>, never, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.readFileString(path)),\n Effect.map(decodePid),\n Effect.orElseSucceed(Option.none),\n );\n\nconst heldBy = (path: string, holder: Option.Option<number>): ModelServerError =>\n ModelServerError.make({\n message: `lock ${path} is held by ${pipe(\n holder,\n Option.map(String),\n Option.getOrElse(() => UNKNOWN_HOLDER),\n )}`,\n });\n\nconst clearStale = Effect.fnUntraced(function* clearStale(path: string) {\n const fs = yield* FileSystem.FileSystem;\n const holder = yield* holderOf(path);\n if (Option.exists(holder, (pid) => !isAlive(pid))) {\n yield* fs.remove(path, { force: true }).pipe(Effect.ignore);\n }\n return yield* heldBy(path, holder);\n});\n\nconst tryAcquire = (path: string): Effect.Effect<void, ModelServerError, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.writeFileString(path, `${globalThis.process.pid}`, { flag: \"wx\" })),\n Effect.catchTag(\"PlatformError\", () => clearStale(path)),\n );\n\nconst release = (path: string): Effect.Effect<void, never, FileSystem.FileSystem> =>\n FileSystem.FileSystem.pipe(\n Effect.flatMap((fs) => fs.remove(path, { force: true })),\n Effect.ignore,\n );\n\nconst acquireWithin = (\n path: string,\n timeout: Duration.Input,\n): Effect.Effect<void, ModelServerError, FileSystem.FileSystem> =>\n tryAcquire(path).pipe(\n Effect.retry(Schedule.spaced(RETRY)),\n Effect.timeoutOrElse({ duration: timeout, orElse: () => tryAcquire(path) }),\n );\n\n/** @internal */\nexport const acquireLock =\n (timeout: Duration.Input) =>\n (path: string): Effect.Effect<void, ModelServerError, FileSystem.FileSystem | Scope.Scope> =>\n Effect.acquireRelease(acquireWithin(path, timeout), () => release(path));\n","import { NodeSocketServer } from \"@effect/platform-node-shared\";\nimport {\n Duration,\n Effect,\n FiberSet,\n FileSystem,\n Layer,\n Option,\n Path,\n Ref,\n Semaphore,\n} from \"effect\";\nimport type { Scope } from \"effect\";\nimport { RpcSerialization, RpcServer } from \"effect/rpc\";\nimport type { SocketServer } from \"effect/socket\";\n\nimport { Engine } from \"#/entities/model-engine/index.ts\";\nimport { probe, ModelRpcs } from \"#/shared/api/model-server/index.ts\";\nimport type {\n EmbedPayload,\n ModelKey,\n ModelServerError,\n Status,\n Vectors,\n Location,\n} from \"#/shared/api/model-server/index.ts\";\n\nimport { makeActivity, remember, tracked, untilIdle } from \"./activity.ts\";\nimport type { Activity } from \"./activity.ts\";\nimport { acquireLock } from \"./lock.ts\";\n\nconst LOCK_TIMEOUT_SECONDS = 10;\nconst LOCK_TIMEOUT = Duration.seconds(LOCK_TIMEOUT_SECONDS);\nconst PRIVATE_DIRECTORY = 0o700;\nconst SINGLE = 1;\n\n/** @internal */\nexport interface ServeOptions {\n readonly location: Location;\n readonly idle: Duration.Duration;\n}\n\nconst statusOf = (activity: Activity): Effect.Effect<Status> =>\n Ref.get(activity.models).pipe(\n Effect.map((models) => ({ pid: globalThis.process.pid, models: [...models] })),\n );\n\nconst makeHandlers = Effect.fnUntraced(function* makeHandlers(activity: Activity) {\n const engine = yield* Engine;\n const serial = yield* Semaphore.make(SINGLE);\n const background = yield* FiberSet.make();\n const exclusive = <Value>(\n effect: Effect.Effect<Value, ModelServerError>,\n ): Effect.Effect<Value, ModelServerError> =>\n effect.pipe(Semaphore.withPermits(serial, SINGLE), tracked(activity));\n const load = (key: ModelKey): Effect.Effect<void, ModelServerError> =>\n exclusive(engine.load(key)).pipe(Effect.andThen(remember(activity)(key)));\n const warm = (key: ModelKey): Effect.Effect<void> =>\n load(key).pipe(Effect.ignore, FiberSet.run(background), Effect.asVoid);\n const remembered = remember(activity);\n const embed = (payload: EmbedPayload): Effect.Effect<Vectors, ModelServerError> => {\n const vectors = exclusive(engine.embed(payload));\n return vectors.pipe(Effect.tap(() => remembered(payload)));\n };\n return ModelRpcs.of({\n Embed: embed,\n Load: load,\n Warm: warm,\n Status: () => statusOf(activity),\n });\n});\n\nconst serverLayer = (\n socket: string,\n activity: Activity,\n): Layer.Layer<never, SocketServer.SocketServerError, Engine> => {\n const handlers = ModelRpcs.toLayer(makeHandlers(activity));\n return RpcServer.layer(ModelRpcs).pipe(\n Layer.provide(handlers),\n Layer.provide(RpcServer.layerProtocolSocketServer),\n Layer.provide(NodeSocketServer.layer({ path: socket })),\n Layer.provide(RpcSerialization.layerNdjson),\n );\n};\n\nconst listen = Effect.fnUntraced(function* listen(\n location: Location,\n activity: Activity,\n scope: Scope.Scope,\n) {\n const fs = yield* FileSystem.FileSystem;\n yield* acquireLock(LOCK_TIMEOUT)(`${location.socket}.lock`);\n const running = yield* probe(location.socket);\n if (Option.isSome(running)) {\n return false;\n }\n yield* fs.remove(location.socket, { force: true });\n yield* Layer.buildWithScope(serverLayer(location.socket, activity), scope);\n return true;\n}, Effect.scoped);\n\n/** @internal */\nexport const serve = Effect.fnUntraced(function* serve({ location, idle }: ServeOptions) {\n const fs = yield* FileSystem.FileSystem;\n const path = yield* Path.Path;\n const scope = yield* Effect.scope;\n yield* fs.makeDirectory(path.dirname(location.socket), {\n recursive: true,\n mode: PRIVATE_DIRECTORY,\n });\n const activity = yield* makeActivity();\n const started = yield* listen(location, activity, scope);\n if (started) {\n yield* untilIdle(idle)(activity);\n }\n return started;\n});\n","import { Duration, Effect, Layer, Option, Predicate, Schema } from \"effect\";\nimport type { FileSystem, Path } from \"effect\";\nimport type { ChildProcessSpawner } from \"effect/process\";\n\nimport type { Engine } from \"#/entities/model-engine/index.ts\";\nimport { transformersEngine } from \"#/features/load-transformers/index.ts\";\nimport { runMainWith } from \"#/features/run-main/index.ts\";\nimport { serve } from \"#/features/serve-models/index.ts\";\nimport { ServerArguments } from \"#/features/start-server/index.ts\";\nimport { ModelServerError } from \"#/shared/api/model-server/index.ts\";\n\nconst ARGUMENT_INDEX = 2;\n\nconst options = Schema.decodeUnknownEffect(Schema.fromJsonString(ServerArguments))(\n globalThis.process.argv[ARGUMENT_INDEX],\n);\n\nconst isEngineModule = (value: unknown): value is { readonly layer: Layer.Layer<Engine> } =>\n Predicate.hasProperty(value, \"layer\") && Layer.isLayer(value.layer);\n\nconst importModule = (path: string): Promise<unknown> => import(path);\n\nconst importFailed =\n (path: string) =>\n (cause: unknown): ModelServerError =>\n ModelServerError.make({ message: `importing ${path} failed: ${String(cause)}` });\n\nconst engineModule = (path: string): Layer.Layer<Engine, ModelServerError> =>\n Layer.unwrap(\n Effect.tryPromise({ try: () => importModule(path), catch: importFailed(path) }).pipe(\n Effect.filterOrFail(isEngineModule, () =>\n ModelServerError.make({ message: `${path} exports no engine layer` }),\n ),\n Effect.map((found) => found.layer),\n ),\n );\n\nconst engineOf = ({\n cache,\n engine: module,\n}: typeof ServerArguments.Type): Layer.Layer<\n Engine,\n ModelServerError,\n FileSystem.FileSystem | Path.Path | ChildProcessSpawner.ChildProcessSpawner\n> =>\n Option.match(Option.fromNullishOr(module), {\n onNone: () => transformersEngine(cache),\n onSome: engineModule,\n });\n\nconst engine = Layer.unwrap(options.pipe(Effect.map(engineOf)));\n\nconst program = options.pipe(\n Effect.flatMap(({ socket, cache, idleMillis }) =>\n serve({ location: { socket, cache }, idle: Duration.millis(idleMillis) }),\n ),\n Effect.scoped,\n);\n\nrunMainWith({ serviceName: \"model-server\", services: engine })(program);\n"],"ignoreList":[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,34,35,36,37,38,39,40,41,42,43],"mappings":";;;AA0xCA,MAAM,aAAa,EACjB,CAAC,OAAO,YAAY;CAClB,OAAO;AACT,EACF;AACA,MAAM,qBAAqB,EACzB,OAAO;CACL,OAAO;EACL,MAAM;EACN,OAAO,KAAA;CACT;AACF,EACF;;;;;;;;;;;;;;;;;;;;;AAqBA,MAAaA,gBAAc;;;ACzzC3B,MAAaC,WAAsBC,wBAAkB,iBAAiB,EACpE,qBAAqB;CACnB,gBAAgB;EACd,OAAO,KAAK,MAAM,KAAK,OAAO,KAAK,OAAO,mBAAmB,OAAO,mBAAmB,EAAE,IAAI,OAAO;CACtG;CACA,mBAAmB;EACjB,OAAO,KAAK,OAAO;CACrB;AACF,GACF,CAAC;;ACHD,MAAMC,WAAS;AAuBf,MAAM,sBAAsB;EACzBA,WAASA;CACV,CAAC,OAAO,YAAY;EAClB,OAAO,KAAK,QAAQ,OAAO,SAAS,CAAC;CACvC;CACA,WAAW;EACT,OAAO,kBAAkB,OAAO,MAAM,KAAK,IAAI,CAAC,EAAE;CACpD;CACA,SAAS;EACP,OAAO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