better-effect 0.9.31 → 0.11.0

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 (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +277 -16
  3. package/dist/adapters/iti.d.mts +10 -5
  4. package/dist/adapters/iti.d.mts.map +1 -1
  5. package/dist/adapters/iti.mjs +30 -5
  6. package/dist/adapters/iti.mjs.map +1 -1
  7. package/dist/context-BUEf1qjL.mjs +152 -0
  8. package/dist/context-BUEf1qjL.mjs.map +1 -0
  9. package/dist/effect-2ZcGZI8A.mjs +513 -0
  10. package/dist/effect-2ZcGZI8A.mjs.map +1 -0
  11. package/dist/errors-BKcsQ0ip.d.mts +12 -0
  12. package/dist/errors-BKcsQ0ip.d.mts.map +1 -0
  13. package/dist/hono.d.mts +39 -21
  14. package/dist/hono.d.mts.map +1 -1
  15. package/dist/hono.mjs +25 -20
  16. package/dist/hono.mjs.map +1 -1
  17. package/dist/{index-BsPr7qHf.d.mts → index-C7Qild0_.d.mts} +158 -28
  18. package/dist/index-C7Qild0_.d.mts.map +1 -0
  19. package/dist/{index-CITM15SE.d.mts → index-DStz0JMN.d.mts} +4 -4
  20. package/dist/{index-CITM15SE.d.mts.map → index-DStz0JMN.d.mts.map} +1 -1
  21. package/dist/{index-1NLNdkJy.d.mts → index-heuaRmXR.d.mts} +8 -8
  22. package/dist/{index-1NLNdkJy.d.mts.map → index-heuaRmXR.d.mts.map} +1 -1
  23. package/dist/{index-EJlskfAW.d.mts → index-rQhZk3Nt.d.mts} +130 -23
  24. package/dist/index-rQhZk3Nt.d.mts.map +1 -0
  25. package/dist/index.d.mts +5 -6
  26. package/dist/index.mjs +6 -540
  27. package/dist/index.mjs.map +1 -1
  28. package/dist/runtime/explicit.d.mts +11 -7
  29. package/dist/runtime/explicit.d.mts.map +1 -1
  30. package/dist/runtime/explicit.mjs +96 -23
  31. package/dist/runtime/explicit.mjs.map +1 -1
  32. package/dist/runtime/node.d.mts +2 -2
  33. package/dist/runtime/node.d.mts.map +1 -1
  34. package/dist/runtime/node.mjs +10 -6
  35. package/dist/runtime/node.mjs.map +1 -1
  36. package/dist/runtime-DnMn0X0X.mjs +613 -0
  37. package/dist/runtime-DnMn0X0X.mjs.map +1 -0
  38. package/dist/scope-GGnmTQck.mjs +245 -0
  39. package/dist/scope-GGnmTQck.mjs.map +1 -0
  40. package/dist/{signal-Cl9tqGyX.mjs → signal-B97cs85Z.mjs} +86 -6
  41. package/dist/signal-B97cs85Z.mjs.map +1 -0
  42. package/dist/{standard-services-QseopL9g.mjs → standard-services-BFBq-4lo.mjs} +2 -2
  43. package/dist/{standard-services-QseopL9g.mjs.map → standard-services-BFBq-4lo.mjs.map} +1 -1
  44. package/dist/standard-services.d.mts +2 -2
  45. package/dist/standard-services.mjs +2 -2
  46. package/dist/testing.d.mts +198 -2
  47. package/dist/testing.d.mts.map +1 -0
  48. package/dist/testing.mjs +976 -2
  49. package/dist/testing.mjs.map +1 -0
  50. package/package.json +6 -3
  51. package/dist/context-B4yO5LaH.mjs +0 -80
  52. package/dist/context-B4yO5LaH.mjs.map +0 -1
  53. package/dist/effect-CZdZCZLW.mjs +0 -522
  54. package/dist/effect-CZdZCZLW.mjs.map +0 -1
  55. package/dist/errors-BXKc7juX.d.mts +0 -8
  56. package/dist/errors-BXKc7juX.d.mts.map +0 -1
  57. package/dist/index-BsPr7qHf.d.mts.map +0 -1
  58. package/dist/index-EJlskfAW.d.mts.map +0 -1
  59. package/dist/map-layer-backend-DMJauecV.d.mts +0 -42
  60. package/dist/map-layer-backend-DMJauecV.d.mts.map +0 -1
  61. package/dist/map-layer-backend-gal-mcRv.mjs +0 -53
  62. package/dist/map-layer-backend-gal-mcRv.mjs.map +0 -1
  63. package/dist/signal-Cl9tqGyX.mjs.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"effect-2ZcGZI8A.mjs","names":["map","mapError","andThen","next","resultMatchError","resultMatchErrorPartial","tap","tapError","matchError","matchErrorPartial","recover","programMap","programMapError","programAndThen","programTap","programTapError","programRecover"],"sources":["../src/effect/combinators.ts","../src/effect/program-combinators.ts","../src/effect/program-scheduler.ts","../src/effect/effect.ts"],"sourcesContent":["import {\n matchError as resultMatchError,\n matchErrorPartial as resultMatchErrorPartial,\n Result\n} from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { AnyService } from '../service'\nimport { isPromiseLike } from '../utils/runtime'\nimport type { Effect, EffectError, EffectRequirements, EffectSuccess } from './types'\n\ntype EffectInput<A, E> = ResultType<A, E> | PromiseLike<ResultType<A, E>>\n\ntype AnyEffectInput = EffectInput<any, any>\ntype AnyEffectValue = ResultType<any, any>\ntype AnyAsyncEffectInput = PromiseLike<ResultType<any, any>>\ntype CombinatorCallback = (value: any) => any\ntype CombinatorInput = AnyEffectInput | CombinatorCallback\n\ntype PreserveAsync<Input, Output> = Input extends PromiseLike<unknown> ? Promise<Output> : Output\n\ntype MappedResult<Input, B> = Effect<B, EffectError<Input>, EffectRequirements<Input>>\n\ntype ErrorMappedResult<Input, E2> = Effect<EffectSuccess<Input>, E2, EffectRequirements<Input>>\n\ntype ChainedResult<First, Next> = Effect<\n EffectSuccess<Next>,\n EffectError<First> | EffectError<Next>,\n EffectRequirements<First> | EffectRequirements<Next>\n>\n\ntype ChainedOutput<First, Next> = ChainedResult<First, Next>\n\ntype AsyncChainedOutput<First, Next> = Promise<ChainedResult<First, Next>>\n\ntype MapOperation<A, B> = {\n <Input>(effect: Input & EffectInput<A, any>): PreserveAsync<Input, MappedResult<Input, B>>\n}\n\ntype MapErrorOperation<E1, E2> = {\n <Input>(effect: Input & EffectInput<any, E1>): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\n}\n\ntype AndThenOperation<Next> = {\n <Input>(effect: Input & AnyEffectValue): ChainedOutput<Input, Next>\n}\n\ntype AndThenAsyncOperation<A, Next> = {\n <Input>(effect: Input & EffectInput<A, any>): AsyncChainedOutput<Input, Next>\n}\n\ntype TappedResult<Input> = Effect<\n EffectSuccess<Input>,\n EffectError<Input>,\n EffectRequirements<Input>\n>\n\ntype RecoveredResult<Input, Next> = Effect<\n EffectSuccess<Input> | EffectSuccess<Next>,\n EffectError<Next>,\n EffectRequirements<Input> | EffectRequirements<Next>\n>\n\ntype FlattenedResult<Input> = Effect<\n EffectSuccess<EffectSuccess<Input>>,\n EffectError<Input> | EffectError<EffectSuccess<Input>>,\n EffectRequirements<Input> | EffectRequirements<EffectSuccess<Input>>\n>\n\ntype AsResult<Input, Value> = Effect<Value, EffectError<Input>, EffectRequirements<Input>>\n\ntype MatchedResult<Input, OkResult, ErrResult> = Effect<\n EffectSuccess<OkResult> | EffectSuccess<ErrResult>,\n EffectError<OkResult> | EffectError<ErrResult>,\n EffectRequirements<Input> | EffectRequirements<OkResult> | EffectRequirements<ErrResult>\n>\n\ntype AllResult<Results extends readonly AnyEffectValue[]> = Effect<\n { -readonly [Index in keyof Results]: EffectSuccess<Results[Index]> },\n EffectError<Results[number]>,\n EffectRequirements<Results[number]>\n>\n\ntype ZipResult<Left, Right> = Effect<\n [EffectSuccess<Left>, EffectSuccess<Right>],\n EffectError<Left> | EffectError<Right>,\n EffectRequirements<Left> | EffectRequirements<Right>\n>\n\ntype TapOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => void\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype TapErrorOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => void\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype TapBothOperation = {\n <Input>(\n effect: Input & AnyEffectInput,\n handlers: {\n ok: (value: EffectSuccess<Input>) => void\n err: (error: EffectError<Input>) => void\n }\n ): PreserveAsync<Input, TappedResult<Input>>\n}\n\ntype TapAsyncOperation = {\n <Input>(effect: Input & AnyEffectInput): Promise<TappedResult<Input>>\n}\n\ntype TapErrorAsyncOperation = {\n <Input>(effect: Input & AnyEffectInput): Promise<TappedResult<Input>>\n}\n\ntype TapBothAsyncOperation = {\n <Input>(effect: Input & AnyEffectInput): Promise<TappedResult<Input>>\n}\n\ntype TaggedErrorLike = Error & { readonly _tag: string }\n\ntype TaggedErrorHandlers<ErrorValue extends TaggedErrorLike> = {\n // oxlint-disable-next-line anti-slop/no-unknown-returns -- better-result matchers allow arbitrary handler results.\n [Tag in ErrorValue['_tag']]: (error: Extract<ErrorValue, { readonly _tag: Tag }>) => unknown\n}\n\ntype TaggedErrorOf<Input> = Extract<EffectError<Input>, TaggedErrorLike>\n\ntype TaggedErrorHandlersFor<Input> = [EffectError<Input>] extends [TaggedErrorLike]\n ? TaggedErrorHandlers<TaggedErrorOf<Input>>\n : never\n\ntype HandlerReturn<Handlers> = {\n [Key in keyof Handlers]-?: NonNullable<Handlers[Key]> extends (error: never) => infer Return\n ? Return\n : never\n}[keyof Handlers]\n\ntype RequiredHandlerKeys<Handlers> = {\n [Key in keyof Handlers]-?: {} extends Pick<Handlers, Key>\n ? never\n : undefined extends Handlers[Key]\n ? never\n : Key\n}[keyof Handlers]\n\ntype UnhandledTaggedErrors<ErrorValue extends TaggedErrorLike, Handlers> = Exclude<\n ErrorValue,\n { readonly _tag: Extract<RequiredHandlerKeys<Handlers>, ErrorValue['_tag']> }\n>\n\ntype MatchErrorResult<Input, Handlers> = Effect<\n EffectSuccess<Input>,\n HandlerReturn<Handlers>,\n EffectRequirements<Input>\n>\n\ntype MatchErrorPartialResult<Input, Handlers> = Effect<\n EffectSuccess<Input>,\n HandlerReturn<Handlers> | UnhandledTaggedErrors<TaggedErrorOf<Input>, Handlers>,\n EffectRequirements<Input>\n>\n\ntype RecoverOperation<Next> = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n ): PreserveAsync<Input, RecoveredResult<Input, Next>>\n}\n\ntype RecoverAsyncOperation<Next> = {\n <Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n ): Promise<RecoveredResult<Input, Next>>\n}\n\nconst asResult = <Value>(value: Value): ResultType<any, any> => {\n // SAFETY: Effect is the declaration-only Result facade, so every runtime value is a Result.\n return value as ResultType<any, any>\n}\n\nconst mapResult = <A, B, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => B\n): Effect<B, E, Requirements> => {\n // SAFETY: Result.map changes only the success channel; the declaration-only Effect marker is restored by this adapter.\n return Result.map(result, fn) as Effect<B, E, Requirements>\n}\n\nconst mapErrorResult = <A, E1, E2, Requirements extends AnyService>(\n result: ResultType<A, E1>,\n fn: (error: E1) => E2\n): Effect<A, E2, Requirements> => {\n // SAFETY: Result.mapError changes only the error channel; the declaration-only Effect marker is restored by this adapter.\n return Result.mapError(result, fn) as Effect<A, E2, Requirements>\n}\n\nconst andThenResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => ResultType<B, E2>\n): Effect<B, E1 | E2, Requirements1 | Requirements2> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = next as (value: A) => ResultType<B, E2>\n\n // SAFETY: Result.andThen unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThen(result, resultNext) as Effect<B, E1 | E2, Requirements1 | Requirements2>\n}\n\nconst andThenAsyncResult = <\n A,\n B,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E1>,\n next: (value: A) => PromiseLike<ResultType<B, E2>>\n): Promise<Effect<B, E1 | E2, Requirements1 | Requirements2>> => {\n // SAFETY: The public callback returns an Effect, whose only runtime contract is the underlying Result.\n const resultNext = (value: A) => {\n // SAFETY: Promise resolution preserves the callback's Result value; only declaration-only Effect metadata is erased.\n return Promise.resolve(next(value)) as Promise<ResultType<B, E2>>\n }\n\n // SAFETY: Result.andThenAsync unions Result errors; the declaration-only Effect marker is restored by this adapter.\n return Result.andThenAsync(result, resultNext) as Promise<\n Effect<B, E1 | E2, Requirements1 | Requirements2>\n >\n}\n\n/**\n * Map the successful value of a Result or Effect result.\n *\n * Supports both data-first and data-last forms and preserves asynchronous\n * results and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const doubled = Effect.map(Result.ok(2), (value) => value * 2)\n * const toLabel = Effect.map((value: number) => `#${value}`)\n * ```\n */\nexport function map<A, B>(fn: (value: A) => B): MapOperation<A, B>\nexport function map<Input, B>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => B\n): PreserveAsync<Input, MappedResult<Input, B>>\nexport function map(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return map(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Map the error value of a Result or Effect result while preserving its\n * successful value, asynchronous shape, and declaration-only Service requirements.\n *\n * @example\n * ```ts\n * const labelled = Effect.mapError(Result.err('missing'), (error) => ({ error }))\n * ```\n */\nexport function mapError<E1, E2>(fn: (error: E1) => E2): MapErrorOperation<E1, E2>\nexport function mapError<Input, E2>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => E2\n): PreserveAsync<Input, ErrorMappedResult<Input, E2>>\nexport function mapError(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary error-mapping callback in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return mapError(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to be a unary error-mapping callback.\n const fn = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return mapErrorResult(result as ResultType<any, any>, fn)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return mapErrorResult(first as ResultType<any, any>, fn)\n}\n\n/**\n * Chain a synchronous Result-producing operation after a successful result.\n *\n * The next operation is skipped when the input is an error. Both error types\n * and both sets of Service requirements are preserved in the output.\n *\n * @example\n * ```ts\n * const user = Effect.andThen(Result.ok('u1'), (id) => repository.find(id))\n * ```\n */\nexport function andThen<A, Next extends AnyEffectValue>(\n next: (value: A) => Next\n): AndThenOperation<Next>\nexport function andThen<Input, Next extends AnyEffectValue>(\n effect: Input & AnyEffectValue,\n next: (value: EffectSuccess<Input>) => Next\n): ChainedOutput<Input, Next>\nexport function andThen(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThen(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a Result.\n const next = second as CombinatorCallback\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenResult(first as ResultType<any, any>, next)\n}\n\n/**\n * Chain an asynchronous Result-producing operation after a successful result.\n *\n * The returned value is always a Promise and retains both operations' error\n * and Service-requirement metadata.\n *\n * @example\n * ```ts\n * const user = Effect.andThenAsync(loadUser(), (user) => fetchProfile(user.id))\n * ```\n */\nexport function andThenAsync<A, Next extends AnyAsyncEffectInput>(\n next: (value: A) => Next\n): AndThenAsyncOperation<A, Next>\nexport function andThenAsync<Input, Next extends AnyAsyncEffectInput>(\n effect: Input & AnyEffectInput,\n next: (value: EffectSuccess<Input>) => Next\n): AsyncChainedOutput<Input, Next>\nexport function andThenAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n // SAFETY: The curried overload accepts a unary asynchronous continuation in this branch.\n const callback = first as CombinatorCallback\n\n return (effect: AnyEffectInput) => {\n // SAFETY: The overload implementation has already established the callback and Effect input positions.\n return andThenAsync(effect as never, callback as never)\n }\n }\n\n // SAFETY: The data-first overload requires the second argument to return a PromiseLike Effect.\n const next = second as CombinatorCallback\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => {\n // SAFETY: Result is the runtime representation shared by Effect and better-result.\n return andThenAsyncResult(result as ResultType<any, any>, next)\n })\n }\n\n // SAFETY: The data-first overload supplies a Result-compatible Effect value.\n return andThenAsyncResult(first as ResultType<any, any>, next)\n}\n\nconst tapResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => void\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tap preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tap(result, fn) as Effect<A, E, Requirements>\n\nconst tapErrorResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (error: E) => void\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tapError preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tapError(result, fn) as Effect<A, E, Requirements>\n\nconst tapBothResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n handlers: { ok: (value: A) => void; err: (error: E) => void }\n): Effect<A, E, Requirements> =>\n // SAFETY: Result.tapBoth preserves the Result value; the declaration-only Effect marker is restored here.\n Result.tapBoth(result, handlers) as Effect<A, E, Requirements>\n\nconst tapAsyncResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (value: A) => PromiseLike<void>\n): Promise<Effect<A, E, Requirements>> =>\n // SAFETY: Result.tapAsync preserves the Result value and owns observer defect behavior; only the Effect marker is restored here.\n Result.tapAsync(result, (value) => Promise.resolve(fn(value))) as Promise<\n Effect<A, E, Requirements>\n >\n\nconst tapErrorAsyncResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n fn: (error: E) => PromiseLike<void>\n): Promise<Effect<A, E, Requirements>> =>\n // SAFETY: Result.tapErrorAsync preserves the Result value and owns observer defect behavior; only the Effect marker is restored here.\n Result.tapErrorAsync(result, (error) => Promise.resolve(fn(error))) as Promise<\n Effect<A, E, Requirements>\n >\n\nconst tapBothAsyncResult = <A, E, Requirements extends AnyService>(\n result: ResultType<A, E>,\n handlers: { ok: (value: A) => PromiseLike<void>; err: (error: E) => PromiseLike<void> }\n): Promise<Effect<A, E, Requirements>> =>\n // SAFETY: Result.tapBothAsync selects one branch and preserves the Result; only the Effect marker is restored here.\n Result.tapBothAsync(result, {\n ok: (value) => Promise.resolve(handlers.ok(value)),\n err: (error) => Promise.resolve(handlers.err(error))\n }) as Promise<Effect<A, E, Requirements>>\n\nconst asTaggedResult = (\n result: ResultType<unknown, unknown>\n): ResultType<unknown, TaggedErrorLike> => {\n // SAFETY: The public matcher overload restricts error values to TaggedErrorLike before reaching this runtime boundary.\n return result as ResultType<unknown, TaggedErrorLike>\n}\n\nconst matchErrorResult = <\n A,\n E extends TaggedErrorLike,\n Requirements extends AnyService,\n Handlers extends TaggedErrorHandlers<E>\n>(\n result: ResultType<A, E>,\n handlers: Handlers\n): Effect<A, HandlerReturn<Handlers>, Requirements> => {\n // SAFETY: Result.mapError selects Err and preserves Ok; the declaration-only Effect marker is restored here.\n return Result.mapError(result, (error) => resultMatchError(error, handlers)) as Effect<\n A,\n HandlerReturn<Handlers>,\n Requirements\n >\n}\n\nconst matchErrorPartialResult = <\n A,\n E extends TaggedErrorLike,\n Requirements extends AnyService,\n Handlers extends Partial<TaggedErrorHandlers<E>>\n>(\n result: ResultType<A, E>,\n handlers: Handlers\n): Effect<A, HandlerReturn<Handlers> | UnhandledTaggedErrors<E, Handlers>, Requirements> => {\n // SAFETY: Result.mapError selects Err and preserves Ok; the declaration-only Effect marker is restored here.\n return Result.mapError(result, (error) => resultMatchErrorPartial(error, handlers)) as Effect<\n A,\n HandlerReturn<Handlers> | UnhandledTaggedErrors<E, Handlers>,\n Requirements\n >\n}\n\nconst recoverResult = <\n A,\n E,\n B,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E>,\n fn: (error: E) => ResultType<B, E2>\n): Effect<A | B, E2, Requirements1 | Requirements2> =>\n // SAFETY: Result.tryRecover owns recovery and short-circuiting; only Effect metadata is restored here.\n Result.tryRecover(result, fn) as Effect<A | B, E2, Requirements1 | Requirements2>\n\nconst recoverAsyncResult = <\n A,\n E,\n B,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<A, E>,\n fn: (error: E) => PromiseLike<ResultType<B, E2>>\n): Promise<Effect<A | B, E2, Requirements1 | Requirements2>> =>\n // SAFETY: Result.tryRecoverAsync owns asynchronous recovery; only Effect metadata is restored here.\n Result.tryRecoverAsync(result, (error) => Promise.resolve(fn(error))) as Promise<\n Effect<A | B, E2, Requirements1 | Requirements2>\n >\n\nconst flattenResult = <\n A,\n E1,\n E2,\n Requirements1 extends AnyService,\n Requirements2 extends AnyService\n>(\n result: ResultType<ResultType<A, E2>, E1>\n): Effect<A, E1 | E2, Requirements1 | Requirements2> =>\n // SAFETY: Result.flatten removes one Result layer; the outer and inner Effect markers are restored here.\n Result.flatten(result) as Effect<A, E1 | E2, Requirements1 | Requirements2>\n\nconst matchResult = <A, E, OkResult, ErrResult>(\n result: ResultType<A, E>,\n handlers: { ok: (value: A) => OkResult; err: (error: E) => ErrResult }\n): OkResult | ErrResult =>\n // SAFETY: Result.match invokes only the selected branch; handler Results remain ordinary runtime values.\n Result.match(result, handlers as never) as OkResult | ErrResult\n\nconst allResult = <const Results extends readonly AnyEffectValue[]>(\n results: Results\n): AllResult<Results> =>\n // SAFETY: Result.all preserves tuple order and short-circuiting; the declaration-only channels are restored here.\n Result.all(results as readonly ResultType<any, any>[]) as AllResult<Results>\n\n/** Observe a successful value without changing the Result. */\nexport function tap(fn: (value: any) => void): TapOperation\nexport function tap<Input>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => void\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tap(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tap(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tap requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapResult(asResult(result), fn))\n }\n\n return tapResult(asResult(first), fn)\n}\n\n/** Observe an error value without changing the Result. */\nexport function tapError(fn: (error: any) => void): TapErrorOperation\nexport function tapError<Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => void\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tapError(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tapError(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tapError requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapErrorResult(asResult(result), fn))\n }\n\n return tapErrorResult(asResult(first), fn)\n}\n\n/** Observe whichever Result branch is active without changing the Result. */\nexport function tapBoth(handlers: {\n ok: (value: any) => void\n err: (error: any) => void\n}): TapBothOperation\nexport function tapBoth<Input>(\n effect: Input & AnyEffectInput,\n handlers: {\n ok: (value: EffectSuccess<Input>) => void\n err: (error: EffectError<Input>) => void\n }\n): PreserveAsync<Input, TappedResult<Input>>\nexport function tapBoth(first: any, second?: any): any {\n if (second === undefined) {\n return (effect: AnyEffectInput) => tapBoth(effect, first)\n }\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapBothResult(result, second))\n }\n\n return tapBothResult(asResult(first), second)\n}\n\n/** Observe a successful value asynchronously without changing the Result. */\nexport function tapAsync(fn: (value: any) => PromiseLike<void>): TapAsyncOperation\nexport function tapAsync<Input>(\n effect: Input & AnyEffectInput,\n fn: (value: EffectSuccess<Input>) => PromiseLike<void>\n): Promise<TappedResult<Input>>\nexport function tapAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tapAsync(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tapAsync requires a callback')\n }\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapAsyncResult(asResult(result), second))\n }\n\n return tapAsyncResult(asResult(first), second)\n}\n\n/** Observe an error value asynchronously without changing the Result. */\nexport function tapErrorAsync(fn: (error: any) => PromiseLike<void>): TapErrorAsyncOperation\nexport function tapErrorAsync<Input>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => PromiseLike<void>\n): Promise<TappedResult<Input>>\nexport function tapErrorAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => tapErrorAsync(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.tapErrorAsync requires a callback')\n }\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapErrorAsyncResult(asResult(result), second))\n }\n\n return tapErrorAsyncResult(asResult(first), second)\n}\n\n/** Observe the active Result branch asynchronously without changing the Result. */\nexport function tapBothAsync(handlers: {\n ok: (value: any) => PromiseLike<void>\n err: (error: any) => PromiseLike<void>\n}): TapBothAsyncOperation\nexport function tapBothAsync<Input>(\n effect: Input & AnyEffectInput,\n handlers: {\n ok: (value: EffectSuccess<Input>) => PromiseLike<void>\n err: (error: EffectError<Input>) => PromiseLike<void>\n }\n): Promise<TappedResult<Input>>\nexport function tapBothAsync(first: any, second?: any): any {\n if (second === undefined) {\n return (effect: AnyEffectInput) => tapBothAsync(effect, first)\n }\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => tapBothAsyncResult(result, second))\n }\n\n return tapBothAsyncResult(asResult(first), second)\n}\n\n/** Match every tagged error variant and map it to a new error value. */\nexport function matchError<Input, Handlers extends TaggedErrorHandlersFor<Input>>(\n effect: Input & AnyEffectInput,\n handlers: Handlers\n): PreserveAsync<Input, MatchErrorResult<Input, Handlers>>\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- overload implementation is narrowed by the typed public signature.\nexport function matchError(first: AnyEffectInput, second?: unknown): any {\n if (second === undefined) {\n throw new TypeError('Effect.matchError requires handlers')\n }\n\n // SAFETY: The public matcher overload checks the handler map against the source tagged-error union.\n const handlers = second as TaggedErrorHandlers<TaggedErrorLike>\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) =>\n matchErrorResult(asTaggedResult(asResult(result)), handlers)\n )\n }\n\n return matchErrorResult(asTaggedResult(asResult(first)), handlers)\n}\n\n/** Match selected tagged errors and retain unhandled variants unchanged. */\nexport function matchErrorPartial<Input, Handlers extends Partial<TaggedErrorHandlersFor<Input>>>(\n effect: Input & AnyEffectInput,\n handlers: Handlers\n): PreserveAsync<Input, MatchErrorPartialResult<Input, Handlers>>\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- overload implementation is narrowed by the typed public signature.\nexport function matchErrorPartial(first: AnyEffectInput, second?: unknown): any {\n if (second === undefined) {\n throw new TypeError('Effect.matchErrorPartial requires handlers')\n }\n\n // SAFETY: The public matcher overload checks the handler map against the source tagged-error union.\n const handlers = second as Partial<TaggedErrorHandlers<TaggedErrorLike>>\n\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) =>\n matchErrorPartialResult(asTaggedResult(asResult(result)), handlers)\n )\n }\n\n return matchErrorPartialResult(asTaggedResult(asResult(first)), handlers)\n}\n\n/** Recover an Err with a synchronous Result-producing callback. */\nexport function recover<Next extends AnyEffectValue>(\n fn: (error: any) => Next\n): RecoverOperation<Next>\nexport function recover<Input, Next extends AnyEffectValue>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n): PreserveAsync<Input, RecoveredResult<Input, Next>>\nexport function recover(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => recover(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.recover requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => recoverResult(asResult(result), fn))\n }\n\n return recoverResult(asResult(first), fn)\n}\n\n/** Recover an Err with an asynchronous Result-producing callback. */\nexport function recoverAsync<Next extends AnyAsyncEffectInput>(\n fn: (error: any) => Next\n): RecoverAsyncOperation<Next>\nexport function recoverAsync<Input, Next extends AnyAsyncEffectInput>(\n effect: Input & AnyEffectInput,\n fn: (error: EffectError<Input>) => Next\n): Promise<RecoveredResult<Input, Next>>\nexport function recoverAsync(first: CombinatorInput, second?: CombinatorCallback): any {\n if (first instanceof Function && second === undefined) {\n const callback = first\n return (effect: AnyEffectInput) => recoverAsync(effect, callback)\n }\n\n if (second === undefined) {\n throw new TypeError('Effect.recoverAsync requires a callback')\n }\n\n const fn = second\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => recoverAsyncResult(asResult(result), fn))\n }\n\n return recoverAsyncResult(asResult(first), fn)\n}\n\n/** Remove one nested Result/Effect layer. */\nexport function flatten<Input>(effect: Input & AnyEffectValue): FlattenedResult<Input> {\n // SAFETY: flattenResult restores the nested Effect channels after Result.flatten removes one runtime layer.\n return flattenResult(asResult(effect)) as FlattenedResult<Input>\n}\n\n/** Replace a successful value while preserving errors and requirements. */\nexport function as<Value>(\n value: Value\n): <Input>(effect: Input & AnyEffectValue) => AsResult<Input, Value>\nexport function as<Input, Value>(\n effect: Input & AnyEffectValue,\n value: Value\n): AsResult<Input, Value>\nexport function as(first: any, second?: any): any {\n if (arguments.length < 2) {\n return (effect: AnyEffectValue) => as(effect, first)\n }\n\n return mapResult(asResult(first), () => second)\n}\n\n/** Replace a successful value with void. */\nexport function asVoid<Input>(effect: Input & AnyEffectValue): AsResult<Input, void> {\n return mapResult(asResult(effect), () => undefined)\n}\n\n/** Match an Effect and return branch Effects with their channels unioned. */\nexport function match<Input, OkResult extends AnyEffectValue, ErrResult extends AnyEffectValue>(\n effect: Input & AnyEffectValue,\n handlers: {\n ok: (value: EffectSuccess<Input>) => OkResult\n err: (error: EffectError<Input>) => ErrResult\n }\n): PreserveAsync<Input, MatchedResult<Input, OkResult, ErrResult>>\nexport function match<Input, OkValue, ErrValue>(\n effect: Input & AnyEffectValue,\n handlers: {\n ok: (value: EffectSuccess<Input>) => OkValue\n err: (error: EffectError<Input>) => ErrValue\n }\n): PreserveAsync<Input, OkValue | ErrValue>\nexport function match(first: AnyEffectInput, second?: any): any {\n if (isPromiseLike(first)) {\n return Promise.resolve(first).then((result) => match(asResult(result), second))\n }\n\n return matchResult(asResult(first), second)\n}\n\n/** Collect already-created Effects in input order. */\nexport function all<const Results extends readonly AnyEffectValue[]>(\n results: Results\n): AllResult<Results> {\n return allResult(results)\n}\n\n/** Combine two already-created Effects in input order. */\nexport function zip<Left, Right>(\n left: Left & AnyEffectValue,\n right: Right & AnyEffectValue\n): ZipResult<Left, Right> {\n // SAFETY: Result.all returns the ordered pair; ZipResult restores only the declaration-only Effect channels.\n return Result.all([left, right]) as ZipResult<Left, Right>\n}\n","import { Result } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\nimport type { AnyService } from '../service'\nimport { isPromiseLike } from '../utils/runtime'\n\nimport type { EffectError, EffectRequirements, EffectSuccess, Program } from './types'\n\ntype AnyResult = ResultType<any, any>\ntype RuntimeEffect = AnyResult | PromiseLike<AnyResult>\ntype RuntimeProgram = () => RuntimeEffect\ntype RuntimeProgramOutput = RuntimeEffect | RuntimeProgram\ntype RuntimeCallback = (value: any) => any\ntype RuntimeContinuation = (value: any) => RuntimeProgramOutput\ntype AnyProgram = Program<any, any, AnyService>\n\ntype ProgramInput<Input extends RuntimeProgram> = Input &\n Program<EffectSuccess<Input>, EffectError<Input>, EffectRequirements<Input>>\n\ntype CompatibleSuccess<Input, A> = EffectSuccess<Input> extends A ? unknown : never\ntype CompatibleError<Input, E> = EffectError<Input> extends E ? unknown : never\n\ntype ProgramOutput<Output> =\n Output extends Program<infer _Success, infer _Error, infer _Requirements extends AnyService>\n ? Output\n : Output extends PromiseLike<infer AsyncOutput>\n ? AsyncOutput extends ResultType<infer _Success, infer _Error>\n ? Output\n : never\n : Output extends ResultType<infer _Success, infer _Error>\n ? Output\n : never\n\ntype MappedProgram<Input, B> = Program<B, EffectError<Input>, EffectRequirements<Input>>\n\ntype ErrorMappedProgram<Input, E2> = Program<EffectSuccess<Input>, E2, EffectRequirements<Input>>\n\ntype ChainedProgram<Input, Next> = Program<\n EffectSuccess<Next>,\n EffectError<Input> | EffectError<Next>,\n EffectRequirements<Input> | EffectRequirements<Next>\n>\n\ntype TappedProgram<Input> = Program<\n EffectSuccess<Input>,\n EffectError<Input>,\n EffectRequirements<Input>\n>\n\ntype RecoveredProgram<Input, Next> = Program<\n EffectSuccess<Input> | EffectSuccess<Next>,\n EffectError<Next>,\n EffectRequirements<Input> | EffectRequirements<Next>\n>\n\ntype MapOperation<A, B> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleSuccess<Input, A>\n ): MappedProgram<Input, B>\n}\n\ntype MapErrorOperation<E1, E2> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleError<Input, E1>\n ): ErrorMappedProgram<Input, E2>\n}\n\ntype AndThenOperation<A, Next> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleSuccess<Input, A>\n ): ChainedProgram<Input, Next>\n}\n\ntype TapOperation<A> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleSuccess<Input, A>\n ): TappedProgram<Input>\n}\n\ntype TapErrorOperation<E> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleError<Input, E>\n ): TappedProgram<Input>\n}\n\ntype RecoverOperation<E, Next> = {\n <Input extends RuntimeProgram>(\n program: ProgramInput<Input> & CompatibleError<Input, E>\n ): RecoveredProgram<Input, Next>\n}\n\nconst asProgram = <Output extends AnyProgram>(program: RuntimeProgram): Output =>\n // SAFETY: Program's channels and nominal marker are declaration-only; callers derive them from typed inputs.\n program as Output\n\nconst isAsyncEffect = (effect: RuntimeEffect): effect is PromiseLike<AnyResult> =>\n isPromiseLike(effect)\n\nconst mapRuntime = (effect: RuntimeEffect, fn: RuntimeCallback): RuntimeEffect => {\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.map(result, fn))\n }\n\n return Result.map(effect, fn)\n}\n\nconst mapErrorRuntime = (effect: RuntimeEffect, fn: RuntimeCallback): RuntimeEffect => {\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.mapError(result, fn))\n }\n\n return Result.mapError(effect, fn)\n}\n\nconst tapRuntime = (effect: RuntimeEffect, fn: RuntimeCallback): RuntimeEffect => {\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.tap(result, fn))\n }\n\n return Result.tap(effect, fn)\n}\n\nconst tapErrorRuntime = (effect: RuntimeEffect, fn: RuntimeCallback): RuntimeEffect => {\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.tapError(result, fn))\n }\n\n return Result.tapError(effect, fn)\n}\n\nconst invoke = (output: RuntimeProgramOutput): RuntimeEffect =>\n output instanceof Function ? output() : output\n\nconst andThenRuntime = (effect: RuntimeEffect, next: RuntimeContinuation): Promise<AnyResult> => {\n const continueWith = (value: any) => Promise.resolve(invoke(next(value)))\n\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.andThenAsync(result, continueWith))\n }\n\n return Result.andThenAsync(effect, continueWith)\n}\n\nconst recoverRuntime = (\n effect: RuntimeEffect,\n recover: RuntimeContinuation\n): Promise<AnyResult> => {\n const continueWith = (error: any) => Promise.resolve(invoke(recover(error)))\n\n if (isAsyncEffect(effect)) {\n return Promise.resolve(effect).then((result) => Result.tryRecoverAsync(result, continueWith))\n }\n\n return Result.tryRecoverAsync(effect, continueWith)\n}\n\nconst mapProgram = <Input extends RuntimeProgram, B>(\n program: ProgramInput<Input>,\n fn: (value: EffectSuccess<Input>) => B\n): MappedProgram<Input, B> => asProgram<MappedProgram<Input, B>>(() => mapRuntime(program(), fn))\n\nconst mapErrorProgram = <Input extends RuntimeProgram, E2>(\n program: ProgramInput<Input>,\n fn: (error: EffectError<Input>) => E2\n): ErrorMappedProgram<Input, E2> =>\n asProgram<ErrorMappedProgram<Input, E2>>(() => mapErrorRuntime(program(), fn))\n\nconst tapProgram = <Input extends RuntimeProgram>(\n program: ProgramInput<Input>,\n fn: (value: EffectSuccess<Input>) => any\n): TappedProgram<Input> => asProgram<TappedProgram<Input>>(() => tapRuntime(program(), fn))\n\nconst tapErrorProgram = <Input extends RuntimeProgram>(\n program: ProgramInput<Input>,\n fn: (error: EffectError<Input>) => any\n): TappedProgram<Input> => asProgram<TappedProgram<Input>>(() => tapErrorRuntime(program(), fn))\n\n/** Lazily map the successful Result value of a Program. */\nexport function map<A, B>(fn: (value: A) => B): MapOperation<A, B>\nexport function map<Input extends RuntimeProgram, B>(\n program: ProgramInput<Input>,\n fn: (value: EffectSuccess<Input>) => B\n): MappedProgram<Input, B>\nexport function map(first: RuntimeProgram | RuntimeCallback, second?: RuntimeCallback): any {\n if (second === undefined) {\n return (program: RuntimeProgram) => {\n // SAFETY: The curried overload supplies a Program and a callback that accepts its success channel.\n return mapProgram(program as ProgramInput<typeof program>, first)\n }\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return mapProgram(first as ProgramInput<RuntimeProgram>, second)\n}\n\n/** Lazily map the error Result value of a Program. */\nexport function mapError<E1, E2>(fn: (error: E1) => E2): MapErrorOperation<E1, E2>\nexport function mapError<Input extends RuntimeProgram, E2>(\n program: ProgramInput<Input>,\n fn: (error: EffectError<Input>) => E2\n): ErrorMappedProgram<Input, E2>\nexport function mapError(first: RuntimeProgram | RuntimeCallback, second?: RuntimeCallback): any {\n if (second === undefined) {\n return (program: RuntimeProgram) => {\n // SAFETY: The curried overload supplies a Program and a callback that accepts its error channel.\n return mapErrorProgram(program as ProgramInput<typeof program>, first)\n }\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return mapErrorProgram(first as ProgramInput<RuntimeProgram>, second)\n}\n\n/** Lazily continue a successful Program with an Effect or Program. */\nexport function andThen<A, Next>(\n next: (value: A) => Next & ProgramOutput<Next>\n): AndThenOperation<A, Next>\nexport function andThen<Input extends RuntimeProgram, Next>(\n program: ProgramInput<Input>,\n next: (value: EffectSuccess<Input>) => Next & ProgramOutput<Next>\n): ChainedProgram<Input, Next>\nexport function andThen(\n first: RuntimeProgram | RuntimeContinuation,\n second?: RuntimeContinuation\n): any {\n if (second === undefined) {\n return (program: RuntimeProgram) =>\n // SAFETY: The curried overload supplies a Program and a continuation for its success channel.\n () =>\n andThenRuntime(program(), first as RuntimeContinuation)\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return () => andThenRuntime((first as RuntimeProgram)(), second)\n}\n\n/** Lazily observe a successful Program value without changing its Result. */\nexport function tap<A>(fn: (value: A) => void): TapOperation<A>\nexport function tap<Input extends RuntimeProgram>(\n program: ProgramInput<Input>,\n fn: (value: EffectSuccess<Input>) => void\n): TappedProgram<Input>\nexport function tap(first: RuntimeProgram | RuntimeCallback, second?: RuntimeCallback): any {\n if (second === undefined) {\n return (program: RuntimeProgram) => {\n // SAFETY: The curried overload supplies a Program and a callback that accepts its success channel.\n return tapProgram(program as ProgramInput<typeof program>, first)\n }\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return tapProgram(first as ProgramInput<RuntimeProgram>, second)\n}\n\n/** Lazily observe a failed Program value without changing its Result. */\nexport function tapError<E>(fn: (error: E) => void): TapErrorOperation<E>\nexport function tapError<Input extends RuntimeProgram>(\n program: ProgramInput<Input>,\n fn: (error: EffectError<Input>) => void\n): TappedProgram<Input>\nexport function tapError(first: RuntimeProgram | RuntimeCallback, second?: RuntimeCallback): any {\n if (second === undefined) {\n return (program: RuntimeProgram) => {\n // SAFETY: The curried overload supplies a Program and a callback that accepts its error channel.\n return tapErrorProgram(program as ProgramInput<typeof program>, first)\n }\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return tapErrorProgram(first as ProgramInput<RuntimeProgram>, second)\n}\n\n/** Lazily recover a failed Program with an Effect or Program. */\nexport function recover<E, Next>(\n fn: (error: E) => Next & ProgramOutput<Next>\n): RecoverOperation<E, Next>\nexport function recover<Input extends RuntimeProgram, Next>(\n program: ProgramInput<Input>,\n recover: (error: EffectError<Input>) => Next & ProgramOutput<Next>\n): RecoveredProgram<Input, Next>\nexport function recover(\n first: RuntimeProgram | RuntimeContinuation,\n second?: RuntimeContinuation\n): any {\n if (second === undefined) {\n return (program: RuntimeProgram) =>\n // SAFETY: The curried overload supplies a Program and a recovery callback for its error channel.\n () =>\n recoverRuntime(program(), first as RuntimeContinuation)\n }\n\n // SAFETY: The data-first overload supplies a Program as its first argument.\n return () => recoverRuntime((first as RuntimeProgram)(), second)\n}\n","import { Err } from 'better-result'\n\nimport type { Result as ResultType } from 'better-result'\n\ntype AnyResult = ResultType<any, any>\n\ntype ProgramCollectionFailure =\n | { readonly kind: 'result'; readonly result: AnyResult }\n | { readonly kind: 'defect'; readonly cause: unknown }\n\ntype ProgramCollectionDefect = { readonly cause: unknown }\n\ntype ProgramCollectionOutcome = {\n readonly results: Array<AnyResult | undefined>\n readonly defects: Array<ProgramCollectionDefect | undefined>\n}\n\nexport type ProgramCollectionOptions = {\n readonly concurrency: number | undefined\n readonly stopOnResultError: boolean\n}\n\ntype ProgramTask = (index: number) => AnyResult | PromiseLike<AnyResult>\n\ntype SchedulerState = {\n nextIndex: number\n stopScheduling: boolean\n readonly results: Array<AnyResult | undefined>\n readonly defects: Array<ProgramCollectionDefect | undefined>\n}\n\n/** Validate the shared bounded-concurrency option before a Program is run. */\nexport const validateProgramConcurrency = (concurrency: number | undefined): void => {\n if (\n concurrency !== undefined &&\n (!Number.isFinite(concurrency) || !Number.isInteger(concurrency) || concurrency <= 0)\n ) {\n throw new RangeError('Program.all concurrency must be a positive integer')\n }\n}\n\nconst runWorker = async (\n length: number,\n task: ProgramTask,\n stopOnResultError: boolean,\n state: SchedulerState\n): Promise<void> => {\n while (!state.stopScheduling) {\n const index = state.nextIndex++\n\n if (index >= length) {\n return\n }\n\n try {\n const result = await task(index)\n state.results[index] = result\n\n if (result instanceof Err) {\n state.stopScheduling ||= stopOnResultError\n }\n } catch (cause) {\n state.defects[index] = { cause }\n state.stopScheduling = true\n }\n }\n}\n\n/** Run claimed Programs with a shared FIFO worker pool and no cancellation. */\nexport const runProgramCollection = async (\n length: number,\n task: ProgramTask,\n options: ProgramCollectionOptions\n): Promise<ProgramCollectionOutcome> => {\n const state: SchedulerState = {\n nextIndex: 0,\n stopScheduling: false,\n results: Array.from({ length }),\n defects: Array.from({ length })\n }\n const workerCount = Math.min(options.concurrency ?? length, length)\n const workers = Array.from({ length: workerCount }, () =>\n runWorker(length, task, options.stopOnResultError, state)\n )\n\n await Promise.all(workers)\n\n return state\n}\n\n/** Select the first defect by input index, independent of settlement order. */\nexport const firstProgramDefect = (\n defects: readonly (ProgramCollectionDefect | undefined)[]\n): ProgramCollectionDefect | undefined => {\n for (const defect of defects) {\n if (defect !== undefined) {\n return defect\n }\n }\n\n return undefined\n}\n\n/** Select the first short-circuiting failure by input index. */\nexport const firstProgramFailure = (\n results: readonly (AnyResult | undefined)[],\n defects: readonly (ProgramCollectionDefect | undefined)[]\n): ProgramCollectionFailure | undefined => {\n const length = Math.max(results.length, defects.length)\n\n for (let index = 0; index < length; index++) {\n const defect = defects[index]\n if (defect !== undefined) {\n return { kind: 'defect', cause: defect.cause }\n }\n\n const result = results[index]\n if (result instanceof Err) {\n return { kind: 'result', result }\n }\n }\n\n return undefined\n}\n","import { Result } from 'better-result'\n\nimport type { Err, Result as ResultType, UnhandledException } from 'better-result'\n\nimport { Scope } from '../scope'\n\nimport type { DisposableResource, MaybePromise, ScopeOutcome } from '../scope'\nimport type { AnyService } from '../service'\n\nimport type {\n AnyEffect,\n Effect as EffectType,\n EffectError,\n EffectFromGenerator,\n EffectRequirements,\n EffectSuccess,\n EffectYield,\n Program as ProgramType,\n ProgramFromGenerator\n} from './types'\n\nimport {\n all,\n andThen,\n andThenAsync,\n as,\n asVoid,\n flatten,\n map,\n mapError,\n match,\n matchError,\n matchErrorPartial,\n recover,\n recoverAsync,\n tap,\n tapAsync,\n tapBoth,\n tapBothAsync,\n tapError,\n tapErrorAsync,\n zip\n} from './combinators'\nimport {\n andThen as programAndThen,\n map as programMap,\n mapError as programMapError,\n recover as programRecover,\n tap as programTap,\n tapError as programTapError\n} from './program-combinators'\nimport {\n firstProgramDefect,\n firstProgramFailure,\n runProgramCollection,\n validateProgramConcurrency\n} from './program-scheduler'\n\nexport type Effect<A, E, R extends AnyService = never> = EffectType<A, E, R>\n\ntype LazyProgram<A, E, R extends AnyService = never> = ProgramType<A, E, R>\n\n/** A nominal lazy computation that produces an Effect when invoked. */\nexport type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\ntype AnyResult = ResultType<any, any>\n\ntype AnyProgram = ProgramType<any, any, AnyService>\n\ntype ProgramAllSuccess<Programs extends readonly AnyProgram[]> = {\n -readonly [Index in keyof Programs]: EffectSuccess<Programs[Index]>\n}\n\ntype ProgramAllError<Programs extends readonly AnyProgram[]> = EffectError<Programs[number]>\n\ntype ProgramAllRequirements<Programs extends readonly AnyProgram[]> = EffectRequirements<\n Programs[number]\n>\n\ntype ProgramAllResult<Programs extends readonly AnyProgram[]> = ProgramType<\n ProgramAllSuccess<Programs>,\n ProgramAllError<Programs>,\n ProgramAllRequirements<Programs>\n>\n\ntype ProgramResultFor<Child> = Child extends AnyProgram\n ? ResultType<EffectSuccess<Child>, EffectError<Child>>\n : never\n\ntype ProgramAllResultsSuccess<Programs extends readonly AnyProgram[]> =\n number extends Programs['length']\n ? ReadonlyArray<ResultType<EffectSuccess<Programs[number]>, EffectError<Programs[number]>>>\n : { readonly [Index in keyof Programs]: ProgramResultFor<Programs[Index]> }\n\ntype ProgramAllResultsResult<Programs extends readonly AnyProgram[]> = ProgramType<\n ProgramAllResultsSuccess<Programs>,\n never,\n ProgramAllRequirements<Programs>\n>\n\ntype ProgramForEachResult<Child extends AnyProgram> = ProgramType<\n ReadonlyArray<EffectSuccess<Child>>,\n EffectError<Child>,\n EffectRequirements<Child>\n>\n\nexport type ProgramAllOptions = {\n readonly concurrency?: number\n}\n\ntype EffectGenerator =\n | (() => Generator<EffectYield, AnyResult, unknown>)\n | (() => AsyncGenerator<EffectYield, AnyResult, unknown>)\n\ntype RuntimeResultGenerator = (body: EffectGenerator) => AnyResult | Promise<AnyResult>\n\n// SAFETY: Service iterators yield no runtime markers, so Result.gen receives only the Err values that exist at runtime.\nconst runResultGenerator = Result.gen as RuntimeResultGenerator\n\n/**\n * Compose `better-result` operations while preserving Service requirements in\n * a declaration-only type channel.\n *\n * A generator may yield Service tokens and Result operations. It must return a\n * `Result` as its final value; Service yields are resolved by the active\n * Runtime and do not add runtime values to the Result stream.\n * Use `fn` when generator execution should wait for a Runtime boundary.\n *\n * @example\n * ```ts\n * const loadUser = Effect.gen(async function* () {\n * const database = yield* Database\n * const user = yield* Result.await(database.findUser('u1'))\n *\n * return Result.ok(user)\n * })\n * ```\n */\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): EffectFromGenerator<Yield, Returned>\n\nexport function gen<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): Promise<EffectFromGenerator<Yield, Returned>>\n\nexport function gen(body: EffectGenerator): AnyResult | Promise<AnyResult> {\n return runResultGenerator(body)\n}\n\n/** Build a lazy Program without running its generator. */\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => Generator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn<Yield extends EffectYield, Returned extends AnyResult>(\n body: () => AsyncGenerator<Yield, Returned, unknown>\n): ProgramFromGenerator<Yield, Returned>\n\nexport function fn(body: EffectGenerator): Program<any, any, AnyService> {\n const program = () => runResultGenerator(body)\n\n // SAFETY: The generator overloads derive the Program channels; this cast only adds the declaration-only nominal marker.\n return program as Program<any, any, AnyService>\n}\n\nconst runShortCircuitingCollection = async (\n length: number,\n task: (index: number) => AnyResult | PromiseLike<AnyResult>,\n concurrency: number | undefined\n): Promise<AnyResult> => {\n const outcome = await runProgramCollection(length, task, {\n concurrency,\n stopOnResultError: true\n })\n const failure = firstProgramFailure(outcome.results, outcome.defects)\n\n if (failure?.kind === 'defect') {\n throw failure.cause\n }\n\n if (failure?.kind === 'result') {\n return failure.result\n }\n\n // SAFETY: The scheduler records one Result per claimed index before completing successfully.\n return Result.all(outcome.results as AnyResult[])\n}\n\nconst runAllResultsCollection = async (\n length: number,\n task: (index: number) => AnyResult | PromiseLike<AnyResult>,\n concurrency: number | undefined\n): Promise<AnyResult> => {\n const outcome = await runProgramCollection(length, task, {\n concurrency,\n stopOnResultError: false\n })\n const defect = firstProgramDefect(outcome.defects)\n\n if (defect !== undefined) {\n throw defect.cause\n }\n\n // SAFETY: The scheduler records each Result object at its input index.\n return Result.ok(outcome.results as AnyResult[])\n}\n\n/** Build a lazy Program collection with optional bounded concurrency. */\nexport function programAll<const Programs extends readonly AnyProgram[]>(\n programs: Programs,\n options: ProgramAllOptions = {}\n): ProgramAllResult<Programs> {\n const concurrency = options.concurrency\n validateProgramConcurrency(concurrency)\n const program = () =>\n runShortCircuitingCollection(programs.length, (index) => programs[index]!(), concurrency)\n\n // SAFETY: Program channels are declaration-only and are restored from the input tuple here.\n return program as ProgramAllResult<Programs>\n}\n\n/** Build a lazy Program collection from an input array and Program factory. */\nexport function programForEach<const Items extends readonly unknown[], Child extends AnyProgram>(\n items: Items,\n makeProgram: (item: Items[number], index: number) => Child,\n options: ProgramAllOptions = {}\n): ProgramForEachResult<Child> {\n const concurrency = options.concurrency\n validateProgramConcurrency(concurrency)\n const program = () =>\n runShortCircuitingCollection(\n items.length,\n (index) => makeProgram(items[index]!, index)(),\n concurrency\n )\n\n // SAFETY: Program channels are declaration-only and are restored from the factory's result type.\n return program as ProgramForEachResult<Child>\n}\n\n/** Build a lazy Program collection that retains every child Result. */\nexport function programAllResults<const Programs extends readonly AnyProgram[]>(\n programs: Programs,\n options: ProgramAllOptions = {}\n): ProgramAllResultsResult<Programs> {\n const concurrency = options.concurrency\n validateProgramConcurrency(concurrency)\n const program = () =>\n runAllResultsCollection(programs.length, (index) => programs[index]!(), concurrency)\n\n // SAFETY: Program channels are declaration-only and are restored from the input tuple here.\n return program as ProgramAllResultsResult<Programs>\n}\n\n/** Value-level namespace for lazy Program combinators. */\nexport const Program = {\n all: programAll,\n forEach: programForEach,\n allResults: programAllResults,\n map: programMap,\n mapError: programMapError,\n andThen: programAndThen,\n tap: programTap,\n tapError: programTapError,\n recover: programRecover\n} as const\n\n/**\n * Acquire a resource in the current Scope and register its release callback.\n *\n * Acquisition failures are represented in the Effect Result error channel;\n * release failures remain owned by Scope cleanup. The release callback\n * receives the final outcome chosen by the enclosing execution boundary.\n *\n * @example\n * ```ts\n * const connection = yield* Effect.acquireRelease(\n * () => pool.connect(),\n * (connection, outcome) => connection.close(outcome)\n * )\n * ```\n */\nexport function acquireRelease<R>(\n acquire: () => MaybePromise<R>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.acquire(acquire, release)))\n}\n\nclass AcquireReleaseResultFailure<R, E> {\n constructor(readonly result: Err<R, E>) {}\n}\n\n/**\n * Acquire a Result-valued resource and register only successful acquisitions.\n *\n * Typed acquisition failures remain unchanged in the Effect error channel;\n * unexpected acquisition and registration failures are normalized by\n * `better-result`. Release failures remain Scope cleanup failures.\n */\nexport function acquireReleaseResult<R, E>(\n acquire: () => MaybePromise<ResultType<R, E>>,\n release: (resource: R, outcome: ScopeOutcome) => MaybePromise<void>\n): AsyncGenerator<Err<never, E | UnhandledException>, R, unknown> {\n const scope = Scope.current()\n const registered = Result.tryPromise(async (): Promise<ResultType<R, E>> => {\n try {\n const resource = await scope.acquire(async () => {\n const result = await acquire()\n\n if (Result.isError(result)) {\n throw new AcquireReleaseResultFailure(result)\n }\n\n return result.value\n }, release)\n\n return Result.ok(resource)\n } catch (cause) {\n if (cause instanceof AcquireReleaseResultFailure) {\n return cause.result\n }\n\n throw cause\n }\n })\n\n return Result.await(registered.then((result) => result.andThen((acquired) => acquired)))\n}\n\n/**\n * Lazily acquire and register a disposable resource in the current Scope.\n *\n * Disposal is delegated to `Scope.add`, including protocol preference,\n * validation, race-safe registration, and cleanup error handling.\n */\nexport function acquireDisposable<R extends DisposableResource>(\n acquire: () => MaybePromise<R>\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(async () => scope.add(await acquire())))\n}\n\n/**\n * Register an already-acquired disposable resource in the current Scope.\n *\n * The resource is not acquired by this helper. Registration failures are\n * represented in the Effect Result error channel; disposal failures remain\n * owned by Scope cleanup.\n *\n * @example\n * ```ts\n * const file = yield* Effect.add(await openFile('notes.txt'))\n * ```\n */\nexport function add<R extends DisposableResource>(\n resource: R\n): AsyncGenerator<Err<never, UnhandledException>, R, unknown> {\n const scope = Scope.current()\n\n return Result.await(Result.tryPromise(() => scope.add(resource)))\n}\n\n/**\n * Effect namespace containing generator, resource, and Result combinators.\n *\n * Prefer these helpers when a program needs typed Service requirements or\n * Scope-aware acquisition and cleanup.\n */\ntype EffectNamespace = {\n readonly gen: typeof gen\n readonly fn: typeof fn\n readonly acquireRelease: typeof acquireRelease\n readonly acquireReleaseResult: typeof acquireReleaseResult\n readonly acquireDisposable: typeof acquireDisposable\n readonly add: typeof add\n readonly map: typeof map\n readonly mapError: typeof mapError\n readonly andThen: typeof andThen\n readonly andThenAsync: typeof andThenAsync\n readonly tap: typeof tap\n readonly tapAsync: typeof tapAsync\n readonly tapError: typeof tapError\n readonly tapErrorAsync: typeof tapErrorAsync\n readonly tapBoth: typeof tapBoth\n readonly tapBothAsync: typeof tapBothAsync\n readonly matchError: typeof matchError\n readonly matchErrorPartial: typeof matchErrorPartial\n readonly recover: typeof recover\n readonly recoverAsync: typeof recoverAsync\n readonly flatten: typeof flatten\n readonly as: typeof as\n readonly asVoid: typeof asVoid\n readonly match: typeof match\n readonly all: typeof all\n readonly zip: typeof zip\n}\n\nexport const Effect: EffectNamespace = {\n /** Compose a generator-based Effect program. */\n gen,\n /** Build a lazy Program from a generator. */\n fn,\n /** Acquire and register a resource in the current Scope. */\n acquireRelease,\n /** Acquire a Result-valued resource and register successful acquisitions. */\n acquireReleaseResult,\n /** Acquire and register a disposable resource in the current Scope. */\n acquireDisposable,\n /** Register an already-acquired disposable in the current Scope. */\n add,\n /** Map a successful Effect result. */\n map,\n /** Map an Effect error. */\n mapError,\n /** Chain a synchronous Effect result. */\n andThen,\n /** Chain an asynchronous Effect result. */\n andThenAsync,\n /** Observe successful values without changing the Result. */\n tap,\n /** Observe successful values asynchronously without changing the Result. */\n tapAsync,\n /** Observe error values without changing the Result. */\n tapError,\n /** Observe error values asynchronously without changing the Result. */\n tapErrorAsync,\n /** Observe the active Result branch without changing the Result. */\n tapBoth,\n /** Observe the active Result branch asynchronously without changing the Result. */\n tapBothAsync,\n /** Match every tagged error variant and map it to a new error value. */\n matchError,\n /** Match selected tagged errors and retain unhandled variants. */\n matchErrorPartial,\n /** Recover an error with another Effect. */\n recover,\n /** Recover an error asynchronously with another Effect. */\n recoverAsync,\n /** Remove one nested Effect layer. */\n flatten,\n /** Replace a successful value. */\n as,\n /** Replace a successful value with void. */\n asVoid,\n /** Match either Result branch. */\n match,\n /** Collect Effects in input order. */\n all,\n /** Zip two Effects in input order. */\n zip\n} as const\n\n/** Type-level aliases for inspecting Effect result channels and requirements. */\nexport declare namespace Effect {\n /** A nominal lazy computation that produces an Effect when invoked. */\n export type Program<A, E, R extends AnyService = never> = LazyProgram<A, E, R>\n\n /** Extract the success channel from an Effect result or Promise. */\n export type Success<T> = EffectSuccess<T>\n\n /** Extract the error channel from an Effect result or Promise. */\n export type Error<T> = EffectError<T>\n\n /** Extract the Service requirements from an Effect result or Promise. */\n export type Requirements<T> = EffectRequirements<T>\n\n /** An Effect with erased success, error, and requirements. */\n export type Any = AnyEffect\n}\n"],"mappings":";;;;AAwLA,MAAM,YAAmB,UAAuC;CAE9D,OAAO;AACT;AAEA,MAAM,aACJ,QACA,OAC+B;CAE/B,OAAO,OAAO,IAAI,QAAQ,EAAE;AAC9B;AAEA,MAAM,kBACJ,QACA,OACgC;CAEhC,OAAO,OAAO,SAAS,QAAQ,EAAE;AACnC;AAEA,MAAM,iBAQJ,QACA,SACsD;CAEtD,MAAM,aAAa;CAGnB,OAAO,OAAO,QAAQ,QAAQ,UAAU;AAC1C;AAEA,MAAM,sBAQJ,QACA,SAC+D;CAE/D,MAAM,cAAc,UAAa;EAE/B,OAAO,QAAQ,QAAQ,KAAK,KAAK,CAAC;CACpC;CAGA,OAAO,OAAO,aAAa,QAAQ,UAAU;AAG/C;AAmBA,SAAgBA,MAAI,OAAwB,QAAkC;CAC5E,IAAI,iBAAiB,YAAY,WAAW,KAAA,GAAW;EAErD,MAAM,WAAW;EAEjB,QAAQ,WAA2B;GAEjC,OAAOA,MAAI,QAAiB,QAAiB;EAC/C;CACF;CAGA,MAAM,KAAK;CAEX,IAAI,cAAc,KAAK,GACrB,OAAO,QAAQ,QAAQ,KAAK,CAAC,CAAC,MAAM,WAAW;EAE7C,OAAO,UAAU,QAAgC,EAAE;CACrD,CAAC;CAIH,OAAO,UAAU,OAA+B,EAAE;AACpD;AAgBA,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CAC5D,MAAM,QAAQ,MAAM,QAAQ;CAE5B,OAAO,OAAO,MAAM,OAAO,iBAAiB,MAAM,IAAI,QAAQ,CAAC,CAAC;AAClE;AAqCA,MAAa,SAA0B;;CAErC;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA,KAAA;;CAEA,UAAA;;CAEA,SAAA;;CAEA;;CAEA,KAAA;;CAEA;;CAEA,UAAA;;CAEA;;CAEA;;CAEA;;CAEA,YAAA;;CAEA,mBAAA;;CAEA,SAAA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;;CAEA;AACF"}
