@nicolastoulemont/std 0.8.2 → 0.10.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.
- package/README.md +391 -40
- package/dist/brand/index.d.mts +1 -1
- package/dist/brand/index.mjs +1 -1
- package/dist/{brand-DZgGDrAe.mjs → brand-DP-C92GS.mjs} +2 -2
- package/dist/{brand-DZgGDrAe.mjs.map → brand-DP-C92GS.mjs.map} +1 -1
- package/dist/{brand.types-B3NDX1vo.d.mts → brand.types-C_7QgCA4.d.mts} +1 -1
- package/dist/{brand.types-B3NDX1vo.d.mts.map → brand.types-C_7QgCA4.d.mts.map} +1 -1
- package/dist/context/index.d.mts +1 -1
- package/dist/context/index.mjs +1 -1
- package/dist/{context-0xDbwtpx.mjs → context-7oKePrBY.mjs} +2 -2
- package/dist/{context-0xDbwtpx.mjs.map → context-7oKePrBY.mjs.map} +1 -1
- package/dist/{context-B2dWloPl.d.mts → context-B9oWzbwF.d.mts} +2 -2
- package/dist/{context-B2dWloPl.d.mts.map → context-B9oWzbwF.d.mts.map} +1 -1
- package/dist/data/index.d.mts +1 -1
- package/dist/data/index.mjs +1 -1
- package/dist/data-W10ldR5l.mjs +2 -0
- package/dist/data-W10ldR5l.mjs.map +1 -0
- package/dist/{dual-fN6OUwN_.mjs → dual-CZhzZslG.mjs} +1 -1
- package/dist/{dual-fN6OUwN_.mjs.map → dual-CZhzZslG.mjs.map} +1 -1
- package/dist/duration/index.d.mts +1 -1
- package/dist/duration/index.mjs +1 -1
- package/dist/{duration-CYoDHcOR.mjs → duration-Dwtjy95Z.mjs} +2 -2
- package/dist/{duration-CYoDHcOR.mjs.map → duration-Dwtjy95Z.mjs.map} +1 -1
- package/dist/either/index.d.mts +1 -1
- package/dist/either/index.mjs +1 -1
- package/dist/{either-G7uOu4Ar.mjs → either-B2TvVY_j.mjs} +2 -2
- package/dist/{either-G7uOu4Ar.mjs.map → either-B2TvVY_j.mjs.map} +1 -1
- package/dist/exit-DOdhmr81.d.mts +67 -0
- package/dist/exit-DOdhmr81.d.mts.map +1 -0
- package/dist/fiber/index.d.mts +2 -0
- package/dist/fiber/index.mjs +1 -0
- package/dist/fiber-CZsyrDdd.mjs +2 -0
- package/dist/fiber-CZsyrDdd.mjs.map +1 -0
- package/dist/{flow-CNyLsPGb.mjs → flow-D8_tllWl.mjs} +1 -1
- package/dist/{flow-CNyLsPGb.mjs.map → flow-D8_tllWl.mjs.map} +1 -1
- package/dist/functions/index.mjs +1 -1
- package/dist/functions-DmOZ7O4j.mjs +2 -0
- package/dist/{functions-ByAk682_.mjs.map → functions-DmOZ7O4j.mjs.map} +1 -1
- package/dist/fx/index.d.mts +1 -1
- package/dist/fx/index.mjs +1 -1
- package/dist/fx-DXBw4iYX.mjs +2 -0
- package/dist/fx-DXBw4iYX.mjs.map +1 -0
- package/dist/fx.runtime-B2_rL7h_.mjs +2 -0
- package/dist/fx.runtime-B2_rL7h_.mjs.map +1 -0
- package/dist/fx.runtime-BuIElLpZ.d.mts +16 -0
- package/dist/fx.runtime-BuIElLpZ.d.mts.map +1 -0
- package/dist/{fx.types-DyQVgTS8.mjs → fx.types-Bg-Mmdm5.mjs} +1 -1
- package/dist/{fx.types-DyQVgTS8.mjs.map → fx.types-Bg-Mmdm5.mjs.map} +1 -1
- package/dist/{fx.types-BdN1EWxr.d.mts → fx.types-CpFKa-Jj.d.mts} +1 -1
- package/dist/{fx.types-BdN1EWxr.d.mts.map → fx.types-CpFKa-Jj.d.mts.map} +1 -1
- package/dist/{index-DCUGtEcj.d.mts → index-5QkUtJ-4.d.mts} +4 -4
- package/dist/{index-DCUGtEcj.d.mts.map → index-5QkUtJ-4.d.mts.map} +1 -1
- package/dist/{index-C4DOLLaU.d.mts → index-B3xia3Jl.d.mts} +82 -58
- package/dist/index-B3xia3Jl.d.mts.map +1 -0
- package/dist/{index-CIvNgjsx.d.mts → index-B4rHoUK4.d.mts} +2 -2
- package/dist/{index-CIvNgjsx.d.mts.map → index-B4rHoUK4.d.mts.map} +1 -1
- package/dist/{index-BA0EsFxS.d.mts → index-BDUhDs4D.d.mts} +3 -3
- package/dist/{index-BA0EsFxS.d.mts.map → index-BDUhDs4D.d.mts.map} +1 -1
- package/dist/{index-CNTYbcY9.d.mts → index-BZ1-IrU_.d.mts} +1 -1
- package/dist/{index-CNTYbcY9.d.mts.map → index-BZ1-IrU_.d.mts.map} +1 -1
- package/dist/{index-uE3S3Krx.d.mts → index-BZP6t2h9.d.mts} +5 -5
- package/dist/{index-uE3S3Krx.d.mts.map → index-BZP6t2h9.d.mts.map} +1 -1
- package/dist/{index-D8rDE60Y.d.mts → index-Bu-z5Xoq.d.mts} +1 -1
- package/dist/index-Bu-z5Xoq.d.mts.map +1 -0
- package/dist/index-C8KMi_I9.d.mts +226 -0
- package/dist/index-C8KMi_I9.d.mts.map +1 -0
- package/dist/{index-dCRymj_g.d.mts → index-CfXGmPMY.d.mts} +5 -5
- package/dist/{index-dCRymj_g.d.mts.map → index-CfXGmPMY.d.mts.map} +1 -1
- package/dist/index-Cv48HmyO.d.mts +59 -0
- package/dist/index-Cv48HmyO.d.mts.map +1 -0
- package/dist/{index-B2Z7-XGR.d.mts → index-D-KxgnwF.d.mts} +59 -34
- package/dist/index-D-KxgnwF.d.mts.map +1 -0
- package/dist/{index-DR7hzXU4.d.mts → index-DLkMqvw4.d.mts} +137 -29
- package/dist/index-DLkMqvw4.d.mts.map +1 -0
- package/dist/index-DlWm_PwP.d.mts +436 -0
- package/dist/index-DlWm_PwP.d.mts.map +1 -0
- package/dist/{index-B0flvtFB.d.mts → index-DogEz6WQ.d.mts} +2 -2
- package/dist/{index-B0flvtFB.d.mts.map → index-DogEz6WQ.d.mts.map} +1 -1
- package/dist/{index-crtzMG48.d.mts → index-XxPUUAGQ.d.mts} +41 -6
- package/dist/index-XxPUUAGQ.d.mts.map +1 -0
- package/dist/{index-BqJ1GWAF.d.mts → index-pC80zLHb.d.mts} +2 -2
- package/dist/{index-BqJ1GWAF.d.mts.map → index-pC80zLHb.d.mts.map} +1 -1
- package/dist/index.d.mts +23 -20
- package/dist/index.mjs +1 -1
- package/dist/layer/index.d.mts +1 -1
- package/dist/layer/index.mjs +1 -1
- package/dist/layer-BmrPWBkT.mjs +2 -0
- package/dist/layer-BmrPWBkT.mjs.map +1 -0
- package/dist/{layer.types-BB0MrvLg.d.mts → layer.types-DsCTjICW.d.mts} +4 -4
- package/dist/{layer.types-BB0MrvLg.d.mts.map → layer.types-DsCTjICW.d.mts.map} +1 -1
- package/dist/log/index.d.mts +2 -0
- package/dist/log/index.mjs +1 -0
- package/dist/log-Bh8G5umo.mjs +2 -0
- package/dist/log-Bh8G5umo.mjs.map +1 -0
- package/dist/multithread/index.d.mts +1 -1
- package/dist/multithread/index.mjs +1 -1
- package/dist/multithread-CovZ2ioL.mjs +21 -0
- package/dist/multithread-CovZ2ioL.mjs.map +1 -0
- package/dist/option/index.d.mts +1 -1
- package/dist/option/index.mjs +1 -1
- package/dist/{option-C2iCxAuJ.mjs → option-BlyP5LA2.mjs} +2 -2
- package/dist/{option-C2iCxAuJ.mjs.map → option-BlyP5LA2.mjs.map} +1 -1
- package/dist/{option.types-D9hrKcfa.d.mts → option.types-DLp3QpFE.d.mts} +3 -3
- package/dist/{option.types-D9hrKcfa.d.mts.map → option.types-DLp3QpFE.d.mts.map} +1 -1
- package/dist/{option.types-CbY_swma.mjs → option.types-bFFSErJ-.mjs} +1 -1
- package/dist/{option.types-CbY_swma.mjs.map → option.types-bFFSErJ-.mjs.map} +1 -1
- package/dist/order/index.d.mts +1 -1
- package/dist/order/index.mjs +1 -1
- package/dist/{order-BXOBEKvB.mjs → order-VTXpppmI.mjs} +2 -2
- package/dist/{order-BXOBEKvB.mjs.map → order-VTXpppmI.mjs.map} +1 -1
- package/dist/{pipeable-BIrevC0D.d.mts → pipeable-BY9yPsNK.d.mts} +1 -1
- package/dist/{pipeable-BIrevC0D.d.mts.map → pipeable-BY9yPsNK.d.mts.map} +1 -1
- package/dist/pipeable-COGyGMUV.mjs +2 -0
- package/dist/{pipeable-Dp1_23zH.mjs.map → pipeable-COGyGMUV.mjs.map} +1 -1
- package/dist/predicate/index.d.mts +1 -1
- package/dist/predicate/index.mjs +1 -1
- package/dist/{predicate-D_1SsIi4.mjs → predicate-8hY-0Ocv.mjs} +2 -2
- package/dist/{predicate-D_1SsIi4.mjs.map → predicate-8hY-0Ocv.mjs.map} +1 -1
- package/dist/provide/index.d.mts +1 -1
- package/dist/provide/index.mjs +1 -1
- package/dist/provide-K-6oXtLm.mjs +2 -0
- package/dist/provide-K-6oXtLm.mjs.map +1 -0
- package/dist/queue/index.d.mts +1 -1
- package/dist/queue/index.mjs +1 -1
- package/dist/{queue-apiEOlRD.mjs → queue-CeEIUHcY.mjs} +2 -2
- package/dist/{queue-apiEOlRD.mjs.map → queue-CeEIUHcY.mjs.map} +1 -1
- package/dist/result/index.d.mts +1 -1
- package/dist/result/index.mjs +1 -1
- package/dist/{result-D3VY0qBG.mjs → result-C74pRN2x.mjs} +2 -2
- package/dist/{result-D3VY0qBG.mjs.map → result-C74pRN2x.mjs.map} +1 -1
- package/dist/{result.types-BKzChyWY.d.mts → result.types-CnhiVFEV.d.mts} +3 -3
- package/dist/{result.types-BKzChyWY.d.mts.map → result.types-CnhiVFEV.d.mts.map} +1 -1
- package/dist/schedule/index.d.mts +1 -1
- package/dist/schedule/index.mjs +1 -1
- package/dist/{schedule-C6iN3oMt.mjs → schedule-ChcIgvd5.mjs} +2 -2
- package/dist/{schedule-C6iN3oMt.mjs.map → schedule-ChcIgvd5.mjs.map} +1 -1
- package/dist/{schedule-D2651VJY.d.mts → schedule-DiidMLcl.d.mts} +3 -3
- package/dist/{schedule-D2651VJY.d.mts.map → schedule-DiidMLcl.d.mts.map} +1 -1
- package/dist/schema/index.d.mts +1 -1
- package/dist/schema/index.mjs +1 -1
- package/dist/schema-CT_wO7tN.mjs +2 -0
- package/dist/schema-CT_wO7tN.mjs.map +1 -0
- package/dist/scope/index.d.mts +1 -1
- package/dist/scope/index.mjs +1 -1
- package/dist/{scope-CuM3CzwG.d.mts → scope-7bLTmdRX.d.mts} +4 -4
- package/dist/scope-7bLTmdRX.d.mts.map +1 -0
- package/dist/scope-D2AqJy7j.mjs +2 -0
- package/dist/scope-D2AqJy7j.mjs.map +1 -0
- package/dist/service/index.d.mts +1 -1
- package/dist/service/index.mjs +1 -1
- package/dist/{service-D8mr0wwg.d.mts → service-C4xUfS_M.d.mts} +2 -2
- package/dist/{service-D8mr0wwg.d.mts.map → service-C4xUfS_M.d.mts.map} +1 -1
- package/dist/{service-CWAIEH46.mjs → service-DHkeorS3.mjs} +2 -2
- package/dist/{service-CWAIEH46.mjs.map → service-DHkeorS3.mjs.map} +1 -1
- package/dist/trace/index.d.mts +2 -0
- package/dist/trace/index.mjs +1 -0
- package/dist/trace-ByjppUes.mjs +2 -0
- package/dist/trace-ByjppUes.mjs.map +1 -0
- package/dist/trace-D_7sjH22.d.mts +375 -0
- package/dist/trace-D_7sjH22.d.mts.map +1 -0
- package/package.json +13 -5
- package/dist/adt/index.d.mts +0 -2
- package/dist/adt/index.mjs +0 -1
- package/dist/adt-CPG_sa8q.mjs +0 -2
- package/dist/adt-CPG_sa8q.mjs.map +0 -1
- package/dist/data-BHYPdqWZ.mjs +0 -2
- package/dist/data-BHYPdqWZ.mjs.map +0 -1
- package/dist/discriminator.types-C-ygT2S1.d.mts +0 -7
- package/dist/discriminator.types-C-ygT2S1.d.mts.map +0 -1
- package/dist/equality-BX6BUidG.mjs +0 -2
- package/dist/equality-BX6BUidG.mjs.map +0 -1
- package/dist/functions-ByAk682_.mjs +0 -2
- package/dist/fx-DUXDxwsU.mjs +0 -2
- package/dist/fx-DUXDxwsU.mjs.map +0 -1
- package/dist/fx.runtime-jQxh77s3.mjs +0 -2
- package/dist/fx.runtime-jQxh77s3.mjs.map +0 -1
- package/dist/index-B2Z7-XGR.d.mts.map +0 -1
- package/dist/index-B41_sFR6.d.mts +0 -64
- package/dist/index-B41_sFR6.d.mts.map +0 -1
- package/dist/index-C4DOLLaU.d.mts.map +0 -1
- package/dist/index-C6W3_n_Q.d.mts +0 -458
- package/dist/index-C6W3_n_Q.d.mts.map +0 -1
- package/dist/index-D8rDE60Y.d.mts.map +0 -1
- package/dist/index-DR7hzXU4.d.mts.map +0 -1
- package/dist/index-crtzMG48.d.mts.map +0 -1
- package/dist/layer-CKtH7TRL.mjs +0 -2
- package/dist/layer-CKtH7TRL.mjs.map +0 -1
- package/dist/multithread-Cyc8Bz45.mjs +0 -19
- package/dist/multithread-Cyc8Bz45.mjs.map +0 -1
- package/dist/pipeable-Dp1_23zH.mjs +0 -2
- package/dist/provide--yZE8x-n.mjs +0 -2
- package/dist/provide--yZE8x-n.mjs.map +0 -1
- package/dist/schema-DstB1_VK.mjs +0 -2
- package/dist/schema-DstB1_VK.mjs.map +0 -1
- package/dist/schema.shared-Bjyroa6b.mjs +0 -2
- package/dist/schema.shared-Bjyroa6b.mjs.map +0 -1
- package/dist/schema.types-E1pjcc0Y.d.mts +0 -62
- package/dist/schema.types-E1pjcc0Y.d.mts.map +0 -1
- package/dist/scope-CuM3CzwG.d.mts.map +0 -1
- package/dist/scope-gVt4PESc.mjs +0 -2
- package/dist/scope-gVt4PESc.mjs.map +0 -1
- package/dist/service-resolution-BefYr4nR.mjs +0 -2
- package/dist/service-resolution-BefYr4nR.mjs.map +0 -1
- /package/dist/{chunk-oQKkju2G.mjs → chunk-6rpU2rUb.mjs} +0 -0
- /package/dist/{option-CXXiA1w-.mjs → option-BqAUkJ8e.mjs} +0 -0
- /package/dist/{result-xFLfwriM.mjs → result-B5WbPg8C.mjs} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-ByjppUes.mjs","names":["attributes","span","Context.empty"],"sources":["../src/trace/trace.ts"],"sourcesContent":["/**\n * Runtime-local tracing helpers for `Fx` programs.\n *\n * Trace state is execution state, not a service requirement. Use `Trace.span`\n * to create spans, `Trace.annotate` / `Trace.attribute` to add span attributes,\n * and `Trace.layer` to install a tracer backend.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * yield* Trace.attribute(\"order.id\", \"ord_1\")\n * yield* Trace.event(\"charged\")\n * return \"ok\"\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"ok\" }\n * ```\n *\n * @module\n */\nimport * as Context from \"../context/context\"\nimport type { Exit } from \"../fx/exit\"\nimport {\n getRuntimeState,\n setRuntimeTracer,\n updateRuntimeState,\n withRuntimeState,\n withRuntimeStateAndExit,\n} from \"../fx/fx.runtime\"\nimport type { RuntimeState } from \"../fx/fx.runtime\"\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { AsyncFx, FxYield, RunnableFx, SyncFx } from \"../fx/fx.types\"\nimport type { Layer } from \"../layer/layer.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Trace bridges internal runtime state slots to public typed tracing APIs. */\n\n/**\n * Span kind used when creating spans.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const kind: Trace.SpanKind = \"server\"\n * ```\n */\nexport type SpanKind = \"internal\" | \"client\" | \"server\" | \"producer\" | \"consumer\"\n\n/**\n * Serializable trace identity.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const context: Trace.SpanContext = {\n * traceId: \"trace-1\",\n * spanId: \"span-1\",\n * }\n * ```\n */\nexport type SpanContext = {\n readonly traceId: string\n readonly spanId: string\n readonly traceFlags?: number\n readonly traceState?: string\n}\n\n/**\n * Link to another span context.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const link: Trace.Link = {\n * context: { traceId: \"trace-1\", spanId: \"span-1\" },\n * attributes: { relation: \"caused-by\" },\n * }\n * ```\n */\nexport type Link = {\n readonly context: SpanContext\n readonly attributes?: Record<string, unknown>\n}\n\n/**\n * Active tracing span interface.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const tracer: Trace.Tracer = Trace.native()\n * ```\n */\nexport type Span = {\n readonly name: string\n readonly context: SpanContext\n readonly kind: SpanKind\n attribute(key: string, value: unknown): void\n event(name: string, attributes?: Record<string, unknown>): void\n end(exit: Exit<unknown, unknown>): void\n}\n\n/**\n * Backend interface used by `Trace.layer`.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const spans: Trace.Span[] = []\n * const tracer: Trace.Tracer = {\n * startSpan: (options) => {\n * const span: Trace.Span = {\n * name: options.name,\n * kind: options.kind,\n * context: { traceId: \"trace-1\", spanId: \"span-1\" },\n * attribute: () => undefined,\n * event: () => undefined,\n * end: () => undefined,\n * }\n * spans.push(span)\n * return span\n * },\n * }\n * ```\n */\nexport type Tracer = {\n readonly startSpan: (options: {\n readonly name: string\n readonly parent?: Span | SpanContext\n readonly root?: boolean\n readonly kind: SpanKind\n readonly attributes: Record<string, unknown>\n readonly links: ReadonlyArray<Link>\n }) => Span\n}\n\n/**\n * Typed error returned by `Trace.current` when no local span exists.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const error: Trace.NoCurrentSpanError = { _tag: \"NoCurrentSpanError\" }\n * ```\n */\nexport type NoCurrentSpanError = {\n readonly _tag: \"NoCurrentSpanError\"\n}\n\n/**\n * Options used when creating a span.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const options: Trace.SpanOptions = {\n * kind: \"server\",\n * attributes: { route: \"/orders\" },\n * }\n * ```\n */\nexport type SpanOptions = {\n readonly parent?: Span | SpanContext\n readonly root?: boolean\n readonly kind?: SpanKind\n readonly attributes?: Record<string, unknown>\n readonly links?: ReadonlyArray<Link>\n}\n\n/**\n * Span options accepted by `Fx.gen` and `Fx.fn`.\n *\n * Attribute and link callbacks receive the generator parameters.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const options: Trace.FxSpanOptions<[string]> = {\n * name: \"load-user\",\n * attributes: (userId) => ({ userId }),\n * }\n * ```\n */\nexport type FxSpanOptions<Params extends ReadonlyArray<unknown> = readonly []> = SpanOptions & {\n readonly name: string\n readonly attributes?: Record<string, unknown> | ((...params: Params) => Record<string, unknown>)\n readonly links?: ReadonlyArray<Link> | ((...params: Params) => ReadonlyArray<Link>)\n}\n\n/**\n * Options accepted by `Fx.gen` and `Fx.fn`.\n *\n * @example\n * ```ts\n * import type { Trace } from \"@nicolastoulemont/std\"\n *\n * const options: Trace.FxGenOptions = {\n * span: \"checkout\",\n * }\n * ```\n */\nexport type FxGenOptions<Params extends ReadonlyArray<unknown> = readonly []> = {\n readonly span?: string | FxSpanOptions<Params>\n}\n\nlet nextSpanId = 0\n\nconst randomHex = (bytes: number): string => {\n const values = crypto.getRandomValues(new Uint8Array(bytes))\n return [...values].map((value) => value.toString(16).padStart(2, \"0\")).join(\"\")\n}\n\nconst newSpanContext = (parent: Span | SpanContext | undefined): SpanContext => ({\n traceId: parent === undefined ? randomHex(16) : (\"context\" in parent ? parent.context : parent).traceId,\n spanId: `${++nextSpanId}`.padStart(16, \"0\"),\n})\n\n/**\n * Create the built-in lightweight tracer backend.\n *\n * The native tracer creates in-memory span objects and is useful for local\n * runtime correlation and tests. Install production exporters by implementing\n * `Tracer` and providing it with `Trace.layer`.\n *\n * @example\n * ```ts\n * import { Trace } from \"@nicolastoulemont/std\"\n *\n * const tracer = Trace.native()\n * const span = tracer.startSpan({\n * name: \"checkout\",\n * kind: \"internal\",\n * attributes: {},\n * links: [],\n * })\n * // => span.name === \"checkout\"\n * ```\n */\nexport const native = (): Tracer => ({\n startSpan: ({ name, kind, parent }) => {\n const attributes: Record<string, unknown> = {}\n const events: Array<{ readonly name: string; readonly attributes?: Record<string, unknown> }> = []\n let ended = false\n\n return {\n name,\n context: newSpanContext(parent),\n kind,\n attribute(key, value) {\n if (!ended) {\n attributes[key] = value\n }\n },\n event(name, attributes) {\n if (!ended) {\n events.push(attributes === undefined ? { name } : { name, attributes })\n }\n },\n end() {\n ended = true\n },\n }\n },\n})\n\nconst noCurrentSpanError: NoCurrentSpanError = { _tag: \"NoCurrentSpanError\" }\n\nconst isTracer = (value: unknown): value is Tracer =>\n typeof value === \"object\" && value !== null && \"startSpan\" in value && typeof value.startSpan === \"function\"\n\nconst isSpan = (value: unknown): value is Span =>\n typeof value === \"object\" && value !== null && \"context\" in value && \"attribute\" in value && \"event\" in value\n\nconst currentTracer = (stateTracer: unknown): Tracer => (isTracer(stateTracer) ? stateTracer : native())\n\nconst spanContextOf = (span: Span | SpanContext): SpanContext => (\"context\" in span ? span.context : span)\n\nconst makeSpan = (state: RuntimeState, name: string, options?: SpanOptions): Span => {\n const tracer = currentTracer(state.tracer)\n const parent =\n options?.root === true\n ? undefined\n : (options?.parent ??\n (isSpan(state.currentSpan) ? state.currentSpan : (state.currentSpan as SpanContext | undefined)))\n const startOptions: Parameters<Tracer[\"startSpan\"]>[0] = {\n name,\n kind: options?.kind ?? \"internal\",\n attributes: {\n ...state.spanAttributes,\n ...options?.attributes,\n },\n links: [...(state.spanLinks as ReadonlyArray<Link>), ...(options?.links ?? [])],\n ...(parent === undefined ? {} : { parent }),\n ...(options?.root === undefined ? {} : { root: options.root }),\n }\n const span = tracer.startSpan(startOptions)\n\n for (const [key, value] of Object.entries(options?.attributes ?? {})) {\n span.attribute(key, value)\n }\n\n return span\n}\n\n/**\n * Run an effect inside a tracing span.\n *\n * The span becomes the current local span while the effect runs. The span is\n * ended with the effect's final `Exit`.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"load-user\",\n * Fx.gen(function* () {\n * yield* Trace.attribute(\"user.id\", \"user_1\")\n * return \"user_1\"\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"user_1\" }\n * ```\n */\nexport function span<A, E, R>(name: string, fx: SyncFx<A, E, R>, options?: SpanOptions): SyncFx<A, E>\nexport function span<A, E, R>(name: string, fx: AsyncFx<A, E, R>, options?: SpanOptions): AsyncFx<A, E>\nexport function span<A, E, R>(name: string, fx: RunnableFx<A, E, R>, options?: SpanOptions): RunnableFx<A, E>\nexport function span<A, E, R>(name: string, fx: RunnableFx<A, E, R>, options?: SpanOptions): RunnableFx<A, E> {\n return withRuntimeStateAndExit(\n fx,\n (state) => {\n const opened = makeSpan(state, name, options)\n return {\n ...state,\n currentSpan: opened,\n currentLocalSpan: opened,\n spanAttributes: {},\n spanLinks: [],\n }\n },\n (exit, state) => {\n if (isSpan(state.currentLocalSpan)) {\n state.currentLocalSpan.end(exit)\n }\n },\n )\n}\n\n/**\n * Add attributes to the current local span and to the pending attributes for\n * the next nested span.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * yield* Trace.annotate({ orderId: \"ord_1\" })\n * return \"ok\"\n * }),\n * )\n * ```\n */\nexport const annotate = (attributes: Record<string, unknown>): SyncFx<void> =>\n updateRuntimeState((state) => {\n if (isSpan(state.currentLocalSpan)) {\n for (const [key, value] of Object.entries(attributes)) {\n state.currentLocalSpan.attribute(key, value)\n }\n }\n\n return {\n ...state,\n spanAttributes: {\n ...state.spanAttributes,\n ...attributes,\n },\n }\n })\n\n/**\n * Add one attribute to the current local span and to the next nested span.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * yield* Trace.attribute(\"order.id\", \"ord_1\")\n * return \"ok\"\n * }),\n * )\n * ```\n */\nexport const attribute = (key: string, value: unknown): SyncFx<void> => annotate({ [key]: value })\n\n/**\n * Add an event to the current local span.\n *\n * If no local span exists, this is a no-op.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * yield* Trace.event(\"charged\", { amountCents: 4600 })\n * return \"ok\"\n * }),\n * )\n * ```\n */\nexport const event = (name: string, attributes?: Record<string, unknown>): SyncFx<void> =>\n updateRuntimeState((state) => {\n if (isSpan(state.currentLocalSpan)) {\n state.currentLocalSpan.event(name, attributes)\n }\n return state\n })\n\n/**\n * Read the current local span.\n *\n * Returns `NoCurrentSpanError` when no local span exists.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * const span = yield* Trace.current()\n * return span.name\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"checkout\" }\n * ```\n */\nexport const current = (): SyncFx<Span, NoCurrentSpanError> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as Span,\n _E: () => noCurrentSpanError,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<NoCurrentSpanError, never>, Span, unknown> {\n const state = yield* getRuntimeState()\n if (isSpan(state.currentLocalSpan)) {\n return state.currentLocalSpan\n }\n yield noCurrentSpanError\n throw new Error(\"Unreachable\")\n },\n})\n\n/**\n * Read the current propagated span context, if any.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Trace.span(\n * \"checkout\",\n * Fx.gen(function* () {\n * return yield* Trace.currentContext()\n * }),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: { traceId: \"...\", spanId: \"...\" } }\n * ```\n */\nexport const currentContext = (): SyncFx<SpanContext | undefined> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as SpanContext | undefined,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<never, never>, SpanContext | undefined, unknown> {\n const state = yield* getRuntimeState()\n if (isSpan(state.currentSpan)) {\n return state.currentSpan.context\n }\n return state.currentSpan === undefined ? undefined : spanContextOf(state.currentSpan as SpanContext)\n },\n})\n\n/**\n * Run an effect with an explicit parent span or span context.\n *\n * @example\n * ```ts\n * import { Fx, Trace } from \"@nicolastoulemont/std\"\n *\n * const parent = { traceId: \"trace-1\", spanId: \"parent-1\" }\n * const program = Trace.withParent(parent)(\n * Trace.span(\"child\", Fx.gen(function* () {\n * return yield* Trace.currentContext()\n * })),\n * )\n * ```\n */\nexport const withParent =\n (parent: Span | SpanContext) =>\n <A, E, R>(fx: RunnableFx<A, E, R>): RunnableFx<A, E, R> =>\n withRuntimeState(fx, (state) => ({\n ...state,\n currentSpan: parent,\n })) as RunnableFx<A, E, R>\n\n/**\n * Install a tracer backend in the current Fx runtime.\n *\n * @example\n * ```ts\n * import { Fx, Provide, Trace } from \"@nicolastoulemont/std\"\n *\n * const program = Provide.layer(Trace.layer(Trace.native()))(\n * Trace.span(\"checkout\", Fx.gen(function* () {\n * return \"ok\"\n * })),\n * )\n *\n * const exit = Fx.run(program)\n * // => { _tag: \"Ok\", value: \"ok\" }\n * ```\n */\nexport const layer = (tracer: Tracer): Layer<never, never, never, true> => ({\n _tag: \"Layer\",\n _ROut: undefined as never,\n _E: undefined as never,\n _RIn: undefined as never,\n _Sync: undefined as unknown as true,\n build: (): SyncFx<Context.Context> => ({\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as unknown as Context.Context,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n *[Symbol.iterator](): Generator<FxYield<never, never>, Context.Context, unknown> {\n yield* updateRuntimeState(setRuntimeTracer(tracer))\n return Context.empty()\n },\n }),\n})\n\n/**\n * Resolve span metadata passed to `Fx.gen` / `Fx.fn`.\n *\n * This is exported for internal module integration and advanced adapters that\n * need the same parameter-aware span option behavior.\n *\n * @example\n * ```ts\n * import { Trace } from \"@nicolastoulemont/std\"\n *\n * const resolved = Trace.resolveFxSpanOptions(\n * { name: \"load-user\", attributes: (id: string) => ({ id }) },\n * [\"user_1\"],\n * )\n * // => { name: \"load-user\", options: { attributes: { id: \"user_1\" } } }\n * ```\n */\nexport const resolveFxSpanOptions = <Params extends ReadonlyArray<unknown>>(\n span: string | FxSpanOptions<Params>,\n params: Params,\n): { readonly name: string; readonly options: SpanOptions } => {\n if (typeof span === \"string\") {\n return { name: span, options: {} }\n }\n\n const { name, attributes, links, ...options } = span\n const resolvedAttributes = typeof attributes === \"function\" ? attributes(...params) : attributes\n const resolvedLinks = typeof links === \"function\" ? links(...params) : links\n return {\n name,\n options: {\n ...options,\n ...(resolvedAttributes === undefined ? {} : { attributes: resolvedAttributes }),\n ...(resolvedLinks === undefined ? {} : { links: resolvedLinks }),\n },\n }\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"yWA0NA,IAAI,EAAa,EAEjB,MAAM,EAAa,GAEV,CAAC,GADO,OAAO,gBAAgB,IAAI,WAAW,EAAM,CAAC,CAC1C,CAAC,IAAK,GAAU,EAAM,SAAS,GAAG,CAAC,SAAS,EAAG,IAAI,CAAC,CAAC,KAAK,GAAG,CAG3E,EAAkB,IAAyD,CAC/E,QAAS,IAAW,IAAA,GAAY,EAAU,GAAG,EAAI,YAAa,EAAS,EAAO,QAAU,GAAQ,QAChG,OAAQ,GAAG,EAAE,IAAa,SAAS,GAAI,IAAI,CAC5C,EAuBY,OAAwB,CACnC,WAAY,CAAE,OAAM,OAAM,YAAa,CACrC,IAAM,EAAsC,EAAE,CACxC,EAA0F,EAAE,CAC9F,EAAQ,GAEZ,MAAO,CACL,OACA,QAAS,EAAe,EAAO,CAC/B,OACA,UAAU,EAAK,EAAO,CACf,IACH,EAAW,GAAO,IAGtB,MAAM,EAAM,EAAY,CACjB,GACH,EAAO,KAAKA,IAAe,IAAA,GAAY,CAAE,KAAA,EAAM,CAAG,CAAE,KAAA,EAAM,WAAA,EAAY,CAAC,EAG3E,KAAM,CACJ,EAAQ,IAEX,EAEJ,EAEK,EA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AC7D,GAAI,OAAOD,GAAS,SAClB,MAAO,CAAE,KAAMA,EAAM,QAAS,EAAE,CAAE,CAGpC,GAAM,CAAE,OAAM,aAAY,QAAO,GAAG,GAAYA,EAC1C,EAAqB,OAAO,GAAe,WAAa,EAAW,GAAG,EAAO,CAAG,EAChF,EAAgB,OAAO,GAAU,WAAa,EAAM,GAAG,EAAO,CAAG,EACvE,MAAO,CACL,OACA,QAAS,CACP,GAAG,EACH,GAAI,IAAuB,IAAA,GAAY,EAAE,CAAG,CAAE,WAAY,EAAoB,CAC9E,GAAI,IAAkB,IAAA,GAAY,EAAE,CAAG,CAAE,MAAO,EAAe,CAChE,CACF"}
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
import { f as RunnableFx, m as SyncFx, t as AsyncFx } from "./fx.types-CpFKa-Jj.mjs";
|
|
2
|
+
import { t as Exit } from "./exit-DOdhmr81.mjs";
|
|
3
|
+
import { n as Layer } from "./layer.types-DsCTjICW.mjs";
|
|
4
|
+
|
|
5
|
+
//#region src/trace/trace.d.ts
|
|
6
|
+
declare namespace trace_d_exports {
|
|
7
|
+
export { FxGenOptions, FxSpanOptions, Link, NoCurrentSpanError, Span, SpanContext, SpanKind, SpanOptions, Tracer, annotate, attribute, current, currentContext, event, layer, native, resolveFxSpanOptions, span, withParent };
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Span kind used when creating spans.
|
|
11
|
+
*
|
|
12
|
+
* @example
|
|
13
|
+
* ```ts
|
|
14
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
15
|
+
*
|
|
16
|
+
* const kind: Trace.SpanKind = "server"
|
|
17
|
+
* ```
|
|
18
|
+
*/
|
|
19
|
+
type SpanKind = "internal" | "client" | "server" | "producer" | "consumer";
|
|
20
|
+
/**
|
|
21
|
+
* Serializable trace identity.
|
|
22
|
+
*
|
|
23
|
+
* @example
|
|
24
|
+
* ```ts
|
|
25
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
26
|
+
*
|
|
27
|
+
* const context: Trace.SpanContext = {
|
|
28
|
+
* traceId: "trace-1",
|
|
29
|
+
* spanId: "span-1",
|
|
30
|
+
* }
|
|
31
|
+
* ```
|
|
32
|
+
*/
|
|
33
|
+
type SpanContext = {
|
|
34
|
+
readonly traceId: string;
|
|
35
|
+
readonly spanId: string;
|
|
36
|
+
readonly traceFlags?: number;
|
|
37
|
+
readonly traceState?: string;
|
|
38
|
+
};
|
|
39
|
+
/**
|
|
40
|
+
* Link to another span context.
|
|
41
|
+
*
|
|
42
|
+
* @example
|
|
43
|
+
* ```ts
|
|
44
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
45
|
+
*
|
|
46
|
+
* const link: Trace.Link = {
|
|
47
|
+
* context: { traceId: "trace-1", spanId: "span-1" },
|
|
48
|
+
* attributes: { relation: "caused-by" },
|
|
49
|
+
* }
|
|
50
|
+
* ```
|
|
51
|
+
*/
|
|
52
|
+
type Link = {
|
|
53
|
+
readonly context: SpanContext;
|
|
54
|
+
readonly attributes?: Record<string, unknown>;
|
|
55
|
+
};
|
|
56
|
+
/**
|
|
57
|
+
* Active tracing span interface.
|
|
58
|
+
*
|
|
59
|
+
* @example
|
|
60
|
+
* ```ts
|
|
61
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
62
|
+
*
|
|
63
|
+
* const tracer: Trace.Tracer = Trace.native()
|
|
64
|
+
* ```
|
|
65
|
+
*/
|
|
66
|
+
type Span = {
|
|
67
|
+
readonly name: string;
|
|
68
|
+
readonly context: SpanContext;
|
|
69
|
+
readonly kind: SpanKind;
|
|
70
|
+
attribute(key: string, value: unknown): void;
|
|
71
|
+
event(name: string, attributes?: Record<string, unknown>): void;
|
|
72
|
+
end(exit: Exit<unknown, unknown>): void;
|
|
73
|
+
};
|
|
74
|
+
/**
|
|
75
|
+
* Backend interface used by `Trace.layer`.
|
|
76
|
+
*
|
|
77
|
+
* @example
|
|
78
|
+
* ```ts
|
|
79
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
80
|
+
*
|
|
81
|
+
* const spans: Trace.Span[] = []
|
|
82
|
+
* const tracer: Trace.Tracer = {
|
|
83
|
+
* startSpan: (options) => {
|
|
84
|
+
* const span: Trace.Span = {
|
|
85
|
+
* name: options.name,
|
|
86
|
+
* kind: options.kind,
|
|
87
|
+
* context: { traceId: "trace-1", spanId: "span-1" },
|
|
88
|
+
* attribute: () => undefined,
|
|
89
|
+
* event: () => undefined,
|
|
90
|
+
* end: () => undefined,
|
|
91
|
+
* }
|
|
92
|
+
* spans.push(span)
|
|
93
|
+
* return span
|
|
94
|
+
* },
|
|
95
|
+
* }
|
|
96
|
+
* ```
|
|
97
|
+
*/
|
|
98
|
+
type Tracer = {
|
|
99
|
+
readonly startSpan: (options: {
|
|
100
|
+
readonly name: string;
|
|
101
|
+
readonly parent?: Span | SpanContext;
|
|
102
|
+
readonly root?: boolean;
|
|
103
|
+
readonly kind: SpanKind;
|
|
104
|
+
readonly attributes: Record<string, unknown>;
|
|
105
|
+
readonly links: ReadonlyArray<Link>;
|
|
106
|
+
}) => Span;
|
|
107
|
+
};
|
|
108
|
+
/**
|
|
109
|
+
* Typed error returned by `Trace.current` when no local span exists.
|
|
110
|
+
*
|
|
111
|
+
* @example
|
|
112
|
+
* ```ts
|
|
113
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
114
|
+
*
|
|
115
|
+
* const error: Trace.NoCurrentSpanError = { _tag: "NoCurrentSpanError" }
|
|
116
|
+
* ```
|
|
117
|
+
*/
|
|
118
|
+
type NoCurrentSpanError = {
|
|
119
|
+
readonly _tag: "NoCurrentSpanError";
|
|
120
|
+
};
|
|
121
|
+
/**
|
|
122
|
+
* Options used when creating a span.
|
|
123
|
+
*
|
|
124
|
+
* @example
|
|
125
|
+
* ```ts
|
|
126
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
127
|
+
*
|
|
128
|
+
* const options: Trace.SpanOptions = {
|
|
129
|
+
* kind: "server",
|
|
130
|
+
* attributes: { route: "/orders" },
|
|
131
|
+
* }
|
|
132
|
+
* ```
|
|
133
|
+
*/
|
|
134
|
+
type SpanOptions = {
|
|
135
|
+
readonly parent?: Span | SpanContext;
|
|
136
|
+
readonly root?: boolean;
|
|
137
|
+
readonly kind?: SpanKind;
|
|
138
|
+
readonly attributes?: Record<string, unknown>;
|
|
139
|
+
readonly links?: ReadonlyArray<Link>;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* Span options accepted by `Fx.gen` and `Fx.fn`.
|
|
143
|
+
*
|
|
144
|
+
* Attribute and link callbacks receive the generator parameters.
|
|
145
|
+
*
|
|
146
|
+
* @example
|
|
147
|
+
* ```ts
|
|
148
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
149
|
+
*
|
|
150
|
+
* const options: Trace.FxSpanOptions<[string]> = {
|
|
151
|
+
* name: "load-user",
|
|
152
|
+
* attributes: (userId) => ({ userId }),
|
|
153
|
+
* }
|
|
154
|
+
* ```
|
|
155
|
+
*/
|
|
156
|
+
type FxSpanOptions<Params extends ReadonlyArray<unknown> = readonly []> = SpanOptions & {
|
|
157
|
+
readonly name: string;
|
|
158
|
+
readonly attributes?: Record<string, unknown> | ((...params: Params) => Record<string, unknown>);
|
|
159
|
+
readonly links?: ReadonlyArray<Link> | ((...params: Params) => ReadonlyArray<Link>);
|
|
160
|
+
};
|
|
161
|
+
/**
|
|
162
|
+
* Options accepted by `Fx.gen` and `Fx.fn`.
|
|
163
|
+
*
|
|
164
|
+
* @example
|
|
165
|
+
* ```ts
|
|
166
|
+
* import type { Trace } from "@nicolastoulemont/std"
|
|
167
|
+
*
|
|
168
|
+
* const options: Trace.FxGenOptions = {
|
|
169
|
+
* span: "checkout",
|
|
170
|
+
* }
|
|
171
|
+
* ```
|
|
172
|
+
*/
|
|
173
|
+
type FxGenOptions<Params extends ReadonlyArray<unknown> = readonly []> = {
|
|
174
|
+
readonly span?: string | FxSpanOptions<Params>;
|
|
175
|
+
};
|
|
176
|
+
/**
|
|
177
|
+
* Create the built-in lightweight tracer backend.
|
|
178
|
+
*
|
|
179
|
+
* The native tracer creates in-memory span objects and is useful for local
|
|
180
|
+
* runtime correlation and tests. Install production exporters by implementing
|
|
181
|
+
* `Tracer` and providing it with `Trace.layer`.
|
|
182
|
+
*
|
|
183
|
+
* @example
|
|
184
|
+
* ```ts
|
|
185
|
+
* import { Trace } from "@nicolastoulemont/std"
|
|
186
|
+
*
|
|
187
|
+
* const tracer = Trace.native()
|
|
188
|
+
* const span = tracer.startSpan({
|
|
189
|
+
* name: "checkout",
|
|
190
|
+
* kind: "internal",
|
|
191
|
+
* attributes: {},
|
|
192
|
+
* links: [],
|
|
193
|
+
* })
|
|
194
|
+
* // => span.name === "checkout"
|
|
195
|
+
* ```
|
|
196
|
+
*/
|
|
197
|
+
declare const native: () => Tracer;
|
|
198
|
+
/**
|
|
199
|
+
* Run an effect inside a tracing span.
|
|
200
|
+
*
|
|
201
|
+
* The span becomes the current local span while the effect runs. The span is
|
|
202
|
+
* ended with the effect's final `Exit`.
|
|
203
|
+
*
|
|
204
|
+
* @example
|
|
205
|
+
* ```ts
|
|
206
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
207
|
+
*
|
|
208
|
+
* const program = Trace.span(
|
|
209
|
+
* "load-user",
|
|
210
|
+
* Fx.gen(function* () {
|
|
211
|
+
* yield* Trace.attribute("user.id", "user_1")
|
|
212
|
+
* return "user_1"
|
|
213
|
+
* }),
|
|
214
|
+
* )
|
|
215
|
+
*
|
|
216
|
+
* const exit = Fx.run(program)
|
|
217
|
+
* // => { _tag: "Ok", value: "user_1" }
|
|
218
|
+
* ```
|
|
219
|
+
*/
|
|
220
|
+
declare function span<A, E, R>(name: string, fx: SyncFx<A, E, R>, options?: SpanOptions): SyncFx<A, E>;
|
|
221
|
+
declare function span<A, E, R>(name: string, fx: AsyncFx<A, E, R>, options?: SpanOptions): AsyncFx<A, E>;
|
|
222
|
+
declare function span<A, E, R>(name: string, fx: RunnableFx<A, E, R>, options?: SpanOptions): RunnableFx<A, E>;
|
|
223
|
+
/**
|
|
224
|
+
* Add attributes to the current local span and to the pending attributes for
|
|
225
|
+
* the next nested span.
|
|
226
|
+
*
|
|
227
|
+
* @example
|
|
228
|
+
* ```ts
|
|
229
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
230
|
+
*
|
|
231
|
+
* const program = Trace.span(
|
|
232
|
+
* "checkout",
|
|
233
|
+
* Fx.gen(function* () {
|
|
234
|
+
* yield* Trace.annotate({ orderId: "ord_1" })
|
|
235
|
+
* return "ok"
|
|
236
|
+
* }),
|
|
237
|
+
* )
|
|
238
|
+
* ```
|
|
239
|
+
*/
|
|
240
|
+
declare const annotate: (attributes: Record<string, unknown>) => SyncFx<void>;
|
|
241
|
+
/**
|
|
242
|
+
* Add one attribute to the current local span and to the next nested span.
|
|
243
|
+
*
|
|
244
|
+
* @example
|
|
245
|
+
* ```ts
|
|
246
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
247
|
+
*
|
|
248
|
+
* const program = Trace.span(
|
|
249
|
+
* "checkout",
|
|
250
|
+
* Fx.gen(function* () {
|
|
251
|
+
* yield* Trace.attribute("order.id", "ord_1")
|
|
252
|
+
* return "ok"
|
|
253
|
+
* }),
|
|
254
|
+
* )
|
|
255
|
+
* ```
|
|
256
|
+
*/
|
|
257
|
+
declare const attribute: (key: string, value: unknown) => SyncFx<void>;
|
|
258
|
+
/**
|
|
259
|
+
* Add an event to the current local span.
|
|
260
|
+
*
|
|
261
|
+
* If no local span exists, this is a no-op.
|
|
262
|
+
*
|
|
263
|
+
* @example
|
|
264
|
+
* ```ts
|
|
265
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
266
|
+
*
|
|
267
|
+
* const program = Trace.span(
|
|
268
|
+
* "checkout",
|
|
269
|
+
* Fx.gen(function* () {
|
|
270
|
+
* yield* Trace.event("charged", { amountCents: 4600 })
|
|
271
|
+
* return "ok"
|
|
272
|
+
* }),
|
|
273
|
+
* )
|
|
274
|
+
* ```
|
|
275
|
+
*/
|
|
276
|
+
declare const event: (name: string, attributes?: Record<string, unknown>) => SyncFx<void>;
|
|
277
|
+
/**
|
|
278
|
+
* Read the current local span.
|
|
279
|
+
*
|
|
280
|
+
* Returns `NoCurrentSpanError` when no local span exists.
|
|
281
|
+
*
|
|
282
|
+
* @example
|
|
283
|
+
* ```ts
|
|
284
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
285
|
+
*
|
|
286
|
+
* const program = Trace.span(
|
|
287
|
+
* "checkout",
|
|
288
|
+
* Fx.gen(function* () {
|
|
289
|
+
* const span = yield* Trace.current()
|
|
290
|
+
* return span.name
|
|
291
|
+
* }),
|
|
292
|
+
* )
|
|
293
|
+
*
|
|
294
|
+
* const exit = Fx.run(program)
|
|
295
|
+
* // => { _tag: "Ok", value: "checkout" }
|
|
296
|
+
* ```
|
|
297
|
+
*/
|
|
298
|
+
declare const current: () => SyncFx<Span, NoCurrentSpanError>;
|
|
299
|
+
/**
|
|
300
|
+
* Read the current propagated span context, if any.
|
|
301
|
+
*
|
|
302
|
+
* @example
|
|
303
|
+
* ```ts
|
|
304
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
305
|
+
*
|
|
306
|
+
* const program = Trace.span(
|
|
307
|
+
* "checkout",
|
|
308
|
+
* Fx.gen(function* () {
|
|
309
|
+
* return yield* Trace.currentContext()
|
|
310
|
+
* }),
|
|
311
|
+
* )
|
|
312
|
+
*
|
|
313
|
+
* const exit = Fx.run(program)
|
|
314
|
+
* // => { _tag: "Ok", value: { traceId: "...", spanId: "..." } }
|
|
315
|
+
* ```
|
|
316
|
+
*/
|
|
317
|
+
declare const currentContext: () => SyncFx<SpanContext | undefined>;
|
|
318
|
+
/**
|
|
319
|
+
* Run an effect with an explicit parent span or span context.
|
|
320
|
+
*
|
|
321
|
+
* @example
|
|
322
|
+
* ```ts
|
|
323
|
+
* import { Fx, Trace } from "@nicolastoulemont/std"
|
|
324
|
+
*
|
|
325
|
+
* const parent = { traceId: "trace-1", spanId: "parent-1" }
|
|
326
|
+
* const program = Trace.withParent(parent)(
|
|
327
|
+
* Trace.span("child", Fx.gen(function* () {
|
|
328
|
+
* return yield* Trace.currentContext()
|
|
329
|
+
* })),
|
|
330
|
+
* )
|
|
331
|
+
* ```
|
|
332
|
+
*/
|
|
333
|
+
declare const withParent: (parent: Span | SpanContext) => <A, E, R>(fx: RunnableFx<A, E, R>) => RunnableFx<A, E, R>;
|
|
334
|
+
/**
|
|
335
|
+
* Install a tracer backend in the current Fx runtime.
|
|
336
|
+
*
|
|
337
|
+
* @example
|
|
338
|
+
* ```ts
|
|
339
|
+
* import { Fx, Provide, Trace } from "@nicolastoulemont/std"
|
|
340
|
+
*
|
|
341
|
+
* const program = Provide.layer(Trace.layer(Trace.native()))(
|
|
342
|
+
* Trace.span("checkout", Fx.gen(function* () {
|
|
343
|
+
* return "ok"
|
|
344
|
+
* })),
|
|
345
|
+
* )
|
|
346
|
+
*
|
|
347
|
+
* const exit = Fx.run(program)
|
|
348
|
+
* // => { _tag: "Ok", value: "ok" }
|
|
349
|
+
* ```
|
|
350
|
+
*/
|
|
351
|
+
declare const layer: (tracer: Tracer) => Layer<never, never, never, true>;
|
|
352
|
+
/**
|
|
353
|
+
* Resolve span metadata passed to `Fx.gen` / `Fx.fn`.
|
|
354
|
+
*
|
|
355
|
+
* This is exported for internal module integration and advanced adapters that
|
|
356
|
+
* need the same parameter-aware span option behavior.
|
|
357
|
+
*
|
|
358
|
+
* @example
|
|
359
|
+
* ```ts
|
|
360
|
+
* import { Trace } from "@nicolastoulemont/std"
|
|
361
|
+
*
|
|
362
|
+
* const resolved = Trace.resolveFxSpanOptions(
|
|
363
|
+
* { name: "load-user", attributes: (id: string) => ({ id }) },
|
|
364
|
+
* ["user_1"],
|
|
365
|
+
* )
|
|
366
|
+
* // => { name: "load-user", options: { attributes: { id: "user_1" } } }
|
|
367
|
+
* ```
|
|
368
|
+
*/
|
|
369
|
+
declare const resolveFxSpanOptions: <Params extends ReadonlyArray<unknown>>(span: string | FxSpanOptions<Params>, params: Params) => {
|
|
370
|
+
readonly name: string;
|
|
371
|
+
readonly options: SpanOptions;
|
|
372
|
+
};
|
|
373
|
+
//#endregion
|
|
374
|
+
export { trace_d_exports as n, FxGenOptions as t };
|
|
375
|
+
//# sourceMappingURL=trace-D_7sjH22.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"trace-D_7sjH22.d.mts","names":[],"sources":["../src/trace/trace.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;;;;KAoDY,QAAA;;;;;;;;;;;;;;AAAA,KAeA,WAAA,GAfQ;EAeR,SAAA,OAAW,EAAA,MAAA;EAoBX,SAAI,MAAA,EAAA,MACI;EAcR,SAAI,UAAA,CAAA,EAAA,MAAA;EAEI,SAAA,UAAA,CAAA,EAAA,MAAA;CACH;;;;AA8BjB;;;;;;;;;AAqBA;AAiBY,KAtFA,IAAA,GAsFW;EACH,SAAA,OAAA,EAtFA,WAsFA;EAAO,SAAA,UAAA,CAAA,EArFH,MAqFG,CAAA,MAAA,EAAA,OAAA,CAAA;CAET;;;;;AAoBlB;;;;;;AAGiC,KAjGrB,IAAA,GAiGqB;EAAd,SAAA,IAAA,EAAA,MAAA;EAAmC,SAAA,OAAA,EA/FlC,WA+FkC;EAAyB,SAAA,IAAA,EA9F9D,QA8F8D;EAAd,SAAA,CAAA,GAAA,EAAA,MAAA,EAAA,KAAA,EAAA,OAAA,CAAA,EAAA,IAAA;EAAa,KAAA,CAAA,IAAA,EAAA,MAAA,EAAA,UAAA,CAAA,EA5F3C,MA4F2C,CAAA,MAAA,EAAA,OAAA,CAAA,CAAA,EAAA,IAAA;EAelE,GAAA,CAAA,IAAA,EA1GA,IA0GA,CAAY,OAAA,EAAA,OAAA,CAAA,CAAA,EAAA,IAAA;CAAgB;;;;AAqCxC;AAwFA;;;;;;;;;;AACA;;;;;;;;;;AACgB,KA9MJ,MAAA,GA8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;;;;;;;;;;;cAmC3B,sBAAqB,OAAO;;;;;;;;;;;;;;;;cA+B5B,qBACF,OAAO,8BACF,WAAW,GAAG,GAAG,OAAK,WAAW,GAAG,GAAG;;;;;;;;;;;;;;;;;;cAuB1C,gBAAiB,WAAS;;;;;;;;;;;;;;;;;;cAqC1B,sCAAuC,uCACnC,cAAc,iBACrB;;oBACoC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nicolastoulemont/std",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.0",
|
|
4
4
|
"description": "Collection of utility functions",
|
|
5
5
|
"homepage": "https://github.com/nicolastoulemont/toolbelt/tree/main/packages/std",
|
|
6
6
|
"license": "ISC",
|
|
@@ -16,10 +16,6 @@
|
|
|
16
16
|
"types": "./dist/index.d.mts",
|
|
17
17
|
"default": "./dist/index.mjs"
|
|
18
18
|
},
|
|
19
|
-
"./adt": {
|
|
20
|
-
"types": "./dist/adt/index.d.mts",
|
|
21
|
-
"default": "./dist/adt/index.mjs"
|
|
22
|
-
},
|
|
23
19
|
"./brand": {
|
|
24
20
|
"types": "./dist/brand/index.d.mts",
|
|
25
21
|
"default": "./dist/brand/index.mjs"
|
|
@@ -40,6 +36,10 @@
|
|
|
40
36
|
"types": "./dist/either/index.d.mts",
|
|
41
37
|
"default": "./dist/either/index.mjs"
|
|
42
38
|
},
|
|
39
|
+
"./fiber": {
|
|
40
|
+
"types": "./dist/fiber/index.d.mts",
|
|
41
|
+
"default": "./dist/fiber/index.mjs"
|
|
42
|
+
},
|
|
43
43
|
"./functions": {
|
|
44
44
|
"types": "./dist/functions/index.d.mts",
|
|
45
45
|
"default": "./dist/functions/index.mjs"
|
|
@@ -52,6 +52,10 @@
|
|
|
52
52
|
"types": "./dist/layer/index.d.mts",
|
|
53
53
|
"default": "./dist/layer/index.mjs"
|
|
54
54
|
},
|
|
55
|
+
"./log": {
|
|
56
|
+
"types": "./dist/log/index.d.mts",
|
|
57
|
+
"default": "./dist/log/index.mjs"
|
|
58
|
+
},
|
|
55
59
|
"./multithread": {
|
|
56
60
|
"types": "./dist/multithread/index.d.mts",
|
|
57
61
|
"default": "./dist/multithread/index.mjs"
|
|
@@ -95,6 +99,10 @@
|
|
|
95
99
|
"./service": {
|
|
96
100
|
"types": "./dist/service/index.d.mts",
|
|
97
101
|
"default": "./dist/service/index.mjs"
|
|
102
|
+
},
|
|
103
|
+
"./trace": {
|
|
104
|
+
"types": "./dist/trace/index.d.mts",
|
|
105
|
+
"default": "./dist/trace/index.mjs"
|
|
98
106
|
}
|
|
99
107
|
},
|
|
100
108
|
"publishConfig": {
|
package/dist/adt/index.d.mts
DELETED
package/dist/adt/index.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"../adt-CPG_sa8q.mjs";export{e as Adt};
|
package/dist/adt-CPG_sa8q.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-oQKkju2G.mjs";import{i as t,n,r,t as i}from"./equality-BX6BUidG.mjs";import{i as a,t as o}from"./result-D3VY0qBG.mjs";import{r as s}from"./schema.shared-Bjyroa6b.mjs";function c(e,t){let n=t[e._tag];return n(e)}function l(e){return typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===Object.prototype}function u(e){return typeof e==`function`&&`_variant`in e&&e._variant===!0}function d(e,t,n){return s(e,t,`ADT variant "${n}"`)}function f(e){return t=>l(t)&&`_tag`in t&&t._tag===e}function p(e){let t=new Set(e);return e=>l(e)&&`_tag`in e&&typeof e._tag==`string`&&t.has(e._tag)}function m(e,t,n,r){return n!==void 0&&r!==void 0?{kind:e,message:t,cause:n,validationIssues:r}:n===void 0?r===void 0?{kind:e,message:t}:{kind:e,message:t,validationIssues:r}:{kind:e,message:t,cause:n}}function h(e){return{to:e=>JSON.stringify(e),from:e=>{try{let t=JSON.parse(e);if(typeof t==`object`&&t&&`_tag`in t){let{_tag:e,...n}=t;return n}return t}catch{return null}}}}function g(e,t,n){let r=h(e),i={json:n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(r.to(i.value))}catch(e){return o(m(`EncodingError`,`JSON encoding failed: ${e instanceof Error?e.message:String(e)}`,e))}}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i=d(t,{...n,_tag:e},e);if(i._tag===`Err`)return o(m(`ValidationError`,`Cannot encode invalid data: ${i.error.issues.map(e=>e.message).join(`, `)}`,void 0,i.error.issues));try{return a(s.to(i.value))}catch(e){return o(m(`EncodingError`,`Encoding with codec '${r}' failed: ${e instanceof Error?e.message:String(e)}`,e))}};return i}function _(e,t,n){let r=h(e),i={json:n=>{let i=r.from(n);if(i===null)return o(m(`DecodingError`,`Invalid JSON format`));let s=d(t,{...i,_tag:e},e);return s._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,s.error.issues)):a({...s.value,_tag:e})}};if(n)for(let[r,s]of Object.entries(n))i[r]=n=>{let i;try{i=s.from(n)}catch(e){return o(m(`DecodingError`,`Decoding with codec '${r}' threw an error`,e))}if(i===null)return o(m(`DecodingError`,`Codec '${r}' failed to decode input`));let c=d(t,{...i,_tag:e},e);return c._tag===`Err`?o(m(`ValidationError`,`Decoded data failed schema validation`,void 0,c.error.issues)):a({...c.value,_tag:e})};return i}function v(e,n,i){let s=f(e),c=g(e,n,i),l=_(e,n,i),u=r(e),p=t(e),m=t=>{let r=d(n,{...t,_tag:e},e);return r._tag===`Err`?o(r.error):a({...r.value,_tag:e})};return m._variant=!0,m._tag=e,m.schema=n,i&&(m.codecs=i),m.is=s,m.to=c,m.from=l,m.equals=u,m.hash=p,m}function y(e,t){let r=Object.keys(t),a={};for(let[e,n]of Object.entries(t))u(n)?n._tag===e?a[e]=n:n.codecs?a[e]=v(e,n.schema,n.codecs):a[e]=v(e,n.schema):a[e]=v(e,n);return{_name:e,is:p(r),equals:i(r),hash:n(r),...a}}var b=e({match:()=>C,union:()=>x,variant:()=>S});const x=y,S=v,C=c;export{b as t};
|
|
2
|
-
//# sourceMappingURL=adt-CPG_sa8q.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"adt-CPG_sa8q.mjs","names":["match","validateSchemaSync","variant","union","variant","unionImpl","variantImpl","matchImpl"],"sources":["../src/adt/adt.match.ts","../src/shared/is-plain-object.ts","../src/adt/adt.utils.ts","../src/adt/adt.codec.ts","../src/adt/adt.variant.ts","../src/adt/adt.union.ts","../src/adt/adt.ts"],"sourcesContent":["/**\n * Handler functions for each variant in a discriminated union.\n * Each key maps to a function that receives the variant value and returns TResult.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n */\ntype AdtMatchHandlers<T extends { readonly _tag: string }, TResult> = {\n [K in T[\"_tag\"]]: (value: Extract<T, { readonly _tag: K }>) => TResult\n}\n\n/**\n * Exhaustive pattern matching for discriminated unions.\n *\n * TypeScript will error if any variant is missing from handlers,\n * ensuring exhaustive handling of all cases.\n *\n * @template T - The discriminated union type (must have readonly _tag)\n * @template TResult - The return type of all handlers\n * @template Handlers - The handler object type (inferred)\n * @param value - A discriminated union value with _tag\n * @param handlers - An object with a handler function for each variant\n * @returns The result of calling the matching handler\n *\n * @see {@link union} for creating discriminated unions\n * @see {@link variant} for creating individual variant types\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const Circle = Adt.variant(\"Circle\", z.object({ radius: z.number() }))\n * const Square = Adt.variant(\"Square\", z.object({ size: z.number() }))\n * const Shape = Adt.union(\"Shape\", { Circle, Square })\n * type Shape = Adt.Infer<typeof Shape>\n *\n * function describeShape(shape: Shape): string {\n * return Adt.match(shape, {\n * Circle: (c) => `Circle with radius ${c.radius}`,\n * Square: (s) => `Square with size ${s.size}`,\n * })\n * }\n * ```\n */\nexport function match<\n T extends { readonly _tag: string },\n TResult,\n Handlers extends AdtMatchHandlers<T, TResult> = AdtMatchHandlers<T, TResult>,\n>(value: T, handlers: Handlers): TResult {\n const tag = value._tag as keyof Handlers\n const handler = handlers[tag]\n // oxlint-disable-next-line no-explicit-any, no-unsafe-argument, no-unsafe-type-assertion -- Required for variant dispatch\n return handler(value as any)\n}\n","/**\n * Check if a value is a plain object.\n * A plain object is an object created with `{}`, `Object.create(null)`, or `new Object()`.\n * Arrays, functions, dates, maps, etc. are not considered plain objects.\n */\nexport function isPlainObject(value: unknown): value is Record<PropertyKey, unknown> {\n if (value === null || typeof value !== \"object\") {\n return false\n }\n\n return Object.getPrototypeOf(value) === null || Object.getPrototypeOf(value) === Object.prototype\n}\n","import { validateSync as validateSchemaSync } from \"../schema/schema.shared\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport type { AdtVariant } from \"./adt.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is an AdtVariant created by variant().\n * AdtVariants are callable functions with static properties.\n */\nexport function isVariant(value: unknown): value is AdtVariant {\n return typeof value === \"function\" && \"_variant\" in value && value[\"_variant\"] === true\n}\n\n/**\n * Validate data using a Standard Schema, enforcing sync-only validation.\n * Throws if the schema returns a Promise.\n */\nexport function validateSync<T>(schema: StandardSchemaV1<unknown, T>, data: unknown, _tag: string) {\n return validateSchemaSync(schema, data, `ADT variant \"${_tag}\"`)\n}\n\n/**\n * Create a type guard function for a specific _tag.\n */\nexport function createIsGuard<Tag extends string, T>(\n _tag: Tag,\n): (value: unknown) => value is T & { readonly _tag: Tag } {\n return (value: unknown): value is T & { readonly _tag: Tag } => {\n return isPlainObject(value) && \"_tag\" in value && value[\"_tag\"] === _tag\n }\n}\n\n/**\n * Create a type guard function for multiple _tags (AdtUnion root guard).\n */\nexport function createIsAnyGuard<T>(_tags: readonly string[]): (value: unknown) => value is T {\n const _tagSet = new Set(_tags)\n return (value: unknown): value is T => {\n return isPlainObject(value) && \"_tag\" in value && typeof value[\"_tag\"] === \"string\" && _tagSet.has(value[\"_tag\"])\n }\n}\n","import { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { ValidationError } from \"../schema/schema.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type {\n AdtCodecConstraint,\n AdtCodecDef,\n AdtCodecError,\n AdtInferInput,\n AdtInferOutput,\n ToMethods,\n FromMethods,\n} from \"./adt.types\"\nimport { validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a AdtCodecError with consistent structure.\n */\nfunction createCodecError(\n kind: AdtCodecError[\"kind\"],\n message: string,\n cause?: unknown,\n validationIssues?: ValidationError[\"issues\"],\n): AdtCodecError {\n if (cause !== undefined && validationIssues !== undefined) {\n return { kind, message, cause, validationIssues }\n }\n if (cause !== undefined) {\n return { kind, message, cause }\n }\n if (validationIssues !== undefined) {\n return { kind, message, validationIssues }\n }\n return { kind, message }\n}\n\n/**\n * Built-in JSON codec that works with any schema.\n * Encodes to JSON string and decodes with JSON.parse.\n */\nfunction createJsonCodec<Tag extends string, S extends StandardSchemaV1>(\n _tag: Tag,\n): AdtCodecDef<AdtInferOutput<S> & Discriminator<Tag>, string, AdtInferInput<S>> {\n return {\n to: (value) => {\n // JSON.stringify can throw for circular references, BigInt, etc.\n // We let it throw and catch it in the wrapper\n return JSON.stringify(value)\n },\n /* oxlint-disable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return -- Required for JSON parsing which returns unknown types */\n from: (input: string) => {\n try {\n const parsed = JSON.parse(input)\n // Return parsed object without _tag - it will be added during validation\n if (typeof parsed === \"object\" && parsed !== null && \"_tag\" in parsed) {\n const { _tag: _, ...rest } = parsed\n return rest as AdtInferInput<S>\n }\n return parsed\n } catch {\n return null\n }\n },\n /* oxlint-enable no-unsafe-assignment, no-unsafe-type-assertion, no-unsafe-return */\n }\n}\n\n/**\n * Create the \"to\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createToMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): ToMethods<S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const to: Record<string, (value: AdtInferInput<S>) => Result<any, AdtCodecError>> = {\n json: (value: AdtInferInput<S>): Result<string, AdtCodecError> => {\n // First, create a validated variant to ensure the encoded payload is well-typed.\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input into object\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(jsonCodec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\"EncodingError\", `JSON encoding failed: ${e instanceof Error ? e.message : String(e)}`, e),\n )\n }\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n to[name] = (value: AdtInferInput<S>): Result<any, AdtCodecError> => {\n // Validate input first\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(value as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n `Cannot encode invalid data: ${result.error.issues.map((i) => i.message).join(\", \")}`,\n undefined,\n result.error.issues,\n ),\n )\n }\n\n try {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for validated value cast\n return ok(codec.to(result.value as Output))\n } catch (e) {\n return err(\n createCodecError(\n \"EncodingError\",\n `Encoding with codec '${name}' failed: ${e instanceof Error ? e.message : String(e)}`,\n e,\n ),\n )\n }\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return to as ToMethods<S, Codecs>\n}\n\n/**\n * Create the \"from\" methods object with JSON codec and custom codecs.\n * All methods return Result<T, AdtCodecError> for consistent error handling.\n */\nexport function createFromMethods<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined = undefined,\n>(_tag: Tag, schema: S, customCodecs?: Codecs): FromMethods<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const jsonCodec = createJsonCodec<Tag, S>(_tag)\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const from: Record<string, (input: any) => Result<Output, AdtCodecError>> = {\n json: (input: string): Result<Output, AdtCodecError> => {\n // Decode\n const decoded = jsonCodec.from(input)\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", \"Invalid JSON format\"))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\"ValidationError\", \"Decoded data failed schema validation\", undefined, result.error.issues),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n },\n }\n\n // Add custom codecs\n if (customCodecs) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n for (const [name, codec] of Object.entries(customCodecs) as Array<[string, AdtCodecDef<Output, any, any>]>) {\n from[name] = (input: unknown): Result<Output, AdtCodecError> => {\n // Decode\n let decoded: unknown\n try {\n decoded = codec.from(input)\n } catch (e) {\n return err(createCodecError(\"DecodingError\", `Decoding with codec '${name}' threw an error`, e))\n }\n\n if (decoded === null) {\n return err(createCodecError(\"DecodingError\", `Codec '${name}' failed to decode input`))\n }\n\n // Validate through schema\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading decoded value\n const taggedInput = { ...(decoded as object), _tag }\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(\n createCodecError(\n \"ValidationError\",\n \"Decoded data failed schema validation\",\n undefined,\n result.error.issues,\n ),\n )\n }\n\n // Ensure _tag in output\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n }\n }\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic return type\n return from as FromMethods<Tag, S, Codecs>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport { ok, err } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport type { ValidationError } from \"../schema/schema.types\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport { createToMethods, createFromMethods } from \"./adt.codec\"\nimport type { AdtCodecConstraint, AdtInferInput, AdtInferOutput, AdtVariant } from \"./adt.types\"\nimport { createIsGuard, validateSync } from \"./adt.utils\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged variant from a Standard Schema with optional codecs.\n *\n * Variants can be used independently or composed into an AdtUnion via union().\n * All defaults should be defined at the schema level (e.g., Zod's .default()).\n *\n * @template Tag - The string literal type for the _tag discriminator\n * @template S - The Standard Schema type for validation\n * @template Codecs - Optional codec definitions for custom serialization formats\n * @param _tag - The _tag discriminator value\n * @param schema - A Standard Schema compliant validator\n * @param codecs - Optional codec definitions for custom serialization formats\n * @returns A callable AdtVariant with is(), to, and from methods\n *\n * @see {@link union} for composing variants into discriminated unions\n * @see {@link tagged} for unvalidated tagged value constructors\n *\n * @example\n * ```ts\n * const CircleSchema = z.object({\n * radius: z.number().positive(),\n * color: z.string().default('blue')\n * })\n *\n * // Basic variant with JSON codec (always included)\n * const Circle = variant('Circle', CircleSchema)\n *\n * const result = Circle({ radius: 10 })\n * // { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 10, color: \"blue\" } }\n *\n * Circle.is(someValue) // type guard\n *\n * const json = Circle.to.json({ radius: 10 }) // JSON string\n * const result2 = Circle.from.json(json) // Result<Circle, AdtCodecError>\n *\n * // Variant with custom codec\n * const Circle2 = variant('Circle', CircleSchema, {\n * graphic: {\n * to: (circle) => `(${circle.radius})`,\n * from: (input: string) => {\n * const match = input.match(/^\\((\\d+)\\)$/)\n * return match ? { radius: parseInt(match[1]!) } : null\n * }\n * }\n * })\n *\n * const graphic = Circle2.to.graphic({ radius: 10 }) // \"(10)\"\n * const result3 = Circle2.from.graphic(\"(10)\") // Result<Circle, AdtCodecError>\n * ```\n */\n// Overload: with codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1, Codecs extends AdtCodecConstraint<Tag, S>>(\n _tag: Tag,\n schema: S,\n codecs: Codecs,\n): AdtVariant<Tag, S, Codecs>\n\n// Overload: without codecs\nexport function variant<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): AdtVariant<Tag, S>\n\n// Implementation\nexport function variant<\n Tag extends string,\n S extends StandardSchemaV1,\n Codecs extends AdtCodecConstraint<Tag, S> | undefined,\n>(_tag: Tag, schema: S, codecs?: Codecs): AdtVariant<Tag, S, Codecs> {\n type Output = AdtInferOutput<S> & Discriminator<Tag>\n\n const isGuard = createIsGuard<Tag, Output>(_tag)\n const to = createToMethods(_tag, schema, codecs)\n const from = createFromMethods(_tag, schema, codecs)\n const equals = createEqualsMethod<Tag, AdtInferOutput<S>>(_tag)\n const hash = createHashMethod<Tag, AdtInferOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: AdtInferInput<S>): Result<Output, ValidationError> => {\n // Add _tag to the input before validation\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for spreading generic input\n const taggedInput = { ...(input as object), _tag }\n\n // Validate using the schema\n const result = validateSync(schema, taggedInput, _tag)\n\n if (result._tag === \"Err\") {\n return err(result.error)\n }\n\n // Ensure _tag is in the output (schema might strip unknown keys)\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for output construction\n const output = { ...(result.value as object), _tag } as Output\n return ok(output)\n }\n\n // Attach static properties to constructor function\n constructor._variant = true as const\n constructor._tag = _tag\n constructor.schema = schema\n if (codecs) {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Conditional assignment of codecs\n ;(constructor as { codecs?: Codecs }).codecs = codecs\n }\n constructor.is = isGuard\n constructor.to = to\n constructor.from = from\n constructor.equals = equals\n constructor.hash = hash\n\n return constructor as AdtVariant<Tag, S, Codecs>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport type { AdtUnion, AdtVariantDef, AdtVariant } from \"./adt.types\"\nimport { createIsAnyGuard, isVariant } from \"./adt.utils\"\nimport { variant } from \"./adt.variant\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (AdtUnion).\n *\n * Accepts either:\n * - Pre-built AdtVariants from variant() (codecs are preserved)\n * - Raw Standard Schema validators (will be wrapped internally)\n *\n * When using pre-built records, the object key overrides the original _tag.\n *\n * @template R - Record of variant names to AdtVariants or StandardSchema validators\n * @param name - The name of this AdtUnion (for identification)\n * @param records - An object mapping _tag names to AdtVariants or schemas\n * @returns An AdtUnion object with accessors for each variant\n *\n * @see {@link variant} for creating individual variant types\n * @see {@link match} for exhaustive pattern matching on AdtUnion values\n *\n * @example\n * ```ts\n * // From pre-built variants\n * const Circle = variant('Circle', CircleSchema)\n * const Square = variant('Square', SquareSchema)\n * const Shape = union('Shape', { Circle, Square })\n *\n * // From raw schemas (JSON codec is automatically included)\n * const Shape = union('Shape', {\n * Circle: CircleSchema,\n * Square: SquareSchema\n * })\n *\n * // JSON codec works on all variants\n * Shape.Circle.to.json({ radius: 10 })\n * Shape.Circle.from.json(jsonString)\n *\n * // Mixed\n * const Shape = union('Shape', {\n * Circle, // Pre-built variant\n * Square: SquareSchema // Raw schema\n * })\n *\n * // Usage\n * Shape.Circle({ radius: 10 })\n * Shape.is(someValue) // type guard for any variant\n * Shape.Circle.is(someValue) // type guard for Circle\n * ```\n */\nexport function union<R extends Record<string, AdtVariantDef>>(name: string, records: R): AdtUnion<R> {\n const tags = Object.keys(records)\n const variants: Record<string, AdtVariant> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isVariant(def)) {\n // Pre-built AdtVariant - key overrides original _tag\n if (def._tag === _tag) {\n // _tag matches key, use as-is (preserves codecs)\n variants[_tag] = def\n // oxlint-disable-next-line strict-boolean-expressions -- codecs can be undefined\n } else if (def.codecs) {\n // _tag differs from key - create new variant with key as _tag\n // Preserve codecs\n variants[_tag] = variant(_tag, def.schema, def.codecs)\n } else {\n // _tag differs from key and no codecs\n variants[_tag] = variant(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in variant\n // Note: Even without custom codecs, this still gets JSON codec!\n // oxlint-disable-next-line no-unsafe-type-assertion -- def is a StandardSchemaV1 in this branch\n variants[_tag] = variant(_tag, def as StandardSchemaV1)\n }\n }\n\n // Create the root type guard for any variant\n const isAnyVariant = createIsAnyGuard(tags)\n const equals = createADTEqualsMethod(tags)\n const hash = createADTHashMethod(tags)\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic AdtUnion return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as AdtUnion<R>\n}\n","/**\n * Tagged union builders and match helpers.\n *\n * **Mental model**\n * - `Adt` helps build discriminated unions with runtime validation.\n * - Use `union`, `variant`, and `match` to model algebraic data types.\n *\n * **Common tasks**\n * - Define variants with `Adt.variant`.\n * - Combine variants with `Adt.union`.\n * - Pattern-match with `Adt.match`.\n *\n * **Gotchas**\n * - `Adt` codec/type helpers are mostly type-level.\n * - Prefer namespace imports from `@nicolastoulemont/std`.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const CircleSchema = z.object({ radius: z.number() })\n *\n * const Shape = Adt.union(\"Shape\", { Circle: CircleSchema })\n * const result = Shape.Circle({ radius: 2 })\n * // => { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 2 } }\n * ```\n *\n * @module\n */\nimport { match as matchImpl } from \"./adt.match\"\nimport type {\n AdtInfer as AdtInferType,\n AdtVariantNames as AdtVariantNamesType,\n AdtVariantOf as AdtVariantOfType,\n} from \"./adt.types\"\nimport { union as unionImpl } from \"./adt.union\"\nimport { variant as variantImpl } from \"./adt.variant\"\n\n/**\n * Re-exported ADT inferred union helper.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const Shape = Adt.union(\"Shape\", {\n * Circle: z.object({ radius: z.number() }),\n * })\n * type Shape = Adt.Infer<typeof Shape>\n * ```\n */\nexport type Infer<T> = AdtInferType<T>\n\n/**\n * Re-exported union variant name helper.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const Shape = Adt.union(\"Shape\", {\n * Circle: z.object({ radius: z.number() }),\n * })\n * type Names = Adt.VariantNames<typeof Shape>\n * ```\n */\nexport type VariantNames<T> = AdtVariantNamesType<T>\n\n/**\n * Re-exported helper to extract a specific variant from an ADT.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const Shape = Adt.union(\"Shape\", {\n * Circle: z.object({ radius: z.number() }),\n * })\n * type Circle = Adt.VariantOf<typeof Shape, \"Circle\">\n * ```\n */\nexport type VariantOf<T, K extends string> = AdtVariantOfType<T, K>\n\n/**\n * Build an ADT union from named variants.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const CircleSchema = z.object({ radius: z.number() })\n *\n * const Shape = Adt.union(\"Shape\", { Circle: CircleSchema })\n * const result = Shape.Circle({ radius: 2 })\n * // => { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 2 } }\n * ```\n */\nexport const union = unionImpl\n\n/**\n * Define one ADT variant with schema-backed validation.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n * import { z } from \"zod\"\n *\n * // Adt accepts any Standard Schema-compatible schema, such as zod, valibot, or arktype.\n * const CircleSchema = z.object({ radius: z.number() })\n *\n * const Circle = Adt.variant(\"Circle\", CircleSchema)\n * const result = Circle({ radius: 2 })\n * // => { _tag: \"Ok\", value: { _tag: \"Circle\", radius: 2 } }\n * ```\n */\nexport const variant = variantImpl\n\n/**\n * Match over ADT variants by discriminator tag.\n *\n * @example\n * ```ts\n * import { Adt } from \"@nicolastoulemont/std\"\n *\n * const label = Adt.match({ _tag: \"Circle\", radius: 2 } as const, {\n * Circle: (circle) => `r=${circle.radius}` ,\n * })\n * // => \"r=2\"\n * ```\n */\nexport const match = matchImpl\n"],"mappings":"kMA8CA,SAAgBA,EAId,EAAU,EAA6B,CAEvC,IAAM,EAAU,EADJ,EAAM,MAGlB,OAAO,EAAQ,EAAa,CCjD9B,SAAgB,EAAc,EAAuD,CAKnF,OAJsB,OAAO,GAAU,WAAnC,EACK,GAGF,OAAO,eAAe,EAAM,GAAK,MAAQ,OAAO,eAAe,EAAM,GAAK,OAAO,UCD1F,SAAgB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I,OAGb,EAAS,GAAQC,EAAQ,EAAM,EAAI,OAAQ,EAAI,OAAO,CAGtD,EAAS,GAAQA,EAAQ,EAAM,EAAI,OAAO,CAM5C,EAAS,GAAQA,EAAQ,EAAM,EAAwB,CAU3D,MAAO,CACL,MAAO,EACP,GAPmB,EAAiB,EAAK,CAQzC,OAPa,EAAsB,EAAK,CAQxC,KAPW,EAAoB,EAAK,CAQpC,GAAG,EACJ,kDCkBH,MAAa,EAAQC,EAkBR,EAAUC,EAeV,EAAQC"}
|
package/dist/data-BHYPdqWZ.mjs
DELETED
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./chunk-oQKkju2G.mjs";import{a as t,i as n,o as r,r as i}from"./equality-BX6BUidG.mjs";import{t as a}from"./fx.types-DyQVgTS8.mjs";function o(e){let n=[...e];Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1});let i=n.map.bind(n);Object.defineProperty(n,`map`,{value:e=>o(i(e)),enumerable:!1,writable:!1,configurable:!1});let a=n.filter.bind(n);Object.defineProperty(n,`filter`,{value:e=>o(a(e)),enumerable:!1,writable:!1,configurable:!1});let s=n.slice.bind(n);Object.defineProperty(n,`slice`,{value:(e,t)=>o(s(e,t)),enumerable:!1,writable:!1,configurable:!1});let c=n.concat.bind(n);return Object.defineProperty(n,`concat`,{value:(...e)=>o(c(...e)),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}function s(e){let n={...e};return Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}function c(e){let t=t=>Object.freeze({...t,_tag:e});return t.is=t=>typeof t==`object`&&!!t&&`_tag`in t&&t._tag===e,t.equals=i(e),t.hash=n(e),t._tag=e,t}function l(e){return class extends Error{static _tag=e;_tag=e;[a]={_A:()=>void 0,_E:()=>this,_R:()=>void 0};constructor(...t){super(e),this.name=e;let n=t[0];n&&Object.assign(this,n),Object.setPrototypeOf(this,new.target.prototype)}*[Symbol.iterator](){throw yield this,Error(`Unreachable: Fx.gen should short-circuit on error`)}}}function u(...e){let n=[...e];return Object.defineProperty(n,`equals`,{value:e=>t(n,e),enumerable:!1,writable:!1,configurable:!1}),Object.defineProperty(n,`hash`,{value:()=>r(n),enumerable:!1,writable:!1,configurable:!1}),Object.freeze(n)}var d=e({TaggedError:()=>p,array:()=>g,struct:()=>m,tagged:()=>f,tuple:()=>h});const f=c,p=l,m=s,h=u,g=o;export{d as n,p as t};
|
|
2
|
-
//# sourceMappingURL=data-BHYPdqWZ.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"data-BHYPdqWZ.mjs","names":["array","struct","tagged","TaggedError","tuple","taggedImpl","TaggedErrorImpl","structImpl","tupleImpl","arrayImpl"],"sources":["../src/data/data.array.ts","../src/data/data.struct.ts","../src/data/data.tagged.ts","../src/data/data.tagged-error.ts","../src/data/data.tuple.ts","../src/data/data.ts"],"sourcesContent":["import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { ArrayValue } from \"./data.types\"\n\n/**\n * Create an array with structural equality.\n *\n * The returned array is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * The map() and filter() methods are overridden to return ArrayValue,\n * enabling method chaining with preserved equality semantics.\n *\n * @template T - The element type of the array\n * @param items - The array elements\n * @returns A frozen array with equals(), hash(), map(), and filter()\n *\n * @see {@link tuple} for fixed-length typed tuples\n * @see {@link struct} for object value types\n *\n * @example\n * ```ts\n * const arr1 = array([1, 2, 3])\n * const arr2 = array([1, 2, 3])\n *\n * arr1.equals(arr2) // true\n * arr1.hash() // number\n *\n * // Chainable operations return ArrayValue\n * arr1.map(x => x * 2) // ArrayValue<number>\n * arr1.filter(x => x > 1) // ArrayValue<number>\n *\n * // Chained equality check\n * arr1.map(x => x * 2).equals(array([2, 4, 6])) // true\n *\n * // Array is frozen\n * arr1[0] = 5 // TypeError\n * arr1.push(4) // TypeError\n * ```\n */\nexport function array<T>(items: readonly T[]): ArrayValue<T> {\n const value = [...items]\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: readonly T[]) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override map to return ArrayValue\n const originalMap = value.map.bind(value)\n Object.defineProperty(value, \"map\", {\n value: <U>(fn: (item: T, index: number, arr: readonly T[]) => U): ArrayValue<U> => {\n return array(originalMap(fn))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override filter to return ArrayValue\n const originalFilter = value.filter.bind(value)\n Object.defineProperty(value, \"filter\", {\n value: (fn: (item: T, index: number, arr: readonly T[]) => boolean): ArrayValue<T> => {\n return array(originalFilter(fn))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override slice to return ArrayValue\n const originalSlice = value.slice.bind(value)\n Object.defineProperty(value, \"slice\", {\n value: (start?: number, end?: number): ArrayValue<T> => {\n return array(originalSlice(start, end))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Override concat to return ArrayValue\n const originalConcat = value.concat.bind(value)\n Object.defineProperty(value, \"concat\", {\n value: (...args: readonly (T | readonly T[])[]): ArrayValue<T> => {\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for concat argument spread\n return array(originalConcat(...(args as T[][])))\n },\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic array return type\n return Object.freeze(value) as unknown as ArrayValue<T>\n}\n","import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { StructValue } from \"./data.types\"\n\n/**\n * Create a frozen value object with structural equality.\n *\n * Unlike tagged(), struct() does not add a _tag discriminator.\n * Use this for simple value objects that don't need discrimination.\n *\n * The returned object is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * @template T - The object shape type\n * @param input - The object to wrap\n * @returns A frozen object with equals() and hash() methods\n *\n * @see {@link tagged} for discriminated value objects with _tag\n * @see {@link array} for array value types\n *\n * @example\n * ```ts\n * const point = struct({ x: 10, y: 20 })\n * const point2 = struct({ x: 10, y: 20 })\n *\n * point.equals(point2) // true\n * point.hash() // number\n *\n * // Object is frozen\n * point.x = 5 // TypeError\n *\n * // equals/hash are non-enumerable\n * Object.keys(point) // [\"x\", \"y\"]\n * ```\n */\nexport function struct<T extends Record<string, unknown>>(input: T): StructValue<T> {\n const value = { ...input }\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: T) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic struct return type\n return Object.freeze(value) as StructValue<T>\n}\n","import { createEqualsMethod, createHashMethod } from \"../equality/equality\"\nimport type { Discriminator } from \"../shared/discriminator.types\"\nimport type { TaggedConstructor, TaggedValue } from \"./data.types\"\n\n/**\n * Create a tagged value constructor without schema validation.\n *\n * Unlike variant(), this creates values directly without validation.\n * Values are frozen and have structural equality via equals() and hash() methods.\n *\n * @template T - The data shape type (excluding _tag)\n * @param tag - The _tag discriminator value\n * @returns A constructor function with is(), equals(), and hash() methods\n *\n * @see {@link variant} for validated variant with schema support\n * @see {@link struct} for untagged value objects\n *\n * @example\n * ```ts\n * const Person = tagged<{ name: string; age: number }>(\"Person\")\n *\n * const alice = Person({ name: \"Alice\", age: 30 })\n * // => { _tag: \"Person\", name: \"Alice\", age: 30 }\n *\n * Person.equals(alice, Person({ name: \"Alice\", age: 30 })) // true\n * Person.is(alice) // true\n *\n * // Type guard usage\n * if (Person.is(unknownValue)) {\n * console.log(unknownValue.name) // TypeScript knows it's a Person\n * }\n *\n * // Values are frozen (immutable)\n * alice.name = \"Bob\" // TypeError\n * ```\n */\nexport function tagged<T extends Record<string, unknown>>(tag: string): TaggedConstructor<typeof tag, T> {\n type Output = TaggedValue<typeof tag, T>\n\n // Constructor function\n const constructor = (input: T): Output => {\n return Object.freeze({ ...input, _tag: tag }) as Output\n }\n\n // Type guard\n constructor.is = (value: unknown): value is Output => {\n return (\n typeof value === \"object\" &&\n value !== null &&\n \"_tag\" in value &&\n // oxlint-disable-next-line no-unsafe-type-assertion -- Already checked with 'in' operator\n (value as Discriminator)._tag === tag\n )\n }\n\n // Equality (static method on constructor)\n constructor.equals = createEqualsMethod<typeof tag, T>(tag)\n\n // Hashing (static method on constructor)\n constructor.hash = createHashMethod<typeof tag, T>(tag)\n\n // Store tag for reflection\n constructor._tag = tag\n\n return constructor as TaggedConstructor<typeof tag, T>\n}\n","import { FxTypeId } from \"../fx/fx.types\"\nimport type { TaggedErrorFactory } from \"./data.tagged-error.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Tagged error factories intentionally cast to preserve ergonomic constructor signatures and Fx marker channels. */\n\n/**\n * Create a class-based tagged error type (Effect-style syntax).\n * Returns a class that can be extended to create custom error types.\n * Errors are native Error objects with proper stack traces and instanceof support.\n * Implements Yieldable protocol so errors can be directly yielded in Fx.gen computations.\n *\n * @template Tag - The error tag (discriminator string)\n * @param tag - The error tag\n * @returns A class that can be extended with custom data\n *\n * @example\n * ```ts\n * // Error with data\n * class NotFoundError extends TaggedError(\"NotFoundError\")<{ id: string }> {}\n * const err = new NotFoundError({ id: \"123\" })\n * err.id // \"123\"\n * err._tag // \"NotFoundError\"\n * err.stack // Error stack trace\n *\n * // Error without data\n * class UnauthorizedError extends TaggedError(\"UnauthorizedError\") {}\n * const err2 = new UnauthorizedError()\n *\n * // Direct yielding in Fx.gen computation\n * const program = Fx.gen(function* () {\n * yield* new NotFoundError({ id: \"123\" }) // Short-circuits with error\n * })\n *\n * // instanceof checks work\n * if (err instanceof NotFoundError) {\n * console.log(err.id)\n * }\n * ```\n */\nexport function TaggedError<Tag extends string>(tag: Tag): TaggedErrorFactory<Tag> {\n return class TaggedErrorImpl<Data extends object = object> extends Error {\n static readonly _tag: Tag = tag\n readonly _tag: Tag = tag\n\n readonly [FxTypeId] = {\n _A: () => undefined as never,\n _E: () => this as TaggedErrorImpl<Data>,\n _R: () => undefined as never,\n }\n\n constructor(...args: keyof Data extends never ? [] : [data: Data]) {\n super(tag)\n this.name = tag\n const data = args[0]\n if (data) Object.assign(this, data)\n Object.setPrototypeOf(this, new.target.prototype)\n }\n\n *[Symbol.iterator](): Generator<this, never, unknown> {\n yield this\n throw new Error(\"Unreachable: Fx.gen should short-circuit on error\")\n }\n } as unknown as TaggedErrorFactory<Tag>\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n","import { deepEquals, deepHash } from \"../equality/equality\"\nimport type { TupleValue } from \"./data.types\"\n\n/**\n * Create a tuple with structural equality.\n *\n * The returned tuple is frozen (immutable) and has non-enumerable\n * equals() and hash() methods for structural comparison.\n *\n * @template T - The tuple type as a readonly array of element types\n * @param args - The tuple elements\n * @returns A frozen tuple-like array with equals() and hash() methods\n *\n * @see {@link array} for variable-length arrays with equality\n * @see {@link struct} for object value types\n *\n * @example\n * ```ts\n * const t1 = tuple(1, \"hello\", true)\n * const t2 = tuple(1, \"hello\", true)\n *\n * t1.equals(t2) // true\n * t1.hash() // number\n *\n * // Access elements (typed)\n * t1[0] // number\n * t1[1] // string\n * t1[2] // boolean\n *\n * // Tuple is frozen\n * t1[0] = 5 // TypeError\n * ```\n */\nexport function tuple<T extends readonly unknown[]>(...args: T): TupleValue<T> {\n const value = [...args]\n\n // Add equals method (non-enumerable)\n Object.defineProperty(value, \"equals\", {\n value: (other: readonly unknown[]) => deepEquals(value, other),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // Add hash method (non-enumerable)\n Object.defineProperty(value, \"hash\", {\n value: () => deepHash(value),\n enumerable: false,\n writable: false,\n configurable: false,\n })\n\n // oxlint-disable-next-line no-unsafe-type-assertion -- Required for generic tuple return type\n return Object.freeze(value) as unknown as TupleValue<T>\n}\n","/**\n * Structural data constructors for tagged objects, tuples, arrays, and records.\n *\n * **Mental model**\n * - `Data` helpers create immutable-friendly values with structural equality semantics.\n * - Use `tagged` and `TaggedError` to model domain objects and errors.\n *\n * **Common tasks**\n * - Build tagged records via `Data.tagged`.\n * - Define typed tagged errors with `Data.TaggedError`.\n * - Create structural containers with `Data.struct`, `Data.tuple`, and `Data.array`.\n *\n * **Gotchas**\n * - These constructors are value-level utilities, not validation schemas.\n * - Prefer explicit tagged names for debugging and pattern matching.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const User = Data.tagged<{ id: string }>(\"User\")\n * const user = User({ id: \"u1\" })\n * // => { _tag: \"User\", id: \"u1\" }\n * ```\n *\n * @module\n */\nimport { array as arrayImpl } from \"./data.array\"\nimport { struct as structImpl } from \"./data.struct\"\nimport { tagged as taggedImpl } from \"./data.tagged\"\nimport { TaggedError as TaggedErrorImpl } from \"./data.tagged-error\"\nexport type { TaggedErrorClass, TaggedErrorCore, TaggedErrorFactory, TaggedErrorInstance } from \"./data.tagged-error.types\"\nimport { tuple as tupleImpl } from \"./data.tuple\"\n\n/**\n * Construct tagged data objects.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const User = Data.tagged<{ id: string }>(\"User\")\n * const user = User({ id: \"u1\" })\n * // => { _tag: \"User\", id: \"u1\" }\n * ```\n */\nexport const tagged = taggedImpl\n\n/**\n * Construct tagged error classes.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * class NotFoundError extends Data.TaggedError(\"NotFoundError\")<{ id: string }> {}\n * const error = new NotFoundError({ id: \"u1\" })\n * // => { _tag: \"NotFoundError\", id: \"u1\" }\n * ```\n */\nexport const TaggedError = TaggedErrorImpl\n\n/**\n * Construct immutable-like structs with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const point = Data.struct({ x: 1, y: 2 })\n * const same = point.equals({ x: 1, y: 2 })\n * // => true\n * ```\n */\nexport const struct = structImpl\n\n/**\n * Construct immutable-like tuples with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const pair = Data.tuple(\"left\", 1)\n * const first = pair[0]\n * // => \"left\"\n * ```\n */\nexport const tuple = tupleImpl\n\n/**\n * Construct immutable-like arrays with stable structural behavior.\n *\n * @example\n * ```ts\n * import { Data } from \"@nicolastoulemont/std\"\n *\n * const ids = Data.array([\"a\", \"b\"])\n * const upper = ids.map((id) => id.toUpperCase())\n * // => [\"A\", \"B\"]\n * ```\n */\nexport const array = arrayImpl\n"],"mappings":"sJAuCA,SAAgBA,EAAS,EAAoC,CAC3D,IAAM,EAAQ,CAAC,GAAG,EAAM,CAGxB,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GAAwB,EAAW,EAAO,EAAM,CACxD,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,OAAO,eAAe,EAAO,OAAQ,CACnC,UAAa,EAAS,EAAM,CAC5B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAc,EAAM,IAAI,KAAK,EAAM,CACzC,OAAO,eAAe,EAAO,MAAO,CAClC,MAAW,GACFA,EAAM,EAAY,EAAG,CAAC,CAE/B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAiB,EAAM,OAAO,KAAK,EAAM,CAC/C,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GACCA,EAAM,EAAe,EAAG,CAAC,CAElC,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,IAAM,EAAgB,EAAM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ACnC,OAAO,eAAe,KAAM,IAAI,OAAO,UAAU,CAGnD,EAAE,OAAO,WAA6C,CAEpD,MADA,MAAM,KACI,MAAM,oDAAoD,GC3B1E,SAAgBC,EAAoC,GAAG,EAAwB,CAC7E,IAAM,EAAQ,CAAC,GAAG,EAAK,CAmBvB,OAhBA,OAAO,eAAe,EAAO,SAAU,CACrC,MAAQ,GAA8B,EAAW,EAAO,EAAM,CAC9D,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGF,OAAO,eAAe,EAAO,OAAQ,CACnC,UAAa,EAAS,EAAM,CAC5B,WAAY,GACZ,SAAU,GACV,aAAc,GACf,CAAC,CAGK,OAAO,OAAO,EAAM,gFCL7B,MAAa,EAASC,EAcT,EAAcC,EAcd,EAASC,EAcT,EAAQC,EAcR,EAAQC"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"discriminator.types-C-ygT2S1.d.mts","names":[],"sources":["../src/shared/discriminator.types.ts"],"sourcesContent":[],"mappings":";KAAY;EAAA,SAAA,IAAA,EAA8D,GAAjD"}
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const e=16777619,t=()=>({hashes:new WeakMap,inProgress:new WeakSet,objectIds:new WeakMap,nextObjectId:1}),n=(e,t)=>{let n=e.objectIds.get(t);if(n!==void 0)return n;let r=e.nextObjectId;return e.objectIds.set(t,r),e.nextObjectId++,r},r=(t,i)=>{let a=2166136261;if(t===null)return a^1853189228;if(t===void 0)return a^1970168933;switch(typeof t){case`boolean`:return a^(t?1:0);case`number`:return Number.isNaN(t)?a^5136718:Number.isFinite(t)?a^(t|0)^(t*1e6|0):a^(t>0?4812390:759787110);case`string`:for(let n=0;n<t.length;n++)a^=t.codePointAt(n),a=Math.imul(a,e);return a>>>0;case`object`:{let o=t,s=i.hashes.get(o);if(s!==void 0)return s;if(i.inProgress.has(o))return(a^1668899692^n(i,o))>>>0;if(t instanceof Date)return a^r(t.getTime(),i);if(i.inProgress.add(o),n(i,o),Array.isArray(t)){a^=23389;for(let n=0;n<t.length;n++)a^=r(t[n],i),a=Math.imul(a,e);let n=a>>>0;return i.inProgress.delete(o),i.hashes.set(o,n),n}a^=31613;let c=t,l=Object.keys(c).toSorted();for(let t of l)a^=r(t,i),a=Math.imul(a,e),a^=r(c[t],i),a=Math.imul(a,e);let u=a>>>0;return i.inProgress.delete(o),i.hashes.set(o,u),u}default:return a}};function i(e){return r(e,t())}const a=(e,t,n)=>{let r=e.get(t);return r?.has(n)===!0?!0:r===void 0?(e.set(t,new WeakSet([n])),!1):(r.add(n),!1)},o=(e,t,n)=>{if(e===t)return!0;if(typeof e!=typeof t||e===null||t===null||typeof e!=`object`||typeof t!=`object`)return!1;if(a(n,e,t))return!0;if(e instanceof Date&&t instanceof Date)return e.getTime()===t.getTime();if(Array.isArray(e)&&Array.isArray(t))return e.length===t.length?e.every((e,r)=>o(e,t[r],n)):!1;if(Array.isArray(e)!==Array.isArray(t))return!1;let r=e,i=t,s=Object.keys(r),c=Object.keys(i);return s.length===c.length?s.every(e=>o(r[e],i[e],n)):!1};function s(e,t){return o(e,t,new WeakMap)}function c(e){return(t,n)=>t===n?!0:t._tag!==e||n._tag!==e?!1:s(t,n)}function l(e){return t=>t._tag===e?i(t):0}function u(e){return(t,n)=>t===n?!0:t._tag!==n._tag||!e.includes(t._tag)?!1:s(t,n)}function d(e){return t=>e.includes(t._tag)?i(t):0}export{s as a,l as i,d as n,i as o,c as r,u as t};
|
|
2
|
-
//# sourceMappingURL=equality-BX6BUidG.mjs.map
|