@@ -0,0 +1,12 @@
1
+ //#region src/runtime/errors.d.ts
2
+ /** Thrown when no RuntimeContext is active in the selected storage. */
3
+ declare class RuntimeContextNotConfiguredError extends Error {
4
+ constructor();
5
+ }
6
+ /** Thrown when ExplicitRuntimeContextStorage cannot safely overlap lineages. */
7
+ declare class RuntimeContextOverlapError extends Error {
8
+ constructor();
9
+ }
10
+ //#endregion
11
+ export { RuntimeContextOverlapError as n, RuntimeContextNotConfiguredError as t };
12
+ //# sourceMappingURL=errors-BKcsQ0ip.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors-BKcsQ0ip.d.mts","names":[],"sources":["../src/runtime/errors.ts"],"mappings":";;cACa,yCAAyC;EAAA;;;cASzC,mCAAmC;EAAA"}
package/dist/hono.d.mts CHANGED
@@ -1,7 +1,7 @@
1
- import { A as ProgramFromGenerator, D as EffectYield, E as EffectSuccess, M as AnyService, k as Program } from "./index-1NLNdkJy.mjs";
2
- import { E as MissingDependencies, S as LayerInput, w as ProvidedEnvironment, x as ExecutionMissing } from "./index-EJlskfAW.mjs";
3
- import { f as Runtime } from "./index-BsPr7qHf.mjs";
4
- import { a as CurrentRequest } from "./index-CITM15SE.mjs";
1
+ import { A as ProgramFromGenerator, C as EffectError, D as EffectYield, E as EffectSuccess, M as AnyService, k as Program } from "./index-heuaRmXR.mjs";
2
+ import { E as LayerInput, M as RequiredEnvironment, N as ValidateLayerInput, P as ValidateOneOverride, R as MissingDependencies, T as ExecutionMissing, j as ProvidedEnvironment, k as MissingServices } from "./index-rQhZk3Nt.mjs";
3
+ import { f as Runtime } from "./index-C7Qild0_.mjs";
4
+ import { a as CurrentRequest } from "./index-DStz0JMN.mjs";
5
5
  import { Result } from "better-result";
6
6
  import { Context, Env, Handler, HonoRequest, Input, MiddlewareHandler } from "hono";
7
7
  //#region src/hono/types.d.ts
@@ -9,9 +9,10 @@ type AnyResult = Result<any, any>;
9
9
  type AnyProgram = Program<any, any, AnyService>;
10
10
  type HonoContext = Context<any, any, any>;
11
11
  type ResponseLike = Response | Promise<Response>;
12
- type AnyHonoMiddleware = MiddlewareHandler<any, any, any, any>;
13
- type MiddlewareInput<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<any, any, infer InputType, any> ? InputType : Input;
14
- type MiddlewareInputs<Middlewares extends readonly AnyHonoMiddleware[]> = Middlewares extends readonly [infer Head extends AnyHonoMiddleware, ...infer Tail extends AnyHonoMiddleware[]] ? MiddlewareInput<Head> & MiddlewareInputs<Tail> : Input;
12
+ type AnyHonoMiddleware = MiddlewareHandler<any, any, any>;
13
+ type MiddlewareInput<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<any, any, infer InputType> ? InputType : Input;
14
+ type UnionToIntersection<Union> = (Union extends unknown ? (value: Union) => void : never) extends ((value: infer Intersection) => void) ? Intersection : never;
15
+ type MiddlewareInputs<Middlewares extends readonly AnyHonoMiddleware[]> = Middlewares extends readonly [] ? Input : Input & UnionToIntersection<MiddlewareInput<Middlewares[number]>>;
15
16
  type ValidatedTarget<InputType extends Input, Target extends 'param' | 'header'> = NonNullable<InputType['out']> extends Record<Target, infer Value> ? Value extends object ? Value : never : never;
16
17
  type ValidatedRequest<P extends string, InputType extends Input> = Omit<HonoRequest<P, NonNullable<InputType['out']>>, 'param' | 'header'> & {
17
18
  param: [ValidatedTarget<InputType, 'param'>] extends [never] ? HonoRequest<P, NonNullable<InputType['out']>>['param'] : {
@@ -28,18 +29,36 @@ type ValidatedRequest<P extends string, InputType extends Input> = Omit<HonoRequ
28
29
  type HonoEffectContext<E extends Env, P extends string, InputType extends Input> = Omit<Context<E, P, InputType>, 'req'> & {
29
30
  readonly req: ValidatedRequest<P, InputType>;
30
31
  };
31
- type MiddlewareEnvironment<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<infer Environment, any, any, any> ? Environment : Env;
32
- type MiddlewarePath<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<any, infer Path, any, any> ? Path : string;
32
+ type IsAny<Type> = 0 extends 1 & Type ? true : false;
33
+ type Specific<Type> = IsAny<Type> extends true ? never : Type;
34
+ type MiddlewareEnvironmentOf<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<infer Environment, any, any> ? Environment : never;
35
+ type MiddlewarePathOf<Middleware extends AnyHonoMiddleware> = Middleware extends MiddlewareHandler<any, infer Path, any> ? Path : never;
36
+ type MiddlewareEnvironmentCandidates<Middlewares extends readonly AnyHonoMiddleware[]> = Middlewares extends readonly [infer Head extends AnyHonoMiddleware, ...infer Tail extends readonly AnyHonoMiddleware[]] ? Specific<MiddlewareEnvironmentOf<Head>> | MiddlewareEnvironmentCandidates<Tail> : Specific<MiddlewareEnvironmentOf<Middlewares[number]>>;
37
+ type MiddlewarePathCandidates<Middlewares extends readonly AnyHonoMiddleware[]> = Middlewares extends readonly [infer Head extends AnyHonoMiddleware, ...infer Tail extends readonly AnyHonoMiddleware[]] ? Specific<MiddlewarePathOf<Head>> extends (infer Path) ? Path extends string ? string extends Path ? MiddlewarePathCandidates<Tail> : Path | MiddlewarePathCandidates<Tail> : MiddlewarePathCandidates<Tail> : never : Specific<MiddlewarePathOf<Middlewares[number]>> extends (infer Path) ? Path extends string ? string extends Path ? never : Path : never : never;
38
+ type MiddlewareEnvironment<Middlewares extends readonly AnyHonoMiddleware[]> = [MiddlewareEnvironmentCandidates<Middlewares>] extends [never] ? Env : Extract<UnionToIntersection<MiddlewareEnvironmentCandidates<Middlewares>>, Env>;
39
+ type MiddlewarePath<Middlewares extends readonly AnyHonoMiddleware[]> = [MiddlewarePathCandidates<Middlewares>] extends [never] ? string : MiddlewarePathCandidates<Middlewares>;
33
40
  type HonoJsonValue = null | boolean | number | string | readonly HonoJsonValue[] | {
34
41
  readonly [key: string]: HonoJsonValue;
35
42
  };
36
43
  type DefaultRequestLayer = ReturnType<typeof CurrentRequest.layer>;
37
44
  type RequestProvided<RequestLayer extends LayerInput> = ProvidedEnvironment<RequestLayer>;
38
45
  type AvailableServices<Provided extends AnyService, RequestLayer extends LayerInput> = Provided | InstanceType<typeof CurrentRequest> | RequestProvided<RequestLayer>;
46
+ type InvalidFailure<Actual, Expected> = {
47
+ readonly __betterEffectInvalidHonoFailure: {
48
+ readonly actual: Actual;
49
+ readonly expected: Expected;
50
+ };
51
+ };
52
+ type FailureCheck<Failure, Actual> = [Actual] extends [Failure] ? unknown : InvalidFailure<Actual, Failure>;
53
+ type ProgramFailure<Failure, Program extends AnyProgram> = FailureCheck<Failure, EffectError<Program>>;
54
+ type RequestLayerMissing<Provided extends AnyService, RequestLayer extends LayerInput> = MissingServices<Extract<RequiredEnvironment<RequestLayer>, AnyService>, Extract<Provided | InstanceType<typeof CurrentRequest>, AnyService>>;
55
+ type RequestLayerChecks<Provided extends AnyService, RequestLayer extends LayerInput> = ValidateLayerInput<RequestLayer> & ValidateOneOverride<DefaultRequestLayer, RequestLayer> & ([RequestLayerMissing<Provided, RequestLayer>] extends [never] ? unknown : MissingDependencies<RequestLayerMissing<Provided, RequestLayer>>);
56
+ /** Validate a request Layer against the Runtime root and built-in CurrentRequest provider. */
57
+ type HonoRequestLayerChecks<Provided extends AnyService, RequestLayer extends LayerInput> = RequestLayerChecks<Provided, RequestLayer>;
39
58
  type ProgramMissing<Provided extends AnyService, Program extends AnyProgram> = ExecutionMissing<Provided, Program>;
40
- type CompleteProgram<Provided extends AnyService, Program extends AnyProgram> = [ProgramMissing<Provided, Program>] extends [never] ? Program : Program & MissingDependencies<ProgramMissing<Provided, Program>>;
59
+ type CompleteProgram<Provided extends AnyService, Program extends AnyProgram, Failure = unknown> = Program & ([ProgramMissing<Provided, Program>] extends [never] ? unknown : MissingDependencies<ProgramMissing<Provided, Program>>) & ProgramFailure<Failure, Program>;
41
60
  type GeneratorBody<ContextType extends object, Yield extends EffectYield, Returned extends AnyResult> = (context: ContextType) => Generator<Yield, Returned, unknown> | AsyncGenerator<Yield, Returned, unknown>;
42
- type GeneratorChecks<Provided extends AnyService, Yield extends EffectYield, Returned extends AnyResult> = [ProgramMissing<Provided, ProgramFromGenerator<Yield, Returned>>] extends [never] ? unknown : MissingDependencies<ProgramMissing<Provided, ProgramFromGenerator<Yield, Returned>>>;
61
+ type GeneratorChecks<Provided extends AnyService, Yield extends EffectYield, Returned extends AnyResult, Failure = unknown> = ([ProgramMissing<Provided, ProgramFromGenerator<Yield, Returned>>] extends [never] ? unknown : MissingDependencies<ProgramMissing<Provided, ProgramFromGenerator<Yield, Returned>>>) & FailureCheck<Failure, EffectError<ProgramFromGenerator<Yield, Returned>>>;
43
62
  type HonoEffectSuccess<A = unknown> = {
44
63
  readonly value: A;
45
64
  readonly status?: number;
@@ -57,6 +76,8 @@ type HonoEffectRouteOptions<A, ContextType extends HonoContext = HonoContext> =
57
76
  };
58
77
  //#endregion
59
78
  //#region src/hono/hono-effect.d.ts
79
+ type HonoRouteArguments<Middlewares extends readonly AnyHonoMiddleware[], Body, Options> = [...middlewares: Middlewares, body: Body] | [...middlewares: Middlewares, body: Body, options: Options | undefined];
80
+ type HonoHandlerFactory<ContextType extends object, Provided extends AnyService, Failure, ProgramFactory extends (context: ContextType) => AnyProgram> = ProgramFactory & ([ReturnType<ProgramFactory>] extends [CompleteProgram<Provided, ReturnType<ProgramFactory>, Failure>] ? unknown : (context: ContextType) => CompleteProgram<Provided, ReturnType<ProgramFactory>, Failure>);
60
81
  /** Run Effect Programs inside one Runtime execution per Hono request. */
61
82
  declare class HonoEffect<Provided extends AnyService = any, Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer> {
62
83
  readonly runtime: Runtime<Provided>;
@@ -65,17 +86,14 @@ declare class HonoEffect<Provided extends AnyService = any, Failure = unknown, R
65
86
  private readonly onFailure;
66
87
  private readonly requestLayer;
67
88
  private constructor();
68
- static make<Provided extends AnyService, Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer>(runtime: Runtime<Provided>, options?: HonoEffectOptions<Failure, RequestLayer>): HonoEffect<Provided, Failure, RequestLayer>;
89
+ static make<Provided extends AnyService, Failure = unknown, RequestLayer extends LayerInput = DefaultRequestLayer>(runtime: Runtime<Provided>, options?: HonoEffectOptions<Failure, RequestLayer> & HonoRequestLayerChecks<Provided, RequestLayer>): HonoEffect<Provided, Failure, RequestLayer>;
69
90
  middleware<E extends Env = Env, Path extends string = string>(): MiddlewareHandler<E, Path>;
70
- handler<E extends Env = Env, Path extends string = string, InputType extends Input = Input, Program extends AnyProgram = AnyProgram>(makeProgram: (context: Context<E, Path, InputType>) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>, options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, InputType>>): Handler<E, Path, InputType, Promise<Response>>;
71
- handler<const FirstMiddleware extends AnyHonoMiddleware, const SecondMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<FirstMiddleware>, Path extends string = MiddlewarePath<FirstMiddleware>, Program extends AnyProgram = AnyProgram>(firstMiddleware: FirstMiddleware, secondMiddleware: SecondMiddleware, makeProgram: (context: HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>, options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>>): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>, Promise<Response>>;
72
- handler<const FirstMiddleware extends AnyHonoMiddleware, const SecondMiddleware extends AnyHonoMiddleware, const ThirdMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<FirstMiddleware>, Path extends string = MiddlewarePath<FirstMiddleware>, Program extends AnyProgram = AnyProgram>(firstMiddleware: FirstMiddleware, secondMiddleware: SecondMiddleware, thirdMiddleware: ThirdMiddleware, makeProgram: (context: HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>, options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>>): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>, Promise<Response>>;
73
- handler<const InputMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<InputMiddleware>, Path extends string = MiddlewarePath<InputMiddleware>, Program extends AnyProgram = AnyProgram>(inputMiddleware: InputMiddleware, makeProgram: (context: HonoEffectContext<E, Path, MiddlewareInput<InputMiddleware>>) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>, options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, MiddlewareInput<InputMiddleware>>>): Handler<E, Path, MiddlewareInput<InputMiddleware>, Promise<Response>>;
74
- gen<E extends Env = Env, Path extends string = string, InputType extends Input = Input, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>, options?: HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, InputType>>): Handler<E, Path, InputType, Promise<Response>>;
75
- gen<const FirstMiddleware extends AnyHonoMiddleware, const SecondMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<FirstMiddleware>, Path extends string = MiddlewarePath<FirstMiddleware>, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(firstMiddleware: FirstMiddleware, secondMiddleware: SecondMiddleware, body: GeneratorBody<HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>, options?: HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>>): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>, Promise<Response>>;
76
- gen<const FirstMiddleware extends AnyHonoMiddleware, const SecondMiddleware extends AnyHonoMiddleware, const ThirdMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<FirstMiddleware>, Path extends string = MiddlewarePath<FirstMiddleware>, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(firstMiddleware: FirstMiddleware, secondMiddleware: SecondMiddleware, thirdMiddleware: ThirdMiddleware, body: GeneratorBody<HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>, options?: HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>>): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>, Promise<Response>>;
77
- gen<const InputMiddleware extends AnyHonoMiddleware, E extends Env = MiddlewareEnvironment<InputMiddleware>, Path extends string = MiddlewarePath<InputMiddleware>, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(inputMiddleware: InputMiddleware, body: GeneratorBody<HonoEffectContext<E, Path, MiddlewareInput<InputMiddleware>>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>, options?: HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, MiddlewareInput<InputMiddleware>>>): Handler<E, Path, MiddlewareInput<InputMiddleware>, Promise<Response>>;
78
- guard<E extends Env = Env, Path extends string = string, InputType extends Input = Input, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>): MiddlewareHandler<E, Path>;
91
+ handler<E extends Env = Env, Path extends string = string, InputType extends Input = Input, Program extends AnyProgram = AnyProgram>(makeProgram: (context: Context<E, Path, InputType>) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program, Failure>, options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, InputType>>): Handler<E, Path, InputType, Promise<Response>>;
92
+ handler<const Middlewares extends readonly AnyHonoMiddleware[], E extends Env = MiddlewareEnvironment<Middlewares>, Path extends string = MiddlewarePath<Middlewares>, const ProgramFactory extends (context: HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>) => AnyProgram = (context: HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>) => AnyProgram>(...args: HonoRouteArguments<Middlewares, HonoHandlerFactory<HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>, AvailableServices<Provided, RequestLayer>, Failure, ProgramFactory>, HonoEffectRouteOptions<EffectSuccess<ReturnType<ProgramFactory>>, Context<E, Path, MiddlewareInputs<Middlewares>>>>): Handler<E, Path, MiddlewareInputs<Middlewares>, Promise<Response>>;
93
+ gen<E extends Env = Env, Path extends string = string, InputType extends Input = Input, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>, options?: HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, InputType>>): Handler<E, Path, InputType, Promise<Response>>;
94
+ gen<const Middlewares extends readonly AnyHonoMiddleware[], E extends Env = MiddlewareEnvironment<Middlewares>, Path extends string = MiddlewarePath<Middlewares>, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(...args: HonoRouteArguments<Middlewares, GeneratorBody<HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>, HonoEffectRouteOptions<EffectSuccess<ProgramFromGenerator<Yield, Returned>>, Context<E, Path, MiddlewareInputs<Middlewares>>>>): Handler<E, Path, MiddlewareInputs<Middlewares>, Promise<Response>>;
95
+ guard<E extends Env = Env, Path extends string = string, InputType extends Input = Input, const Yield extends EffectYield = EffectYield, const Returned extends AnyResult = AnyResult>(body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> & GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>): MiddlewareHandler<E, Path>;
96
+ private handleFailure;
79
97
  private makeHandler;
80
98
  private composeInputMiddleware;
81
99
  private getState;
@@ -1 +1 @@
1
- {"version":3,"file":"hono.d.mts","names":[],"sources":["../src/hono/types.ts","../src/hono/hono-effect.ts"],"mappings":";;;;;;;KASY,YAAY;KACZ,aAAa,kBAAsB;KACnC,cAAc;KACd,eAAe,WAAW,QAAQ;KAClC,oBAAoB;KAIpB,gBAAgB,mBAAmB,qBAC7C,mBAAmB,kCAAkC,kBAAkB,YAAY;KAEzE,iBAAiB,6BAA6B,uBACxD,oCACQ,aAAa,4BACV,aAAa,uBAEpB,gBAAgB,QAAQ,iBAAiB,QACzC;KAED,gBAAgB,kBAAkB,OAAO,qCAC5C,YAAY,0BAA0B,OAAO,cAAc,SACvD,uBACE;KAIH,iBAAiB,kBAAkB,kBAAkB,SAAS,KACjE,YAAY,GAAG,YAAY;EAG3B,QAAQ,gBAAgB,uCACpB,YAAY,GAAG,YAAY;KAExB,kBAAkB,gBAAgB,8B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QAAQ,aACpB,cAAc,cAAc,mBAC5B,iBAAiB,YAAY,WAEnC,MAAM,cAAc,QAAQ,GAAG,MAAM,YAAY,OAAO,YACtD,gBAAgB,kBAAkB,UAAU,eAAe,OAAO,UAAU,UAC9E,UAAU,uBACR,cAAc,qBAAqB,OAAO,YAC1C,QAAQ,GAAG,MAAM,cAElB,QAAQ,GAAG,MAAM,WAAW,QAAQ;EACvC,UACQ,6BAA6B,qBACnC,UAAU,MAAM,sBAAsB,cACtC,sBAAsB,eAAe,oBAC/B,cAAc,cAAc,mBAC5B,iBAAiB,YAAY,cAEhC,MAAM,mBACP,aACA,cAAc,kBAAkB,GAAG,MAAM,iBAAiB,eAAe,OAAO,YAC9E,gBAAgB,kBAAkB,UAAU,eAAe,OAAO,UAAU,UAC9E,uBACE,cAAc,qBAAqB,OAAO,YAC1C,QAAQ,GAAG,MAAM,iBAAiB,kBAGrC,QAAQ,GAAG,MAAM,iBAAiB,cAAc,QAAQ;EA8B3D,MACE,UAAU,MAAM,KAChB,8BACA,kBAAkB,QAAQ,aACpB,cAAc,cAAc,mBAC5B,iBAAiB,YAAY,WAEnC,MAAM,cAAc,QAAQ,GAAG,MAAM,YAAY,OAAO,YACtD,gBAAgB,kBAAkB,UAAU,eAAe,OAAO,UAAU,WAC7E,kBAAkB,GAAG;UAehB;UAWA;UAiCA;UA+BA;;cAWG,uCAAuC;EAAA"}
package/dist/hono.mjs CHANGED
@@ -1,9 +1,12 @@
1
- import { r as Layer } from "./signal-Cl9tqGyX.mjs";
2
- import { t as Effect } from "./effect-CZdZCZLW.mjs";
3
- import { a as CurrentRequest } from "./standard-services-QseopL9g.mjs";
1
+ import { r as Layer } from "./signal-B97cs85Z.mjs";
2
+ import { t as Effect } from "./effect-2ZcGZI8A.mjs";
3
+ import { a as CurrentRequest } from "./standard-services-BFBq-4lo.mjs";
4
4
  import { Result } from "better-result";
5
5
  import { createMiddleware } from "hono/factory";
6
6
  //#region src/hono/request-boundary.ts
7
+ const overrideRequestLayer = (base, replacement) => {
8
+ return Layer.override(base, replacement);
9
+ };
7
10
  const makeRequestBoundary = (options) => {
8
11
  return createMiddleware(async (context, next) => {
9
12
  const key = context;
@@ -16,7 +19,7 @@ const makeRequestBoundary = (options) => {
16
19
  try {
17
20
  const requestLayer = CurrentRequest.layer(context.req.raw);
18
21
  const customLayer = options.requestLayer?.(context);
19
- const layer = customLayer === void 0 ? requestLayer : Layer.override(requestLayer, customLayer);
22
+ const layer = customLayer === void 0 ? requestLayer : overrideRequestLayer(requestLayer, customLayer);
20
23
  await options.runtime.runWith(layer, async () => {
21
24
  try {
22
25
  await next();
@@ -34,6 +37,7 @@ const makeRequestBoundary = (options) => {
34
37
  };
35
38
  //#endregion
36
39
  //#region src/hono/responses.ts
40
+ const DEFAULT_FAILURE_MESSAGE = "Internal Server Error";
37
41
  const defaultSuccess = ({ value, status, serialize }, context) => {
38
42
  if (value instanceof Response) return value;
39
43
  const body = serialize === void 0 ? value : serialize(value);
@@ -43,8 +47,7 @@ const defaultSuccess = ({ value, status, serialize }, context) => {
43
47
  };
44
48
  const defaultFailure = (error, context) => {
45
49
  if (error instanceof Response) return error;
46
- const message = error instanceof Error ? error.message : String(error);
47
- return context.json({ error: message }, 500);
50
+ return context.json({ error: DEFAULT_FAILURE_MESSAGE }, 500);
48
51
  };
49
52
  //#endregion
50
53
  //#region src/hono/hono-effect.ts
@@ -61,8 +64,8 @@ var HonoEffect = class HonoEffect {
61
64
  this.onFailure = options.onFailure ?? defaultFailure;
62
65
  this.requestLayer = options.requestLayer;
63
66
  }
64
- static make(runtime, options = {}) {
65
- return new HonoEffect(runtime, options);
67
+ static make(runtime, options) {
68
+ return new HonoEffect(runtime, options ?? {});
66
69
  }
67
70
  middleware() {
68
71
  return makeRequestBoundary({
@@ -74,7 +77,7 @@ var HonoEffect = class HonoEffect {
74
77
  handler(...args) {
75
78
  const last = args.at(-1);
76
79
  const hasOptions = args.length > 1 && (last === void 0 || typeof last !== "function");
77
- const options = hasOptions ? last : {};
80
+ const options = (hasOptions ? last : {}) ?? {};
78
81
  const bodyIndex = hasOptions ? args.length - 2 : args.length - 1;
79
82
  const makeProgram = args[bodyIndex];
80
83
  let handler = this.makeHandler(makeProgram, options);
@@ -84,7 +87,7 @@ var HonoEffect = class HonoEffect {
84
87
  gen(...args) {
85
88
  const last = args.at(-1);
86
89
  const hasOptions = args.length > 1 && (last === void 0 || typeof last !== "function");
87
- const options = hasOptions ? last : {};
90
+ const options = (hasOptions ? last : {}) ?? {};
88
91
  const bodyIndex = hasOptions ? args.length - 2 : args.length - 1;
89
92
  const body = args[bodyIndex];
90
93
  let handler = this.makeHandler((context) => {
@@ -97,21 +100,19 @@ var HonoEffect = class HonoEffect {
97
100
  return async (context, next) => {
98
101
  const state = this.getState(context);
99
102
  const result = await Effect.fn(() => body(context))();
100
- if (Result.isError(result)) {
101
- state.failure ??= { cause: result.error };
102
- return await this.onFailure(result.error, context);
103
- }
103
+ if (Result.isError(result)) return await this.handleFailure(state, result.error, context);
104
104
  await next();
105
105
  };
106
106
  }
107
+ handleFailure(state, error, context) {
108
+ state.failure ??= { cause: error };
109
+ return this.onFailure(error, context);
110
+ }
107
111
  makeHandler(makeProgram, options) {
108
112
  return async (context) => {
109
113
  const state = this.getState(context);
110
114
  const result = await makeProgram(context)();
111
- if (Result.isError(result)) {
112
- state.failure ??= { cause: result.error };
113
- return await this.onFailure(result.error, context);
114
- }
115
+ if (Result.isError(result)) return await this.handleFailure(state, result.error, context);
115
116
  const value = result.value;
116
117
  if (options.respond !== void 0) return await options.respond(value, context);
117
118
  const success = { value };
@@ -123,9 +124,13 @@ var HonoEffect = class HonoEffect {
123
124
  composeInputMiddleware(inputMiddleware, handler) {
124
125
  return async (context, next) => {
125
126
  let downstreamResponse;
126
- const middlewareResponse = await inputMiddleware(context, async () => {
127
+ let nextCalled = false;
128
+ const nextOnce = async () => {
129
+ if (nextCalled) throw new Error("next() called multiple times");
130
+ nextCalled = true;
127
131
  downstreamResponse = await handler(context, next);
128
- });
132
+ };
133
+ const middlewareResponse = await inputMiddleware(context, nextOnce);
129
134
  if (middlewareResponse instanceof Response) return middlewareResponse;
130
135
  if (downstreamResponse !== void 0) return downstreamResponse;
131
136
  return context.res;
package/dist/hono.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"hono.mjs","names":[],"sources":["../src/hono/request-boundary.ts","../src/hono/responses.ts","../src/hono/hono-effect.ts"],"sourcesContent":["import { Result } from 'better-result'\nimport { createMiddleware } from 'hono/factory'\nimport type { Env, MiddlewareHandler } from 'hono'\n\nimport { CurrentRequest } from '../standard-services'\nimport { Layer } from '../layer'\nimport type { LayerInput } from '../layer/inference'\nimport { Runtime } from '../runtime'\nimport type { AnyService } from '../service'\nimport type { HonoContext } from './types'\n\nexport type RequestState = {\n failure?: {\n readonly cause: unknown\n }\n}\n\nexport type RequestBoundaryOptions<Provided extends AnyService, RequestLayer extends LayerInput> = {\n readonly runtime: Runtime<Provided>\n readonly states: WeakMap<object, RequestState>\n readonly requestLayer?: ((context: HonoContext) => RequestLayer) | undefined\n}\n\nexport const makeRequestBoundary = <\n Provided extends AnyService,\n RequestLayer extends LayerInput,\n E extends Env = Env,\n Path extends string = string\n>(\n options: RequestBoundaryOptions<Provided, RequestLayer>\n): MiddlewareHandler<E, Path> => {\n // SAFETY: createMiddleware preserves the Hono handler contract; only the generic Context is restored here.\n return createMiddleware(async (context, next) => {\n const key = context\n const existing = options.states.get(key)\n\n if (existing !== undefined) {\n await next()\n return\n }\n\n const state: RequestState = {}\n options.states.set(key, state)\n\n try {\n const requestLayer = CurrentRequest.layer(context.req.raw)\n const customLayer = options.requestLayer?.(context)\n // SAFETY: a custom request Layer extends or intentionally overrides the built-in CurrentRequest provider.\n const layer =\n customLayer === undefined\n ? requestLayer\n : Layer.override(requestLayer, customLayer as never)\n\n // SAFETY: request Layers are supplied by this adapter and execute inside the Runtime's typed boundary.\n await options.runtime.runWith(\n layer as never,\n async () => {\n try {\n await next()\n } catch (cause) {\n state.failure ??= { cause }\n }\n\n if (state.failure !== undefined) {\n return Result.err(state.failure.cause)\n }\n\n if (context.error !== undefined) {\n return Result.err(context.error)\n }\n\n return Result.ok(context.res)\n },\n { signal: context.req.raw.signal }\n )\n } finally {\n options.states.delete(key)\n }\n }) as MiddlewareHandler<E, Path>\n}\n","import type { HonoContext, HonoEffectSuccess } from './types'\n\nexport const defaultSuccess = (\n { value, status, serialize }: HonoEffectSuccess,\n context: HonoContext\n): Response => {\n if (value instanceof Response) {\n return value\n }\n\n const body = serialize === undefined ? value : serialize(value)\n\n if (body === undefined) {\n // SAFETY: route status is intentionally configurable and Hono validates it at response construction.\n return context.body(null, (status ?? 204) as never)\n }\n\n if (status === undefined) {\n return context.json({ data: body })\n }\n\n // SAFETY: route status is intentionally configurable and Hono validates it at response construction.\n return context.json({ data: body }, status as never)\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Result errors are intentionally opaque at this HTTP boundary.\nexport const defaultFailure = (error: unknown, context: HonoContext): Response => {\n if (error instanceof Response) {\n return error\n }\n\n const message = error instanceof Error ? error.message : String(error)\n\n return context.json({ error: message }, 500)\n}\n","import { Result } from 'better-result'\nimport type { Context, Env, Handler, Input, MiddlewareHandler } from 'hono'\n\nimport { Effect } from '../effect'\nimport type { EffectSuccess, EffectYield, ProgramFromGenerator } from '../effect/types'\nimport { Runtime } from '../runtime'\nimport type { LayerInput } from '../layer/inference'\nimport type { AnyService } from '../service'\nimport { makeRequestBoundary, type RequestState } from './request-boundary'\nimport { defaultFailure, defaultSuccess } from './responses'\nimport type {\n AnyGeneratorBody,\n AnyHonoMiddleware,\n AnyProgram,\n AnyProgramFactory,\n AnyResult,\n AnyRouteOptions,\n AvailableServices,\n CompleteProgram,\n DefaultRequestLayer,\n GeneratorBody,\n GeneratorChecks,\n HonoContext,\n HonoEffectContext,\n HonoEffectOptions,\n HonoEffectRouteOptions,\n HonoEffectSuccess,\n MiddlewareEnvironment,\n MiddlewareInput,\n MiddlewareInputs,\n MiddlewarePath\n} from './types'\n\n/** Run Effect Programs inside one Runtime execution per Hono request. */\nexport class HonoEffect<\n Provided extends AnyService = any,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer\n> {\n readonly runtime: Runtime<Provided>\n\n private readonly states = new WeakMap<object, RequestState>()\n\n private readonly onSuccess: NonNullable<HonoEffectOptions<Failure, RequestLayer>['onSuccess']>\n\n private readonly onFailure: NonNullable<HonoEffectOptions<Failure, RequestLayer>['onFailure']>\n\n private readonly requestLayer: HonoEffectOptions<Failure, RequestLayer>['requestLayer']\n\n private constructor(\n runtime: Runtime<Provided>,\n options: HonoEffectOptions<Failure, RequestLayer>\n ) {\n this.runtime = runtime\n this.onSuccess = options.onSuccess ?? defaultSuccess\n this.onFailure = options.onFailure ?? defaultFailure\n this.requestLayer = options.requestLayer\n }\n\n static make<\n Provided extends AnyService,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer\n >(\n runtime: Runtime<Provided>,\n options: HonoEffectOptions<Failure, RequestLayer> = {}\n ): HonoEffect<Provided, Failure, RequestLayer> {\n return new HonoEffect(runtime, options)\n }\n\n middleware<E extends Env = Env, Path extends string = string>(): MiddlewareHandler<E, Path> {\n return makeRequestBoundary<Provided, RequestLayer, E, Path>({\n runtime: this.runtime,\n states: this.states,\n requestLayer: this.requestLayer\n })\n }\n\n handler<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n Program extends AnyProgram = AnyProgram\n >(\n makeProgram: (\n context: Context<E, Path, InputType>\n ) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>,\n options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, InputType>>\n ): Handler<E, Path, InputType, Promise<Response>>\n handler<\n const FirstMiddleware extends AnyHonoMiddleware,\n const SecondMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<FirstMiddleware>,\n Path extends string = MiddlewarePath<FirstMiddleware>,\n Program extends AnyProgram = AnyProgram\n >(\n firstMiddleware: FirstMiddleware,\n secondMiddleware: SecondMiddleware,\n makeProgram: (\n context: HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>\n ) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<Program>,\n Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>\n >\n ): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>, Promise<Response>>\n handler<\n const FirstMiddleware extends AnyHonoMiddleware,\n const SecondMiddleware extends AnyHonoMiddleware,\n const ThirdMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<FirstMiddleware>,\n Path extends string = MiddlewarePath<FirstMiddleware>,\n Program extends AnyProgram = AnyProgram\n >(\n firstMiddleware: FirstMiddleware,\n secondMiddleware: SecondMiddleware,\n thirdMiddleware: ThirdMiddleware,\n makeProgram: (\n context: HonoEffectContext<\n E,\n Path,\n MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>\n >\n ) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<Program>,\n Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>\n >\n ): Handler<\n E,\n Path,\n MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>,\n Promise<Response>\n >\n handler<\n const InputMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<InputMiddleware>,\n Path extends string = MiddlewarePath<InputMiddleware>,\n Program extends AnyProgram = AnyProgram\n >(\n inputMiddleware: InputMiddleware,\n makeProgram: (\n context: HonoEffectContext<E, Path, MiddlewareInput<InputMiddleware>>\n ) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<Program>,\n Context<E, Path, MiddlewareInput<InputMiddleware>>\n >\n ): Handler<E, Path, MiddlewareInput<InputMiddleware>, Promise<Response>>\n handler(...args: unknown[]): Handler<any, any, any, Promise<Response>> {\n const last = args.at(-1)\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch separates route options from function callbacks.\n const hasOptions = args.length > 1 && (last === undefined || typeof last !== 'function')\n // SAFETY: the overloads restrict the optional trailing argument to route options.\n const options = (hasOptions ? last : {}) as AnyRouteOptions\n const bodyIndex = hasOptions ? args.length - 2 : args.length - 1\n // SAFETY: the overloads place the program factory immediately before route options.\n const makeProgram = args[bodyIndex] as AnyProgramFactory\n let handler = this.makeHandler(makeProgram, options)\n\n for (let index = bodyIndex - 1; index >= 0; index -= 1) {\n // SAFETY: every argument before the program factory is an input middleware by the overloads.\n handler = this.composeInputMiddleware(args[index] as AnyHonoMiddleware, handler)\n }\n\n return handler\n }\n\n gen<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, InputType>\n >\n ): Handler<E, Path, InputType, Promise<Response>>\n gen<\n const FirstMiddleware extends AnyHonoMiddleware,\n const SecondMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<FirstMiddleware>,\n Path extends string = MiddlewarePath<FirstMiddleware>,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n firstMiddleware: FirstMiddleware,\n secondMiddleware: SecondMiddleware,\n body: GeneratorBody<\n HonoEffectContext<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>,\n Yield,\n Returned\n > &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>>\n >\n ): Handler<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware]>, Promise<Response>>\n gen<\n const FirstMiddleware extends AnyHonoMiddleware,\n const SecondMiddleware extends AnyHonoMiddleware,\n const ThirdMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<FirstMiddleware>,\n Path extends string = MiddlewarePath<FirstMiddleware>,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n firstMiddleware: FirstMiddleware,\n secondMiddleware: SecondMiddleware,\n thirdMiddleware: ThirdMiddleware,\n body: GeneratorBody<\n HonoEffectContext<\n E,\n Path,\n MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>\n >,\n Yield,\n Returned\n > &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>>\n >\n ): Handler<\n E,\n Path,\n MiddlewareInputs<[FirstMiddleware, SecondMiddleware, ThirdMiddleware]>,\n Promise<Response>\n >\n gen<\n const InputMiddleware extends AnyHonoMiddleware,\n E extends Env = MiddlewareEnvironment<InputMiddleware>,\n Path extends string = MiddlewarePath<InputMiddleware>,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n inputMiddleware: InputMiddleware,\n body: GeneratorBody<\n HonoEffectContext<E, Path, MiddlewareInput<InputMiddleware>>,\n Yield,\n Returned\n > &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, MiddlewareInput<InputMiddleware>>\n >\n ): Handler<E, Path, MiddlewareInput<InputMiddleware>, Promise<Response>>\n gen(...args: unknown[]): Handler<any, any, any, Promise<Response>> {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch distinguishes middleware from the generator body.\n const last = args.at(-1)\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch separates route options from function callbacks.\n const hasOptions = args.length > 1 && (last === undefined || typeof last !== 'function')\n // SAFETY: the overloads restrict the optional trailing argument to route options.\n const options = (hasOptions ? last : {}) as AnyRouteOptions\n const bodyIndex = hasOptions ? args.length - 2 : args.length - 1\n // SAFETY: the overloads place the generator body immediately before route options.\n const body = args[bodyIndex] as AnyGeneratorBody\n\n let handler = this.makeHandler((context) => {\n // SAFETY: Effect.fn's runtime generator accepts both sync and async generators; the cast only joins its overloads.\n const program = Effect.fn(\n () => body(context) as AsyncGenerator<EffectYield, AnyResult, unknown>\n )\n\n // SAFETY: the public GeneratorChecks overload validates requirements before this erased boundary.\n return program as AnyProgram\n }, options)\n\n for (let index = bodyIndex - 1; index >= 0; index -= 1) {\n // SAFETY: every argument before the generator body is an input middleware by the overloads.\n handler = this.composeInputMiddleware(args[index] as AnyHonoMiddleware, handler)\n }\n\n return handler\n }\n\n guard<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned>\n ): MiddlewareHandler<E, Path> {\n return async (context, next) => {\n const state = this.getState(context)\n // SAFETY: Effect.fn accepts the sync or async generator supplied by the caller; this joins its overloads.\n const program = Effect.fn(() => body(context) as AsyncGenerator<Yield, Returned, unknown>)\n const result = await program()\n\n if (Result.isError(result)) {\n state.failure ??= { cause: result.error }\n // SAFETY: the configured failure policy is the boundary for this guard's Result error channel.\n return await this.onFailure(result.error as Failure, context)\n }\n\n await next()\n }\n }\n\n private makeHandler(\n makeProgram: (context: HonoContext) => AnyProgram,\n options: HonoEffectRouteOptions<any, any>\n ): Handler<any, any, any, Promise<Response>> {\n return async (context) => {\n const state = this.getState(context)\n const program = makeProgram(context)\n const result = await program()\n\n if (Result.isError(result)) {\n state.failure ??= { cause: result.error }\n // SAFETY: the configured failure policy is the boundary for this Program's Result error channel.\n return await this.onFailure(result.error as Failure, context)\n }\n\n const value = result.value\n\n if (options.respond !== undefined) {\n return await options.respond(value, context)\n }\n\n const success: HonoEffectSuccess<any> = { value }\n\n if (options.status !== undefined) {\n Object.assign(success, { status: options.status })\n }\n\n if (options.serialize !== undefined) {\n Object.assign(success, { serialize: options.serialize })\n }\n\n return await this.onSuccess(success, context)\n }\n }\n\n private composeInputMiddleware(\n inputMiddleware: AnyHonoMiddleware,\n handler: Handler<any, any, any, Promise<Response>>\n ): Handler<any, any, any, Promise<Response>> {\n return async (context, next) => {\n let downstreamResponse: Response | undefined\n\n const middlewareResponse = await inputMiddleware(context, async () => {\n downstreamResponse = await handler(context, next)\n })\n\n if (middlewareResponse instanceof Response) {\n return middlewareResponse\n }\n\n if (downstreamResponse !== undefined) {\n return downstreamResponse\n }\n\n return context.res\n }\n }\n\n private getState(context: HonoContext): RequestState {\n const state = this.states.get(context)\n\n if (state === undefined) {\n throw new HonoEffectBoundaryMissingError()\n }\n\n return state\n }\n}\n\nexport class HonoEffectBoundaryMissingError extends Error {\n constructor() {\n super('Register HonoEffect.middleware() before better-effect handlers')\n this.name = 'HonoEffectBoundaryMissingError'\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAa,uBAMX,YAC+B;CAE/B,OAAO,iBAAiB,OAAO,SAAS,SAAS;EAC/C,MAAM,MAAM;EAGZ,IAFiB,QAAQ,OAAO,IAAI,GAEzB,MAAM,KAAA,GAAW;GAC1B,MAAM,KAAK;GACX;EACF;EAEA,MAAM,QAAsB,CAAC;EAC7B,QAAQ,OAAO,IAAI,KAAK,KAAK;EAE7B,IAAI;GACF,MAAM,eAAe,eAAe,MAAM,QAAQ,IAAI,GAAG;GACzD,MAAM,cAAc,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A,IAAa,iCAAb,cAAoD,MAAM;CACxD,cAAc;EACZ,MAAM,gEAAgE;EACtE,KAAK,OAAO;CACd;AACF"}
1
+ {"version":3,"file":"hono.mjs","names":[],"sources":["../src/hono/request-boundary.ts","../src/hono/responses.ts","../src/hono/hono-effect.ts"],"sourcesContent":["import { Result } from 'better-result'\nimport { createMiddleware } from 'hono/factory'\nimport type { Env, MiddlewareHandler } from 'hono'\n\nimport { CurrentRequest } from '../standard-services'\nimport { Layer } from '../layer'\nimport type { LayerInput } from '../layer/inference'\nimport { Runtime } from '../runtime'\nimport type { AnyService } from '../service'\nimport type { HonoContext } from './types'\n\nexport type RequestState = {\n failure?: {\n readonly cause: unknown\n }\n}\n\nexport type RequestBoundaryOptions<Provided extends AnyService, RequestLayer extends LayerInput> = {\n readonly runtime: Runtime<Provided>\n readonly states: WeakMap<object, RequestState>\n readonly requestLayer?: ((context: HonoContext) => RequestLayer) | undefined\n}\n\nconst overrideRequestLayer = (base: LayerInput, replacement: LayerInput): Layer<any, any> => {\n // SAFETY: HonoEffect.make validates the concrete replacement before this erased dispatch boundary.\n return Layer.override(base, replacement as never)\n}\n\nexport const makeRequestBoundary = <\n Provided extends AnyService,\n RequestLayer extends LayerInput,\n E extends Env = Env,\n Path extends string = string\n>(\n options: RequestBoundaryOptions<Provided, RequestLayer>\n): MiddlewareHandler<E, Path> => {\n // SAFETY: createMiddleware preserves the Hono handler contract; only the generic Context is restored here.\n return createMiddleware(async (context, next) => {\n const key = context\n const existing = options.states.get(key)\n\n if (existing !== undefined) {\n await next()\n return\n }\n\n const state: RequestState = {}\n options.states.set(key, state)\n\n try {\n const requestLayer = CurrentRequest.layer(context.req.raw)\n const customLayer = options.requestLayer?.(context)\n const layer: Layer<any, any> =\n customLayer === undefined ? requestLayer : overrideRequestLayer(requestLayer, customLayer)\n\n await options.runtime.runWith(\n layer,\n async () => {\n try {\n await next()\n } catch (cause) {\n state.failure ??= { cause }\n }\n\n if (state.failure !== undefined) {\n return Result.err(state.failure.cause)\n }\n\n if (context.error !== undefined) {\n return Result.err(context.error)\n }\n\n return Result.ok(context.res)\n },\n { signal: context.req.raw.signal }\n )\n } finally {\n options.states.delete(key)\n }\n }) as MiddlewareHandler<E, Path>\n}\n","import type { HonoContext, HonoEffectSuccess } from './types'\n\nconst DEFAULT_FAILURE_MESSAGE = 'Internal Server Error'\n\nexport const defaultSuccess = (\n { value, status, serialize }: HonoEffectSuccess,\n context: HonoContext\n): Response => {\n if (value instanceof Response) {\n return value\n }\n\n const body = serialize === undefined ? value : serialize(value)\n\n if (body === undefined) {\n // SAFETY: route status is intentionally configurable and Hono validates it at response construction.\n return context.body(null, (status ?? 204) as never)\n }\n\n if (status === undefined) {\n return context.json({ data: body })\n }\n\n // SAFETY: route status is intentionally configurable and Hono validates it at response construction.\n return context.json({ data: body }, status as never)\n}\n\n// oxlint-disable-next-line anti-slop/no-unknown-parameters -- Result errors are intentionally opaque at this HTTP boundary.\nexport const defaultFailure = (error: unknown, context: HonoContext): Response => {\n if (error instanceof Response) {\n return error\n }\n\n return context.json({ error: DEFAULT_FAILURE_MESSAGE }, 500)\n}\n","import { Result } from 'better-result'\nimport type { Context, Env, Handler, Input, MiddlewareHandler } from 'hono'\n\nimport { Effect } from '../effect'\nimport type { EffectSuccess, EffectYield, ProgramFromGenerator } from '../effect/types'\nimport { Runtime } from '../runtime'\nimport type { LayerInput } from '../layer/inference'\nimport type { AnyService } from '../service'\nimport { makeRequestBoundary, type RequestState } from './request-boundary'\nimport { defaultFailure, defaultSuccess } from './responses'\nimport type {\n AnyGeneratorBody,\n AnyHonoMiddleware,\n AnyProgram,\n AnyProgramFactory,\n AnyResult,\n AnyRouteOptions,\n AvailableServices,\n CompleteProgram,\n DefaultRequestLayer,\n GeneratorBody,\n GeneratorChecks,\n HonoContext,\n HonoEffectContext,\n HonoEffectOptions,\n HonoEffectRouteOptions,\n HonoRequestLayerChecks,\n HonoEffectSuccess,\n MiddlewareEnvironment,\n ResponseLike,\n MiddlewareInputs,\n MiddlewarePath\n} from './types'\n\ntype HonoRouteArguments<Middlewares extends readonly AnyHonoMiddleware[], Body, Options> =\n | [...middlewares: Middlewares, body: Body]\n | [...middlewares: Middlewares, body: Body, options: Options | undefined]\n\ntype HonoHandlerFactory<\n ContextType extends object,\n Provided extends AnyService,\n Failure,\n ProgramFactory extends (context: ContextType) => AnyProgram\n> = ProgramFactory &\n ([ReturnType<ProgramFactory>] extends [\n CompleteProgram<Provided, ReturnType<ProgramFactory>, Failure>\n ]\n ? unknown\n : (context: ContextType) => CompleteProgram<Provided, ReturnType<ProgramFactory>, Failure>)\n\n/** Run Effect Programs inside one Runtime execution per Hono request. */\nexport class HonoEffect<\n Provided extends AnyService = any,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer\n> {\n readonly runtime: Runtime<Provided>\n\n private readonly states = new WeakMap<object, RequestState>()\n\n private readonly onSuccess: NonNullable<HonoEffectOptions<Failure, RequestLayer>['onSuccess']>\n\n private readonly onFailure: NonNullable<HonoEffectOptions<Failure, RequestLayer>['onFailure']>\n\n private readonly requestLayer: HonoEffectOptions<Failure, RequestLayer>['requestLayer']\n\n private constructor(\n runtime: Runtime<Provided>,\n options: HonoEffectOptions<Failure, RequestLayer>\n ) {\n this.runtime = runtime\n this.onSuccess = options.onSuccess ?? defaultSuccess\n this.onFailure = options.onFailure ?? defaultFailure\n this.requestLayer = options.requestLayer\n }\n\n static make<\n Provided extends AnyService,\n Failure = unknown,\n RequestLayer extends LayerInput = DefaultRequestLayer\n >(\n runtime: Runtime<Provided>,\n options?: HonoEffectOptions<Failure, RequestLayer> &\n HonoRequestLayerChecks<Provided, RequestLayer>\n ): HonoEffect<Provided, Failure, RequestLayer> {\n return new HonoEffect(runtime, options ?? {})\n }\n\n middleware<E extends Env = Env, Path extends string = string>(): MiddlewareHandler<E, Path> {\n return makeRequestBoundary<Provided, RequestLayer, E, Path>({\n runtime: this.runtime,\n states: this.states,\n requestLayer: this.requestLayer\n })\n }\n\n handler<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n Program extends AnyProgram = AnyProgram\n >(\n makeProgram: (\n context: Context<E, Path, InputType>\n ) => CompleteProgram<AvailableServices<Provided, RequestLayer>, Program, Failure>,\n options?: HonoEffectRouteOptions<EffectSuccess<Program>, Context<E, Path, InputType>>\n ): Handler<E, Path, InputType, Promise<Response>>\n handler<\n const Middlewares extends readonly AnyHonoMiddleware[],\n E extends Env = MiddlewareEnvironment<Middlewares>,\n Path extends string = MiddlewarePath<Middlewares>,\n const ProgramFactory extends (\n context: HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>\n ) => AnyProgram = (\n context: HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>\n ) => AnyProgram\n >(\n ...args: HonoRouteArguments<\n Middlewares,\n HonoHandlerFactory<\n HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>,\n AvailableServices<Provided, RequestLayer>,\n Failure,\n ProgramFactory\n >,\n HonoEffectRouteOptions<\n EffectSuccess<ReturnType<ProgramFactory>>,\n Context<E, Path, MiddlewareInputs<Middlewares>>\n >\n >\n ): Handler<E, Path, MiddlewareInputs<Middlewares>, Promise<Response>>\n handler(...args: unknown[]): Handler<any, any, any, Promise<Response>> {\n const last = args.at(-1)\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch separates route options from function callbacks.\n const hasOptions = args.length > 1 && (last === undefined || typeof last !== 'function')\n // SAFETY: the overloads restrict the optional trailing argument to route options.\n const options = ((hasOptions ? last : {}) ?? {}) as AnyRouteOptions\n const bodyIndex = hasOptions ? args.length - 2 : args.length - 1\n // SAFETY: the overloads place the program factory immediately before route options.\n const makeProgram = args[bodyIndex] as AnyProgramFactory\n let handler = this.makeHandler(makeProgram, options)\n\n for (let index = bodyIndex - 1; index >= 0; index -= 1) {\n // SAFETY: every argument before the program factory is an input middleware by the overloads.\n handler = this.composeInputMiddleware(args[index] as AnyHonoMiddleware, handler)\n }\n\n return handler\n }\n\n gen<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>,\n options?: HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, InputType>\n >\n ): Handler<E, Path, InputType, Promise<Response>>\n gen<\n const Middlewares extends readonly AnyHonoMiddleware[],\n E extends Env = MiddlewareEnvironment<Middlewares>,\n Path extends string = MiddlewarePath<Middlewares>,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n ...args: HonoRouteArguments<\n Middlewares,\n GeneratorBody<HonoEffectContext<E, Path, MiddlewareInputs<Middlewares>>, Yield, Returned> &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>,\n HonoEffectRouteOptions<\n EffectSuccess<ProgramFromGenerator<Yield, Returned>>,\n Context<E, Path, MiddlewareInputs<Middlewares>>\n >\n >\n ): Handler<E, Path, MiddlewareInputs<Middlewares>, Promise<Response>>\n gen(...args: unknown[]): Handler<any, any, any, Promise<Response>> {\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch distinguishes middleware from the generator body.\n const last = args.at(-1)\n // oxlint-disable-next-line anti-slop/no-runtime-typeof -- overload dispatch separates route options from function callbacks.\n const hasOptions = args.length > 1 && (last === undefined || typeof last !== 'function')\n // SAFETY: the overloads restrict the optional trailing argument to route options.\n const options = ((hasOptions ? last : {}) ?? {}) as AnyRouteOptions\n const bodyIndex = hasOptions ? args.length - 2 : args.length - 1\n // SAFETY: the overloads place the generator body immediately before route options.\n const body = args[bodyIndex] as AnyGeneratorBody\n\n let handler = this.makeHandler((context) => {\n // SAFETY: Effect.fn's runtime generator accepts both sync and async generators; the cast only joins its overloads.\n const program = Effect.fn(\n () => body(context) as AsyncGenerator<EffectYield, AnyResult, unknown>\n )\n\n // SAFETY: the public GeneratorChecks overload validates requirements before this erased boundary.\n return program as AnyProgram\n }, options)\n\n for (let index = bodyIndex - 1; index >= 0; index -= 1) {\n // SAFETY: every argument before the generator body is an input middleware by the overloads.\n handler = this.composeInputMiddleware(args[index] as AnyHonoMiddleware, handler)\n }\n\n return handler\n }\n\n guard<\n E extends Env = Env,\n Path extends string = string,\n InputType extends Input = Input,\n const Yield extends EffectYield = EffectYield,\n const Returned extends AnyResult = AnyResult\n >(\n body: GeneratorBody<Context<E, Path, InputType>, Yield, Returned> &\n GeneratorChecks<AvailableServices<Provided, RequestLayer>, Yield, Returned, Failure>\n ): MiddlewareHandler<E, Path> {\n return async (context, next) => {\n const state = this.getState(context)\n // SAFETY: Effect.fn accepts the sync or async generator supplied by the caller; this joins its overloads.\n const program = Effect.fn(() => body(context) as AsyncGenerator<Yield, Returned, unknown>)\n const result = await program()\n\n if (Result.isError(result)) {\n return await this.handleFailure(state, result.error, context)\n }\n\n await next()\n }\n }\n\n private handleFailure(\n state: RequestState,\n // oxlint-disable-next-line anti-slop/no-unknown-parameters -- Result errors are intentionally opaque at this HTTP boundary.\n error: unknown,\n context: HonoContext\n ): ResponseLike {\n state.failure ??= { cause: error }\n // SAFETY: the public handler, gen, and guard constraints validate this error against Failure.\n return this.onFailure(error as Failure, context)\n }\n\n private makeHandler(\n makeProgram: (context: HonoContext) => AnyProgram,\n options: HonoEffectRouteOptions<any, any>\n ): Handler<any, any, any, Promise<Response>> {\n return async (context) => {\n const state = this.getState(context)\n const program = makeProgram(context)\n const result = await program()\n\n if (Result.isError(result)) {\n return await this.handleFailure(state, result.error, context)\n }\n\n const value = result.value\n\n if (options.respond !== undefined) {\n return await options.respond(value, context)\n }\n\n const success: HonoEffectSuccess<any> = { value }\n\n if (options.status !== undefined) {\n Object.assign(success, { status: options.status })\n }\n\n if (options.serialize !== undefined) {\n Object.assign(success, { serialize: options.serialize })\n }\n\n return await this.onSuccess(success, context)\n }\n }\n\n private composeInputMiddleware(\n inputMiddleware: AnyHonoMiddleware,\n handler: Handler<any, any, any, Promise<Response>>\n ): Handler<any, any, any, Promise<Response>> {\n return async (context, next) => {\n let downstreamResponse: Response | undefined\n let nextCalled = false\n\n // Match Hono's compose guard: a middleware may advance the chain only once.\n const nextOnce = async (): Promise<void> => {\n if (nextCalled) {\n throw new Error('next() called multiple times')\n }\n\n nextCalled = true\n downstreamResponse = await handler(context, next)\n }\n const middlewareResponse = await inputMiddleware(context, nextOnce)\n\n if (middlewareResponse instanceof Response) {\n return middlewareResponse\n }\n\n if (downstreamResponse !== undefined) {\n return downstreamResponse\n }\n\n return context.res\n }\n }\n\n private getState(context: HonoContext): RequestState {\n const state = this.states.get(context)\n\n if (state === undefined) {\n throw new HonoEffectBoundaryMissingError()\n }\n\n return state\n }\n}\n\nexport class HonoEffectBoundaryMissingError extends Error {\n constructor() {\n super('Register HonoEffect.middleware() before better-effect handlers')\n this.name = 'HonoEffectBoundaryMissingError'\n }\n}\n"],"mappings":";;;;;;AAuBA,MAAM,wBAAwB,MAAkB,gBAA6C;CAE3F,OAAO,MAAM,SAAS,MAAM,WAAoB;AAClD;AAEA,MAAa,uBAMX,YAC+B;CAE/B,OAAO,iBAAiB,OAAO,SAAS,SAAS;EAC/C,MAAM,MAAM;EAGZ,IAFiB,QAAQ,OAAO,IAAI,GAEzB,MAAM,KAAA,GAAW;GAC1B,MAAM,KAAK;GACX;EACF;EAEA,MAAM,QAAsB,CAAC;EAC7B,QAAQ,OAAO,IAAI,KAAK,KAAK;EAE7B,IAAI;GACF,MAAM,eAAe,eAAe,MAAM,QAAQ,IAAI,GAAG;GACzD,MAAM,cAAc,QAAQ,eAAe,OAAO;GAClD,MAAM,QACJ,gBAAgB,KAAA,IAAY,eAAe,qBAAqB,cAAc,WAAW;GAE3F,MAAM,QAAQ,QAAQ,QACpB,OACA,YAAY;IACV,IAAI;KACF,MAAM,KAAK;IACb,SAAS,OAAO;KACd,MAAM,YAAY,EAAE,MAAM;IAC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