@nicolastoulemont/std 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +406 -69
- 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-Cqkibdlt.d.mts} +1 -1
- package/dist/{brand.types-B3NDX1vo.d.mts.map → brand.types-Cqkibdlt.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-C9UX6GJo.d.mts} +2 -2
- package/dist/{context-B2dWloPl.d.mts.map → context-C9UX6GJo.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-Bas3mi1N.mjs → duration-Dwtjy95Z.mjs} +2 -2
- package/dist/{duration-Bas3mi1N.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-D5zZVlCn.d.mts +67 -0
- package/dist/exit-D5zZVlCn.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.d.mts +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-q661ckFI.d.mts +16 -0
- package/dist/fx.runtime-q661ckFI.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-DfAqfnY0.d.mts → index-BJiD1-T_.d.mts} +4 -4
- package/dist/{index-DfAqfnY0.d.mts.map → index-BJiD1-T_.d.mts.map} +1 -1
- package/dist/{index-DR7hzXU4.d.mts → index-BR6lwlNv.d.mts} +137 -29
- package/dist/index-BR6lwlNv.d.mts.map +1 -0
- package/dist/index-BfQSp6pV.d.mts +226 -0
- package/dist/index-BfQSp6pV.d.mts.map +1 -0
- package/dist/{index-uE3S3Krx.d.mts → index-Bo6pkkVO.d.mts} +5 -5
- package/dist/{index-uE3S3Krx.d.mts.map → index-Bo6pkkVO.d.mts.map} +1 -1
- package/dist/{index-D8rDE60Y.d.mts → index-BsCrdweM.d.mts} +1 -1
- package/dist/index-BsCrdweM.d.mts.map +1 -0
- package/dist/{index-D7mFNjot.d.mts → index-BtPFPfja.d.mts} +1 -1
- package/dist/{index-D7mFNjot.d.mts.map → index-BtPFPfja.d.mts.map} +1 -1
- package/dist/{index-BA0EsFxS.d.mts → index-C7uSldLA.d.mts} +3 -3
- package/dist/{index-BA0EsFxS.d.mts.map → index-C7uSldLA.d.mts.map} +1 -1
- package/dist/{index-CVmgBpDt.d.mts → index-CBtUJ94I.d.mts} +3 -3
- package/dist/{index-CVmgBpDt.d.mts.map → index-CBtUJ94I.d.mts.map} +1 -1
- package/dist/{index-BD-els5J.d.mts → index-CIEdspey.d.mts} +83 -59
- package/dist/index-CIEdspey.d.mts.map +1 -0
- package/dist/{index-dCRymj_g.d.mts → index-CXz5Z5MP.d.mts} +5 -5
- package/dist/{index-dCRymj_g.d.mts.map → index-CXz5Z5MP.d.mts.map} +1 -1
- package/dist/{index-D8gcYvR9.d.mts → index-DDdSA1Rs.d.mts} +5 -5
- package/dist/{index-D8gcYvR9.d.mts.map → index-DDdSA1Rs.d.mts.map} +1 -1
- package/dist/{index-BqJ1GWAF.d.mts → index-D_JbOTtg.d.mts} +2 -2
- package/dist/index-D_JbOTtg.d.mts.map +1 -0
- package/dist/index-DzGXoCV1.d.mts +433 -0
- package/dist/index-DzGXoCV1.d.mts.map +1 -0
- package/dist/{index-CNTYbcY9.d.mts → index-Pma2THAy.d.mts} +10 -3
- package/dist/index-Pma2THAy.d.mts.map +1 -0
- package/dist/{index-CIvNgjsx.d.mts → index-hrn4s4Vn.d.mts} +2 -2
- package/dist/{index-CIvNgjsx.d.mts.map → index-hrn4s4Vn.d.mts.map} +1 -1
- package/dist/{index-D6pjHqlK.d.mts → index-lYxaV6H7.d.mts} +49 -70
- package/dist/index-lYxaV6H7.d.mts.map +1 -0
- package/dist/index-xY9km50k.d.mts +59 -0
- package/dist/index-xY9km50k.d.mts.map +1 -0
- package/dist/index.d.mts +24 -21
- 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-smjitsoN.d.mts} +4 -4
- package/dist/{layer.types-BB0MrvLg.d.mts.map → layer.types-smjitsoN.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-Po1qwxiW.d.mts} +3 -3
- package/dist/{option.types-D9hrKcfa.d.mts.map → option.types-Po1qwxiW.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-CvH7cY_J.mjs +2 -0
- package/dist/predicate-CvH7cY_J.mjs.map +1 -0
- 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-GYVrD39q.mjs → queue-CeEIUHcY.mjs} +2 -2
- package/dist/{queue-GYVrD39q.mjs.map → queue-CeEIUHcY.mjs.map} +1 -1
- package/dist/{queue.types-B-l5XYbU.d.mts → queue.types-Bj63N2ab.d.mts} +1 -1
- package/dist/{queue.types-B-l5XYbU.d.mts.map → queue.types-Bj63N2ab.d.mts.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-JEcowzYH.d.mts} +6 -27
- package/dist/result.types-JEcowzYH.d.mts.map +1 -0
- package/dist/schedule/index.d.mts +1 -1
- package/dist/schedule/index.mjs +1 -1
- package/dist/{schedule-B7qV60tO.mjs → schedule-ChcIgvd5.mjs} +2 -2
- package/dist/{schedule-B7qV60tO.mjs.map → schedule-ChcIgvd5.mjs.map} +1 -1
- package/dist/{schedule-BzPjvMXc.d.mts → schedule-ap6y014J.d.mts} +3 -3
- package/dist/{schedule-BzPjvMXc.d.mts.map → schedule-ap6y014J.d.mts.map} +1 -1
- package/dist/schema/index.d.mts +1 -1
- package/dist/schema/index.mjs +1 -1
- package/dist/schema-CjON86AZ.mjs +2 -0
- package/dist/schema-CjON86AZ.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-BQEFiS_2.d.mts} +4 -4
- package/dist/scope-BQEFiS_2.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-CWAIEH46.mjs → service-DHkeorS3.mjs} +2 -2
- package/dist/{service-CWAIEH46.mjs.map → service-DHkeorS3.mjs.map} +1 -1
- package/dist/{service-D8mr0wwg.d.mts → service-DIKUYHda.d.mts} +2 -2
- package/dist/{service-D8mr0wwg.d.mts.map → service-DIKUYHda.d.mts.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-NETIRDfA.d.mts +375 -0
- package/dist/trace-NETIRDfA.d.mts.map +1 -0
- package/dist/type-utils.types-CnPpsvt5.d.mts +30 -0
- package/dist/type-utils.types-CnPpsvt5.d.mts.map +1 -0
- package/package.json +15 -5
- package/dist/adt/index.d.mts +0 -2
- package/dist/adt/index.mjs +0 -1
- package/dist/adt-CY8wLJJI.mjs +0 -2
- package/dist/adt-CY8wLJJI.mjs.map +0 -1
- package/dist/data-DqACNS_g.mjs +0 -2
- package/dist/data-DqACNS_g.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/functions-ByAk682_.mjs +0 -2
- package/dist/fx-C_RTDEpv.mjs +0 -2
- package/dist/fx-C_RTDEpv.mjs.map +0 -1
- package/dist/fx.runtime-jQxh77s3.mjs +0 -2
- package/dist/fx.runtime-jQxh77s3.mjs.map +0 -1
- package/dist/index-BD-els5J.d.mts.map +0 -1
- package/dist/index-BaRJVkLo.d.mts +0 -458
- package/dist/index-BaRJVkLo.d.mts.map +0 -1
- package/dist/index-BipW0MC3.d.mts +0 -64
- package/dist/index-BipW0MC3.d.mts.map +0 -1
- package/dist/index-BqJ1GWAF.d.mts.map +0 -1
- package/dist/index-CNTYbcY9.d.mts.map +0 -1
- package/dist/index-D6pjHqlK.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/is-plain-object-BoFjRafL.mjs +0 -2
- package/dist/is-plain-object-BoFjRafL.mjs.map +0 -1
- package/dist/layer-C5A-EM0h.mjs +0 -2
- package/dist/layer-C5A-EM0h.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/predicate-D_1SsIi4.mjs +0 -2
- package/dist/predicate-D_1SsIi4.mjs.map +0 -1
- package/dist/provide-CuccogWx.mjs +0 -2
- package/dist/provide-CuccogWx.mjs.map +0 -1
- package/dist/result.types-BKzChyWY.d.mts.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-w1WK4kGS.d.mts +0 -62
- package/dist/schema.types-w1WK4kGS.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
package/dist/schema/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../schema-
|
|
1
|
+
import{t as e}from"../schema-CjON86AZ.mjs";export{e as Schema};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./dual-CZhzZslG.mjs";import{n}from"./flow-D8_tllWl.mjs";import{t as r}from"./pipeable-COGyGMUV.mjs";import{i,t as a}from"./result-C74pRN2x.mjs";import{a as o,i as s,o as c,r as l,s as u,t as d}from"./data-W10ldR5l.mjs";function f(e){return typeof e==`object`&&e&&`key`in e?e.key:e}function p(e){return e.map(e=>({message:e.message,path:e.path?.map(f)}))}function m(e){return e.issues?a({issues:p(e.issues)}):i(e.value)}function h(e){return e instanceof Error&&e.message.length>0?e.message:typeof e==`string`&&e.length>0?e:`Schema validation failed.`}function g(e){return{issues:[{message:h(e)}]}}function _(e,t,r){let i;try{i=e[`~standard`].validate(t)}catch(e){return a(g(e))}if(n(i))throw Promise.resolve(i).catch(()=>void 0),TypeError(`Async validation is not supported in ${r}.`);return m(i)}var v=class extends d(`CodecDecodeError`){},y=class extends d(`CodecDecodeValidationError`){},b=class extends d(`CodecEncodeValidationError`){},x=class extends d(`CodecEncodeError`){};const S={"~standard":{version:1,vendor:`@nicolastoulemont/std`,validate(e){return typeof e==`string`?{value:e}:{issues:[{message:`Expected string`}]}}}};function C(e){return t=>new y({side:e,error:t})}function w(e){return t=>new b({side:e,error:t})}function T(e,t=`Codec decode failed`){return e instanceof v?e:new v({message:t,cause:e})}function E(e,t=`Codec encode failed`){return e instanceof x?e:new x({message:t,cause:e})}function D(e,t){return e._tag===`Err`?a(t(e.error)):i(e.value)}function O(e,t){if(t._tag===`Err`)return a(C(`encoded`)(t.error));let r;try{r=e.decode(t.value)}catch(e){return a(T(e))}return n(r)?Promise.resolve(r).then(t=>D(_(e.decoded,t,`Schema.codec.decode(decoded)`),C(`decoded`)),e=>a(T(e))):D(_(e.decoded,r,`Schema.codec.decode(decoded)`),C(`decoded`))}function k(e,t){if(t._tag===`Err`)return a(w(`decoded`)(t.error));let r;try{r=e.encode(t.value)}catch(e){return a(E(e))}return n(r)?Promise.resolve(r).then(t=>D(_(e.encoded,t,`Schema.codec.encode(encoded)`),w(`encoded`)),e=>a(E(e))):D(_(e.encoded,r,`Schema.codec.encode(encoded)`),w(`encoded`))}function A(e){let t={decoded:e.decoded,encoded:e.encoded,decode(t){return O(e,_(e.encoded,t,`Schema.codec.decode(encoded)`))},encode(t){return k(e,_(e.decoded,t,`Schema.codec.encode(decoded)`))},pipe:r};return Object.freeze(t)}function j(e,t={}){return A({decoded:e,encoded:S,decode(e){try{return JSON.parse(e)}catch(e){throw T(e,`JSON parse failed`)}},encode(e){try{return JSON.stringify(e,t.replacer,t.space)}catch(e){throw E(e,`JSON stringify failed`)}}})}const M=Object.assign(A,{json:j});function N(e){return typeof e!=`object`||!e?!1:Object.getPrototypeOf(e)===null||Object.getPrototypeOf(e)===Object.prototype}function P(e){return t=>{let n=_(e,t,`Schema.struct()`);return n._tag===`Err`?a(n.error):N(n.value)?i(l(n.value)):a({issues:[{message:`Schema.struct() requires schemas with plain object outputs.`}]})}}function F(e){return typeof e==`function`&&`_variant`in e&&e._variant===!0}function I(e,t,n){return _(e,t,`ADT variant "${n}"`)}function L(e){return t=>N(t)&&`_tag`in t&&t._tag===e}function R(e){let t=new Set(e);return e=>N(e)&&`_tag`in e&&typeof e._tag==`string`&&t.has(e._tag)}function z(e,t){let n=L(e),r=c(e),o=u(e),s=n=>{let r=I(t,{...n,_tag:e},e);return r._tag===`Err`?a(r.error):i({...r.value,_tag:e})};return s._variant=!0,s._tag=e,s.schema=t,s.is=n,s.equals=r,s.hash=o,s}function B(e,t){let n=Object.keys(t),r={};for(let[e,n]of Object.entries(t))F(n)?n._tag===e?r[e]=n:r[e]=z(e,n.schema):r[e]=z(e,n);return{_name:e,is:R(n),equals:s(n),hash:o(n),...r}}var V=e({Codec:()=>H,codec:()=>K,is:()=>Z,parse:()=>q,refine:()=>Y,struct:()=>U,tagged:()=>W,union:()=>G});let H;(function(e){e.DecodeError=v,e.DecodeValidationError=y,e.EncodeValidationError=b,e.EncodeError=x})(H||={});const U=P,W=z,G=B,K=M;function q(e){return t=>_(e,t,`Schema.parse()`)}const J=t(2,(e,t)=>_(t,e,`Schema.refine()`)._tag===`Ok`);function Y(...e){return J(...e)}const X=t(2,(e,t)=>_(t,e,`Schema.is()`)._tag===`Ok`);function Z(...e){return X(...e)}export{V as t};
|
|
2
|
+
//# sourceMappingURL=schema-CjON86AZ.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"schema-CjON86AZ.mjs","names":["Result.err","Result.ok","validateSync","Data.TaggedError","validateSync","codec","struct","validateSync","dataStruct","validateSchemaSync","tagged","union","tagged","structImpl","taggedImpl","unionImpl","codecImpl","validateSync"],"sources":["../src/schema/schema.shared.ts","../src/schema/schema.codec.ts","../src/shared/is-plain-object.ts","../src/schema/schema.struct.ts","../src/schema/schema.tagged-utils.ts","../src/schema/schema.tagged.ts","../src/schema/schema.union.ts","../src/schema/schema.ts"],"sourcesContent":["import { Result } from \"../result\"\nimport type { Result as ResultType } from \"../result/result.types\"\nimport { isPromise } from \"../shared/is-promise\"\nimport type { ValidationError, ValidationIssue } from \"./schema.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\nfunction normalizePathSegment(segment: PropertyKey | { readonly key: PropertyKey }): PropertyKey {\n return typeof segment === \"object\" && segment !== null && \"key\" in segment ? segment.key : segment\n}\n\nfunction normalizeIssues(\n issues: NonNullable<StandardSchemaV1.Result<unknown>[\"issues\"]>,\n): ReadonlyArray<ValidationIssue> {\n return issues.map((issue) => ({\n message: issue.message,\n path: issue.path?.map(normalizePathSegment),\n }))\n}\n\nfunction toValidationResult<T>(result: StandardSchemaV1.Result<T>): ResultType<T, ValidationError> {\n if (result.issues) {\n return Result.err({ issues: normalizeIssues(result.issues) })\n }\n\n return Result.ok(result.value)\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.length > 0) {\n return error.message\n }\n\n if (typeof error === \"string\" && error.length > 0) {\n return error\n }\n\n return \"Schema validation failed.\"\n}\n\nfunction toThrownValidationError(error: unknown): ValidationError {\n return {\n issues: [{ message: toErrorMessage(error) }],\n }\n}\n\nexport function validateSync<T>(\n schema: StandardSchemaV1<unknown, T>,\n value: unknown,\n operation: string,\n): ResultType<T, ValidationError> {\n let result: StandardSchemaV1.Result<T> | Promise<StandardSchemaV1.Result<T>>\n\n try {\n result = schema[\"~standard\"].validate(value)\n } catch (error) {\n return Result.err(toThrownValidationError(error))\n }\n\n if (isPromise(result)) {\n void Promise.resolve(result).catch(() => undefined)\n throw new TypeError(`Async validation is not supported in ${operation}.`)\n }\n\n return toValidationResult(result)\n}\n","import { Data } from \"../data\"\nimport { err, ok } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport { isPromise } from \"../shared/is-promise\"\nimport { pipeable } from \"../shared/pipeable\"\nimport type { Pipeable } from \"../shared/pipeable\"\nimport { validateSync } from \"./schema.shared\"\nimport type { Input, Output, SyncSchema, ValidationError } from \"./schema.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\nexport class CodecDecodeError extends Data.TaggedError(\"CodecDecodeError\")<{\n readonly message: string\n readonly cause?: unknown\n}> {}\n\nexport class CodecDecodeValidationError extends Data.TaggedError(\"CodecDecodeValidationError\")<{\n readonly side: \"encoded\" | \"decoded\"\n readonly error: ValidationError\n}> {}\n\nexport class CodecEncodeValidationError extends Data.TaggedError(\"CodecEncodeValidationError\")<{\n readonly side: \"decoded\" | \"encoded\"\n readonly error: ValidationError\n}> {}\n\nexport class CodecEncodeError extends Data.TaggedError(\"CodecEncodeError\")<{\n readonly message: string\n readonly cause?: unknown\n}> {}\n\nexport type CodecError = CodecDecodeError | CodecDecodeValidationError | CodecEncodeValidationError | CodecEncodeError\n\ntype MaybePromise<T> = T | Promise<T>\n\ntype IsNever<T> = [T] extends [never] ? true : false\n\ntype TransformIsAsync<TransformReturn> =\n IsNever<TransformReturn> extends true ? false : TransformReturn extends Promise<unknown> ? true : false\n\ntype CodecMethodResult<T, IsAsync extends boolean> = IsAsync extends true\n ? Promise<Result<T, CodecError>>\n : Result<T, CodecError>\n\nexport type Codec<\n Decoded extends StandardSchemaV1 = StandardSchemaV1,\n Encoded extends StandardSchemaV1 = StandardSchemaV1,\n DecodeReturn = Input<Decoded>,\n EncodeReturn = Input<Encoded>,\n> = Pipeable & {\n readonly decoded: Decoded\n readonly encoded: Encoded\n decode(input: Input<Encoded>): CodecMethodResult<Output<Decoded>, TransformIsAsync<DecodeReturn>>\n encode(value: Output<Decoded>): CodecMethodResult<Output<Encoded>, TransformIsAsync<EncodeReturn>>\n}\n\nexport type Decoded<C> = C extends { readonly decoded: infer DecodedSchema extends StandardSchemaV1 }\n ? Output<DecodedSchema>\n : never\n\nexport type Encoded<C> = C extends { readonly encoded: infer EncodedSchema extends StandardSchemaV1 }\n ? Output<EncodedSchema>\n : never\n\nexport type DecodeInput<C> = C extends { decode(input: infer I): unknown } ? I : never\n\nexport type EncodeInput<C> = C extends { encode(input: infer I): unknown } ? I : never\n\nexport type CodecOptions<\n Decoded extends StandardSchemaV1,\n Encoded extends StandardSchemaV1,\n DecodeReturn extends MaybePromise<Input<Decoded>>,\n EncodeReturn extends MaybePromise<Input<Encoded>>,\n> = {\n readonly decoded: Decoded\n readonly encoded: Encoded\n readonly decode: (encoded: Output<Encoded>) => DecodeReturn\n readonly encode: (decoded: Output<Decoded>) => EncodeReturn\n}\n\nexport type JsonCodecOptions = {\n readonly replacer?: Parameters<typeof JSON.stringify>[1]\n readonly space?: Parameters<typeof JSON.stringify>[2]\n}\n\nconst stringSchema: SyncSchema<string, string> = {\n \"~standard\": {\n version: 1,\n vendor: \"@nicolastoulemont/std\",\n validate(value: unknown) {\n if (typeof value === \"string\") {\n return { value }\n }\n\n return { issues: [{ message: \"Expected string\" }] }\n },\n },\n}\n\nfunction mapDecodeValidationError(side: \"encoded\" | \"decoded\") {\n return (error: ValidationError): CodecDecodeValidationError => new CodecDecodeValidationError({ side, error })\n}\n\nfunction mapEncodeValidationError(side: \"decoded\" | \"encoded\") {\n return (error: ValidationError): CodecEncodeValidationError => new CodecEncodeValidationError({ side, error })\n}\n\nfunction normalizeDecodeCause(cause: unknown, message = \"Codec decode failed\"): CodecDecodeError {\n if (cause instanceof CodecDecodeError) {\n return cause\n }\n\n return new CodecDecodeError({ message, cause })\n}\n\nfunction normalizeEncodeCause(cause: unknown, message = \"Codec encode failed\"): CodecEncodeError {\n if (cause instanceof CodecEncodeError) {\n return cause\n }\n\n return new CodecEncodeError({ message, cause })\n}\n\nfunction mapValidation<T, E extends CodecError>(\n result: Result<T, ValidationError>,\n mapError: (error: ValidationError) => E,\n): Result<T, E> {\n if (result._tag === \"Err\") {\n return err(mapError(result.error))\n }\n\n return ok(result.value)\n}\n\nfunction continueDecode<\n Decoded extends StandardSchemaV1,\n Encoded extends StandardSchemaV1,\n DecodeReturn extends MaybePromise<Input<Decoded>>,\n EncodeReturn extends MaybePromise<Input<Encoded>>,\n>(\n options: CodecOptions<Decoded, Encoded, DecodeReturn, EncodeReturn>,\n encodedResult: Result<Output<Encoded>, ValidationError>,\n): Result<Output<Decoded>, CodecError> | Promise<Result<Output<Decoded>, CodecError>> {\n if (encodedResult._tag === \"Err\") {\n return err(mapDecodeValidationError(\"encoded\")(encodedResult.error))\n }\n\n let decodedInput: DecodeReturn\n\n try {\n decodedInput = options.decode(encodedResult.value)\n } catch (cause) {\n return err(normalizeDecodeCause(cause))\n }\n\n if (isPromise(decodedInput)) {\n return Promise.resolve(decodedInput).then(\n (value) =>\n mapValidation(\n validateSync(options.decoded, value, \"Schema.codec.decode(decoded)\"),\n mapDecodeValidationError(\"decoded\"),\n ),\n (cause) => err(normalizeDecodeCause(cause)),\n )\n }\n\n return mapValidation(\n validateSync(options.decoded, decodedInput, \"Schema.codec.decode(decoded)\"),\n mapDecodeValidationError(\"decoded\"),\n )\n}\n\nfunction continueEncode<\n Decoded extends StandardSchemaV1,\n Encoded extends StandardSchemaV1,\n DecodeReturn extends MaybePromise<Input<Decoded>>,\n EncodeReturn extends MaybePromise<Input<Encoded>>,\n>(\n options: CodecOptions<Decoded, Encoded, DecodeReturn, EncodeReturn>,\n decodedResult: Result<Output<Decoded>, ValidationError>,\n): Result<Output<Encoded>, CodecError> | Promise<Result<Output<Encoded>, CodecError>> {\n if (decodedResult._tag === \"Err\") {\n return err(mapEncodeValidationError(\"decoded\")(decodedResult.error))\n }\n\n let encodedInput: EncodeReturn\n\n try {\n encodedInput = options.encode(decodedResult.value)\n } catch (cause) {\n return err(normalizeEncodeCause(cause))\n }\n\n if (isPromise(encodedInput)) {\n return Promise.resolve(encodedInput).then(\n (value) =>\n mapValidation(\n validateSync(options.encoded, value, \"Schema.codec.encode(encoded)\"),\n mapEncodeValidationError(\"encoded\"),\n ),\n (cause) => err(normalizeEncodeCause(cause)),\n )\n }\n\n return mapValidation(\n validateSync(options.encoded, encodedInput, \"Schema.codec.encode(encoded)\"),\n mapEncodeValidationError(\"encoded\"),\n )\n}\n\n/**\n * Create a first-class bidirectional schema codec.\n *\n * Pipeline:\n * - decode: encoded input -> encoded validation -> decode transform -> decoded validation -> decoded output\n * - encode: decoded value -> decoded validation -> encode transform -> encoded validation -> encoded output\n */\nfunction makeCodec<\n Decoded extends StandardSchemaV1,\n Encoded extends StandardSchemaV1,\n DecodeReturn extends MaybePromise<Input<Decoded>>,\n EncodeReturn extends MaybePromise<Input<Encoded>>,\n>(\n options: CodecOptions<Decoded, Encoded, DecodeReturn, EncodeReturn>,\n): Codec<Decoded, Encoded, DecodeReturn, EncodeReturn> {\n const codec: Codec<Decoded, Encoded, DecodeReturn, EncodeReturn> = {\n decoded: options.decoded,\n encoded: options.encoded,\n decode(input) {\n const encodedResult = validateSync(options.encoded, input, \"Schema.codec.decode(encoded)\")\n\n return continueDecode(options, encodedResult) as ReturnType<\n Codec<Decoded, Encoded, DecodeReturn, EncodeReturn>[\"decode\"]\n >\n },\n encode(value) {\n const decodedResult = validateSync(options.decoded, value, \"Schema.codec.encode(decoded)\")\n\n return continueEncode(options, decodedResult) as ReturnType<\n Codec<Decoded, Encoded, DecodeReturn, EncodeReturn>[\"encode\"]\n >\n },\n pipe: pipeable,\n }\n\n return Object.freeze(codec)\n}\n\nfunction jsonCodec<S extends StandardSchemaV1>(schema: S, options: JsonCodecOptions = {}) {\n return makeCodec({\n decoded: schema,\n encoded: stringSchema,\n decode(input: string): Input<S> {\n try {\n return JSON.parse(input) as Input<S>\n } catch (cause) {\n throw normalizeDecodeCause(cause, \"JSON parse failed\")\n }\n },\n encode(value: Output<S>) {\n try {\n return JSON.stringify(value, options.replacer, options.space)\n } catch (cause) {\n throw normalizeEncodeCause(cause, \"JSON stringify failed\")\n }\n },\n })\n}\n\nexport type CodecConstructor = {\n <\n Decoded extends StandardSchemaV1,\n Encoded extends StandardSchemaV1,\n DecodeReturn extends MaybePromise<Input<Decoded>>,\n EncodeReturn extends MaybePromise<Input<Encoded>>,\n >(\n options: CodecOptions<Decoded, Encoded, DecodeReturn, EncodeReturn>,\n ): Codec<Decoded, Encoded, DecodeReturn, EncodeReturn>\n json<S extends StandardSchemaV1>(schema: S, options?: JsonCodecOptions): ReturnType<typeof jsonCodec<S>>\n}\n\nexport const codec = Object.assign(makeCodec, {\n json: jsonCodec,\n}) as CodecConstructor\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 { struct as dataStruct } from \"../data/data.struct\"\nimport type { StructValue } from \"../data/data.types\"\nimport { err, ok } from \"../result/result\"\nimport type { Result } from \"../result/result.types\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport { validateSync } from \"./schema.shared\"\nimport type { Input, Output, SyncSchema, ValidationError } from \"./schema.types\"\n\ntype StructSchema<TInput = unknown, TOutput extends Record<string, unknown> = Record<string, unknown>> = SyncSchema<\n TInput,\n TOutput\n>\n\ntype StructConstructor<S extends StructSchema> = (input: Input<S>) => Result<StructValue<Output<S>>, ValidationError>\n\n/**\n * Create a sync schema-backed constructor for struct objects.\n *\n * The constructor validates through the provided schema, then wraps the\n * validated object with `Data.struct()` so the result is frozen and gains\n * structural `equals()` and `hash()` behavior.\n */\nexport function struct<S extends StructSchema>(schema: S): StructConstructor<S> {\n return (input: Input<S>) => {\n const result = validateSync(schema, input, \"Schema.struct()\")\n\n if (result._tag === \"Err\") {\n return err(result.error)\n }\n\n if (!isPlainObject(result.value)) {\n return err({\n issues: [{ message: \"Schema.struct() requires schemas with plain object outputs.\" }],\n })\n }\n\n return ok(dataStruct(result.value))\n }\n}\n","import { validateSync as validateSchemaSync } from \"../schema/schema.shared\"\nimport { isPlainObject } from \"../shared/is-plain-object\"\nimport type { TaggedSchema } from \"./schema.union.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Check if a value is an TaggedSchema created by tagged().\n * TaggedSchemas are callable functions with static properties.\n */\nexport function isVariant(value: unknown): value is TaggedSchema {\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 (SchemaUnion 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 { 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 { createIsGuard, validateSync } from \"./schema.tagged-utils\"\nimport type { TaggedSchemaInput, TaggedSchemaOutput, TaggedSchema } from \"./schema.union.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Create a standalone tagged variant from a Standard Schema.\n *\n * Variants can be used independently or composed into an SchemaUnion 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 * @param _tag - The _tag discriminator value\n * @param schema - A Standard Schema compliant validator\n * @returns A callable TaggedSchema with is(), equals(), and hash() 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 * const Circle = tagged('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 */\nexport function tagged<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): TaggedSchema<Tag, S>\n\n// Implementation\nexport function tagged<Tag extends string, S extends StandardSchemaV1>(_tag: Tag, schema: S): TaggedSchema<Tag, S> {\n type Output = TaggedSchemaOutput<S> & Discriminator<Tag>\n\n const isGuard = createIsGuard<Tag, Output>(_tag)\n const equals = createEqualsMethod<Tag, TaggedSchemaOutput<S>>(_tag)\n const hash = createHashMethod<Tag, TaggedSchemaOutput<S>>(_tag)\n\n // Constructor function\n const constructor = (input: TaggedSchemaInput<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 constructor.is = isGuard\n constructor.equals = equals\n constructor.hash = hash\n\n return constructor as TaggedSchema<Tag, S>\n}\n","import { createADTEqualsMethod, createADTHashMethod } from \"../equality/equality\"\nimport { tagged } from \"./schema.tagged\"\nimport { createIsAnyGuard, isVariant } from \"./schema.tagged-utils\"\nimport type { SchemaUnion, TaggedSchemaDef, TaggedSchema } from \"./schema.union.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\n/**\n * Compose records or schemas into a discriminated union (SchemaUnion).\n *\n * Accepts either:\n * - Pre-built TaggedSchemas from tagged()\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 TaggedSchemas or StandardSchema validators\n * @param name - The name of this SchemaUnion (for identification)\n * @param records - An object mapping _tag names to TaggedSchemas or schemas\n * @returns An SchemaUnion 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 SchemaUnion values\n *\n * @example\n * ```ts\n * // From pre-built variants\n * const Circle = tagged('Circle', CircleSchema)\n * const Square = tagged('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 * // 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, TaggedSchemaDef>>(name: string, records: R): SchemaUnion<R> {\n const tags = Object.keys(records)\n const variants: Record<string, TaggedSchema> = {}\n\n for (const [_tag, def] of Object.entries(records)) {\n if (isVariant(def)) {\n // Pre-built TaggedSchema - key overrides original _tag\n if (def._tag === _tag) {\n // _tag matches key, use as-is\n variants[_tag] = def\n } else {\n // _tag differs from key - create new variant with key as _tag\n variants[_tag] = tagged(_tag, def.schema)\n }\n } else {\n // Raw schema - wrap in variant\n // oxlint-disable-next-line no-unsafe-type-assertion -- def is a StandardSchemaV1 in this branch\n variants[_tag] = tagged(_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 SchemaUnion return type\n return {\n _name: name,\n is: isAnyVariant,\n equals,\n hash,\n ...variants,\n } as SchemaUnion<R>\n}\n","import type { Result as ResultType } from \"../result/result.types\"\n/**\n * Standard Schema-backed parsing and refinement helpers.\n *\n * **Mental model**\n * - `Schema.parse` is for boundary validation and parsing.\n * - `Schema.codec` is for bidirectional boundary encoding/decoding.\n * - Schema validation is sync-only across the module.\n * - `Schema.is` is a proof guard for direct in-memory checks.\n * - `Schema.refine` is the reusable preserved-shape guard for higher-order APIs like `Array.filter`.\n *\n * **Common tasks**\n * - Parse loose external data into validated subtypes.\n * - Build first-class codecs with validated encoded and decoded sides.\n * - Use `Schema.is` for direct control-flow checks against already-typed values.\n * - Reuse a schema as a preserved-shape predicate with `Schema.refine`.\n * - Name reusable narrowed types with `Schema.Refine<Base, typeof schema>` or exact schema outputs with `Schema.Infer<typeof schema>`.\n *\n * **Gotchas**\n * - `Schema.parse` is sync-only and throws if schema validation returns a Promise.\n * - `Schema.refine` and `Schema.is` support both data-first and data-last styles.\n * - `Schema.refine` and `Schema.is` are sync-only.\n * - `Schema.is` and `Schema.refine` must only be used with proof schemas that validate the current value in place.\n * - Transforms, defaults, coercions, and other output-changing schemas should use `Schema.parse`.\n * - `Schema.is` narrows `unknown` to the exact schema output, but in direct control flow TypeScript preserves the current value shape.\n * - `Schema.refine` exists for the cases where you need that preserved shape to survive higher-order APIs like `Array.filter`.\n *\n * @module\n */\nimport { dual } from \"../shared/dual\"\nimport {\n CodecDecodeError,\n CodecDecodeValidationError,\n CodecEncodeError,\n CodecEncodeValidationError,\n codec as codecImpl,\n} from \"./schema.codec\"\nimport type {\n Codec as CodecType,\n CodecConstructor as CodecConstructorType,\n CodecError as CodecErrorType,\n CodecOptions as CodecOptionsType,\n Decoded as CodecDecoded,\n DecodeInput as CodecDecodeInput,\n Encoded as CodecEncoded,\n EncodeInput as CodecEncodeInput,\n JsonCodecOptions as CodecJsonOptions,\n} from \"./schema.codec\"\nimport { validateSync } from \"./schema.shared\"\nimport { struct as structImpl } from \"./schema.struct\"\nimport { tagged as taggedImpl } from \"./schema.tagged\"\nimport type {\n Input,\n Output,\n Refine as Refined,\n SyncRefinementSchema,\n SyncSchema,\n ValidationError,\n} from \"./schema.types\"\nimport { union as unionImpl } from \"./schema.union\"\nimport type {\n UnionInfer as UnionInferType,\n UnionVariantNames as UnionVariantNamesType,\n UnionVariantOf as UnionVariantOfType,\n} from \"./schema.union.types\"\nimport type { StandardSchemaV1 } from \"@standard-schema/spec\"\n\nexport type {\n Infer,\n Input,\n Output,\n Refine,\n RefinementSchema,\n SyncRefinementSchema,\n SyncSchema,\n ValidationError,\n ValidationIssue,\n} from \"./schema.types\"\n\nexport type {\n SchemaUnion,\n TaggedSchema,\n TaggedSchemaDef,\n TaggedSchemaInput,\n TaggedSchemaOutput,\n} from \"./schema.union.types\"\nexport type { StructValue } from \"../data/data.types\"\n\nexport declare namespace Union {\n export type Infer<T> = UnionInferType<T>\n export type VariantNames<T> = UnionVariantNamesType<T>\n export type VariantOf<T, K extends string> = UnionVariantOfType<T, K>\n}\n\nexport namespace Codec {\n export const DecodeError = CodecDecodeError\n export const DecodeValidationError = CodecDecodeValidationError\n export const EncodeValidationError = CodecEncodeValidationError\n export const EncodeError = CodecEncodeError\n\n export type Codec<\n DecodedSchema extends StandardSchemaV1 = StandardSchemaV1,\n EncodedSchema extends StandardSchemaV1 = StandardSchemaV1,\n DecodeReturn extends Input<DecodedSchema> | Promise<Input<DecodedSchema>> = Input<DecodedSchema>,\n EncodeReturn extends Input<EncodedSchema> | Promise<Input<EncodedSchema>> = Input<EncodedSchema>,\n > = CodecType<DecodedSchema, EncodedSchema, DecodeReturn, EncodeReturn>\n\n export type Decoded<C> = CodecDecoded<C>\n export type Encoded<C> = CodecEncoded<C>\n export type DecodeInput<C> = CodecDecodeInput<C>\n export type EncodeInput<C> = CodecEncodeInput<C>\n export type Error = CodecErrorType\n export type Options<\n DecodedSchema extends StandardSchemaV1,\n EncodedSchema extends StandardSchemaV1,\n DecodeReturn extends Input<DecodedSchema> | Promise<Input<DecodedSchema>>,\n EncodeReturn extends Input<EncodedSchema> | Promise<Input<EncodedSchema>>,\n > = CodecOptionsType<DecodedSchema, EncodedSchema, DecodeReturn, EncodeReturn>\n export type JsonOptions = CodecJsonOptions\n export type Constructor = CodecConstructorType\n}\n\n/**\n * Construct sync schema-backed structs with structural value semantics.\n */\nexport const struct = structImpl\n\n/**\n * Construct schema-backed tagged values.\n */\nexport const tagged = taggedImpl\n\n/**\n * Compose schema-backed tagged values into a discriminated union.\n */\nexport const union = unionImpl\n\n/**\n * Construct first-class bidirectional schema codecs.\n */\nexport const codec = codecImpl\n\n/**\n * Create a schema-backed parser.\n *\n * Schema validation is sync-only. Provider schemas are accepted directly even\n * when their Standard Schema type allows async validation; a Promise result\n * throws at runtime.\n */\nexport function parse<S extends StandardSchemaV1>(\n schema: S,\n): (value: Input<S>) => ResultType<Output<S>, ValidationError>\nexport function parse<S extends StandardSchemaV1>(schema: S) {\n return (value: Input<S>) => {\n return validateSync(schema, value, \"Schema.parse()\")\n }\n}\n\nexport type RefineFn = {\n <S extends SyncSchema, Base extends Input<S>>(value: Base, schema: S): value is Refined<Base, S>\n <S extends SyncSchema>(schema: S): <Base extends Input<S>>(value: Base) => value is Refined<Base, S>\n}\n\nexport type Is = {\n <Base, Sub extends Base>(value: Base, schema: SyncRefinementSchema<Base, Sub>): value is Sub\n <S extends SyncSchema>(value: unknown, schema: S): value is Output<S>\n <Base, Sub extends Base>(schema: SyncRefinementSchema<Base, Sub>): (value: Base) => value is Sub\n <S extends SyncSchema>(schema: S): (value: unknown) => value is Output<S>\n}\n\n/* oxlint-disable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion -- dual() requires a single implementation signature */\nconst refineImpl = dual(2, (value: unknown, schema: SyncSchema) => {\n return validateSync(schema, value, \"Schema.refine()\")._tag === \"Ok\"\n}) as RefineFn\n\n/**\n * Create a sync-only schema-backed reusable type guard that preserves the original value shape.\n *\n * Use this when a schema validates only a subset of a broader in-memory value\n * and you need the preserved shape to survive higher-order APIs like\n * `Array.filter`. The narrowed type is `Base & Output<typeof schema>`, not the\n * exact schema output.\n *\n * Supports both data-first and data-last styles:\n * - Data-first: `Schema.refine(value, schema)`\n * - Data-last: `Schema.refine(schema)(value)`\n *\n * Only use this with sync proof schemas that validate properties already\n * present on the original value. Transforms, defaults, and coercions are not\n * safe here because they can change the schema output without changing the\n * original input value.\n */\nexport function refine<S extends SyncSchema, Base extends Input<S>>(value: Base, schema: S): value is Refined<Base, S>\nexport function refine<S extends SyncSchema>(\n schema: S,\n): <Base extends Input<S>>(value: Base) => value is Refined<Base, S>\nexport function refine(...args: [value: unknown, schema: SyncSchema] | [schema: SyncSchema]) {\n return (refineImpl as (...args: [unknown, SyncSchema] | [SyncSchema]) => boolean | ((value: unknown) => boolean))(\n ...args,\n )\n}\n\nconst isImpl = dual(2, (value: unknown, schema: SyncSchema) => {\n return validateSync(schema, value, \"Schema.is()\")._tag === \"Ok\"\n}) as Is\n\n/**\n * Create a sync-only schema-backed proof guard.\n *\n * On `unknown` values this narrows to the exact schema output. On already-typed\n * values, TypeScript preserves the current shape during direct control-flow\n * checks. Use `Schema.refine` when that preserved shape must survive\n * higher-order APIs like `Array.filter`.\n *\n * Supports both data-first and data-last styles:\n * - Data-first: `Schema.is(value, schema)`\n * - Data-last: `Schema.is(schema)(value)`\n */\nexport function is<Base, Sub extends Base>(value: Base, schema: SyncRefinementSchema<Base, Sub>): value is Sub\nexport function is<S extends SyncSchema>(value: unknown, schema: S): value is Output<S>\nexport function is<Base, Sub extends Base>(schema: SyncRefinementSchema<Base, Sub>): (value: Base) => value is Sub\nexport function is<S extends SyncSchema>(schema: S): (value: unknown) => value is Output<S>\nexport function is(...args: [value: unknown, schema: SyncSchema] | [schema: SyncSchema]) {\n return (isImpl as (...args: [unknown, SyncSchema] | [SyncSchema]) => boolean | ((value: unknown) => boolean))(...args)\n}\n/* oxlint-enable no-explicit-any, no-unsafe-return, no-unsafe-type-assertion */\n"],"mappings":"kRAMA,SAAS,EAAqB,EAAmE,CAC/F,OAAO,OAAO,GAAY,UAAY,GAAoB,QAAS,EAAU,EAAQ,IAAM,EAG7F,SAAS,EACP,EACgC,CAChC,OAAO,EAAO,IAAK,IAAW,CAC5B,QAAS,EAAM,QACf,KAAM,EAAM,MAAM,IAAI,EAAqB,CAC5C,EAAE,CAGL,SAAS,EAAsB,EAAoE,CAKjG,OAJI,EAAO,OACFA,EAAW,CAAE,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Aa,EAAQ,EAAO,iBAAiB,CAiBxD,MAAM,EAAa,EAAK,GAAI,EAAgB,IACnCA,EAAa,EAAQ,EAAO,kBAAkB,CAAC,OAAS,KAC/D,CAuBF,SAAgB,EAAO,GAAG,EAAmE,CAC3F,OAAQ,EACN,GAAG,EACJ,CAGH,MAAM,EAAS,EAAK,GAAI,EAAgB,IAC/BA,EAAa,EAAQ,EAAO,cAAc,CAAC,OAAS,KAC3D,CAkBF,SAAgB,EAAG,GAAG,EAAmE,CACvF,OAAQ,EAAsG,GAAG,EAAK"}
|
package/dist/scope/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { r as scope_d_exports } from "../scope-
|
|
1
|
+
import { r as scope_d_exports } from "../scope-BQEFiS_2.mjs";
|
|
2
2
|
export { scope_d_exports as Scope };
|
package/dist/scope/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{n as e}from"../scope-
|
|
1
|
+
import{n as e}from"../scope-D2AqJy7j.mjs";export{e as Scope};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { m as SyncFx, t as AsyncFx } from "./fx.types-
|
|
2
|
-
import { t as Result } from "./result.types-
|
|
1
|
+
import { m as SyncFx, t as AsyncFx } from "./fx.types-CpFKa-Jj.mjs";
|
|
2
|
+
import { t as Result } from "./result.types-JEcowzYH.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/scope/scope.d.ts
|
|
5
5
|
declare namespace scope_d_exports {
|
|
@@ -24,7 +24,7 @@ type ScopeService = {
|
|
|
24
24
|
* @param finalizer - A function that returns an Fx to run on cleanup
|
|
25
25
|
* @returns An Fx that completes when the finalizer is registered
|
|
26
26
|
*/
|
|
27
|
-
addFinalizer(finalizer: () => SyncFx<void> | AsyncFx<void>): SyncFx<void>;
|
|
27
|
+
addFinalizer(finalizer: () => SyncFx<void, never, unknown> | AsyncFx<void, never, unknown>): SyncFx<void>;
|
|
28
28
|
/**
|
|
29
29
|
* Close the scope, running all finalizers in LIFO order.
|
|
30
30
|
*
|
|
@@ -70,4 +70,4 @@ declare function make(): ScopeService;
|
|
|
70
70
|
type ExcludeScope<R> = Exclude<R, ScopeService>;
|
|
71
71
|
//#endregion
|
|
72
72
|
export { ScopeService as n, scope_d_exports as r, ExcludeScope as t };
|
|
73
|
-
//# sourceMappingURL=scope-
|
|
73
|
+
//# sourceMappingURL=scope-BQEFiS_2.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-BQEFiS_2.d.mts","names":[],"sources":["../src/scope/scope.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;;AAoDA;;;AAQ+F,KARnF,YAAA,GAQmF;EAQjF;;;;;AA0Bd;AAkHA;EAAsC,YAAA,CAAA,SAAA,EAAA,GAAA,GApJN,MAoJM,CAAA,IAAA,EAAA,KAAA,EAAA,OAAA,CAAA,GApJyB,OAoJzB,CAAA,IAAA,EAAA,KAAA,EAAA,OAAA,CAAA,CAAA,EApJyD,MAoJzD,CAAA,IAAA,CAAA;EAAG;;;;;;cA5I3B,2BAA2B,eAAe;;;;;;;UAQ9C;;;;;;;;;;;;;;;;;iBAkBM,IAAA,CAAA,GAAQ;;;;;;;;;;;;KAkHZ,kBAAkB,QAAQ,GAAG"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";var n=e({make:()=>r});function r(){let e=[],n=!1,i=[];return{addFinalizer(r){return{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){n||e.push(r)}}},close(r){return e.some(e=>e()._tag===`AsyncFx`)?{_tag:`AsyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},async*[Symbol.asyncIterator](){if(n)return;n=!0;for(let e of[...i].toReversed())yield*e.close(r);let t=[...e].toReversed();for(let e of t)yield*e()}}:{_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){if(n)return;n=!0;for(let e of[...i].toReversed())yield*e.close(r);let t=[...e].toReversed();for(let e of t)yield*e()}}},fork(){let e=r();return i.push(e),e}}}export{n,r as t};
|
|
2
|
+
//# sourceMappingURL=scope-D2AqJy7j.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"scope-D2AqJy7j.mjs","names":[],"sources":["../src/scope/scope.ts"],"sourcesContent":["/**\n * Scope lifecycle management for registering and running finalizers.\n *\n * **Mental model**\n * - A scope tracks cleanup actions and executes them in LIFO order.\n * - `Layer.scoped` and `Provide.layer` rely on scope semantics.\n *\n * **Common tasks**\n * - Create scopes with `Scope.make`.\n * - Register cleanup with `scope.addFinalizer`.\n * - Close scopes with `scope.close`.\n *\n * **Gotchas**\n * - Child scopes close before parent finalizers.\n * - Async finalizers force async scope close.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * import { Result } from \"@nicolastoulemont/std\"\n *\n * const scope = Scope.make()\n * const closeFx = scope.close(Result.ok(undefined))\n * // => SyncFx<void> | AsyncFx<void>\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { SyncFx, AsyncFx, FxYield } from \"../fx/fx.types\"\nimport type { Result } from \"../result/result.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Scope encodes Fx phantom type slots and sync/async branch narrowing via assertions. */\n\n// ============================================================================\n// Scope Service\n// ============================================================================\n\n/**\n * Scope manages resource lifecycles with finalizers.\n * Finalizers run in LIFO (Last In, First Out) order when the scope closes.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Scope\n * ```\n */\nexport type ScopeService = {\n /**\n * Add a finalizer to be run when the scope closes.\n * Finalizers are run in LIFO order.\n *\n * @param finalizer - A function that returns an Fx to run on cleanup\n * @returns An Fx that completes when the finalizer is registered\n */\n addFinalizer(finalizer: () => SyncFx<void, never, unknown> | AsyncFx<void, never, unknown>): SyncFx<void>\n\n /**\n * Close the scope, running all finalizers in LIFO order.\n *\n * @param exit - The exit status of the computation\n * @returns An Fx that completes when all finalizers have run\n */\n close(exit: Result<unknown, unknown>): SyncFx<void> | AsyncFx<void>\n\n /**\n * Fork a child scope.\n * The child scope will be closed when the parent scope closes.\n *\n * @returns A new child scope\n */\n fork(): ScopeService\n}\n\n/**\n * Create a new Scope instance.\n * This is the concrete implementation of the ScopeService interface.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * import { Result } from \"@nicolastoulemont/std\"\n *\n * const scope = Scope.make()\n * const closeFx = scope.close(Result.ok(undefined))\n * // => SyncFx<void> | AsyncFx<void>\n * ```\n */\nexport function make(): ScopeService {\n type Finalizer = () => SyncFx<void, never, unknown> | AsyncFx<void, never, unknown>\n const finalizers: Finalizer[] = []\n let closed = false\n const children: ScopeService[] = []\n\n const scope: ScopeService = {\n addFinalizer(finalizer: Finalizer): SyncFx<void> {\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<FxYield<never, never>, void, unknown> {\n if (!closed) {\n finalizers.push(finalizer)\n }\n },\n } as SyncFx<void>\n },\n\n close(exit: Result<unknown, unknown>): SyncFx<void> | AsyncFx<void> {\n // Check if any finalizer is async\n const hasAsyncFinalizer = finalizers.some((f) => {\n const fx = f()\n return fx._tag === \"AsyncFx\"\n })\n\n if (hasAsyncFinalizer) {\n return {\n _tag: \"AsyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n async *[Symbol.asyncIterator](): AsyncGenerator<FxYield<never, never>, void, unknown> {\n if (closed) return\n closed = true\n\n // Close children first\n for (const child of [...children].toReversed()) {\n const childClose = child.close(exit)\n yield* childClose\n }\n\n // Run finalizers in LIFO order\n const reversed = [...finalizers].toReversed()\n for (const finalizer of reversed) {\n const fx = finalizer()\n yield* fx as SyncFx<void> | AsyncFx<void>\n }\n },\n } as AsyncFx<void>\n }\n\n // Sync version\n return {\n _tag: \"SyncFx\",\n [FxTypeId]: {\n _A: () => undefined as void,\n _E: () => undefined as never,\n _R: () => undefined as never,\n },\n // oxlint-disable-next-line require-yield\n *[Symbol.iterator](): Generator<FxYield<never, never>, void, unknown> {\n if (closed) return\n closed = true\n\n // Close children first\n for (const child of [...children].toReversed()) {\n const childClose = child.close(exit)\n yield* childClose as SyncFx<void>\n }\n\n // Run finalizers in LIFO order\n const reversed = [...finalizers].toReversed()\n for (const finalizer of reversed) {\n const fx = finalizer()\n yield* fx as SyncFx<void>\n }\n },\n } as SyncFx<void>\n },\n\n fork(): ScopeService {\n const child = make()\n children.push(child)\n return child\n },\n }\n\n return scope\n}\n\n// ============================================================================\n// Helper Types\n// ============================================================================\n\n/**\n * Type utility to exclude Scope from requirements.\n * Used by Layer.scoped to auto-provide Scope.\n *\n * @example\n * ```ts\n * import { Scope } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Scope\n * ```\n */\nexport type ExcludeScope<R> = Exclude<R, ScopeService>\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"sGA8FA,SAAgB,GAAqB,CAEnC,IAAM,EAA0B,EAAE,CAC9B,EAAS,GACP,EAA2B,EAAE,CA4FnC,MA1F4B,CAC1B,aAAa,EAAoC,CAC/C,MAAO,CACL,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,EAAE,OAAO,WAA6D,CAC/D,GACH,EAAW,KAAK,EAAU,EAG/B,EAGH,MAAM,EAA8D,CAqClE,OAnC0B,EAAW,KAAM,GAC9B,GAAG,CACJ,OAAS,UACnB,CAGO,CACL,KAAM,WACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,OAAQ,OAAO,gBAAuE,CACpF,GAAI,EAAQ,OACZ,EAAS,GAGT,IAAK,IAAM,IAAS,CAAC,GAAG,EAAS,CAAC,YAAY,CAE5C,MADmB,EAAM,MAAM,EAAK,CAKtC,IAAM,EAAW,CAAC,GAAG,EAAW,CAAC,YAAY,CAC7C,IAAK,IAAM,KAAa,EAEtB,MADW,GAAW,EAI3B,CAII,CACL,KAAM,UACL,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAED,EAAE,OAAO,WAA6D,CACpE,GAAI,EAAQ,OACZ,EAAS,GAGT,IAAK,IAAM,IAAS,CAAC,GAAG,EAAS,CAAC,YAAY,CAE5C,MADmB,EAAM,MAAM,EAAK,CAKtC,IAAM,EAAW,CAAC,GAAG,EAAW,CAAC,YAAY,CAC7C,IAAK,IAAM,KAAa,EAEtB,MADW,GAAW,EAI3B,EAGH,MAAqB,CACnB,IAAM,EAAQ,GAAM,CAEpB,OADA,EAAS,KAAK,EAAM,CACb,GAEV"}
|
package/dist/service/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as service_d_exports } from "../service-
|
|
1
|
+
import { n as service_d_exports } from "../service-DIKUYHda.mjs";
|
|
2
2
|
export { service_d_exports as Service };
|
package/dist/service/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{t as e}from"../service-
|
|
1
|
+
import{t as e}from"../service-DHkeorS3.mjs";export{e as Service};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{t as e}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=service-
|
|
1
|
+
import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";var n=e({Service:()=>r,tag:()=>i});function r(){return e=>{let n=class{static _tag=`Service`;static key=e;static _Self=void 0;static[t]={_A:()=>void 0,_E:()=>void 0,_R:()=>void 0};static*[Symbol.iterator](){return yield n}};return n}}function i(e){let n={_tag:`Service`,key:e,_Self:void 0,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){return yield n}};return n}export{n as t};
|
|
2
|
+
//# sourceMappingURL=service-DHkeorS3.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-
|
|
1
|
+
{"version":3,"file":"service-DHkeorS3.mjs","names":["tag"],"sources":["../src/service/service.ts"],"sourcesContent":["/**\n * Service tag constructors for `Fx` dependency injection.\n *\n * **Mental model**\n * - A service tag is both a runtime lookup key and a typed requirement marker.\n * - `Service()` and `tag()` create values that can be yielded in `Fx.gen`.\n *\n * **Common tasks**\n * - Define class-based services with `Service`.\n * - Define interface-only tags with `tag`.\n *\n * **Gotchas**\n * - Service keys must be globally unique in a context.\n * - Yielding a service tag requires the service to be provided.\n *\n * **Quickstart**\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.Service<{ log: (message: string) => void }>()(\"Logger\")\n * // => service class with key \"Logger\"\n * ```\n *\n * @module\n */\nimport { FxTypeId } from \"../fx/fx.types\"\nimport type { Fx } from \"../fx/fx.types\"\n\n/* oxlint-disable no-unsafe-type-assertion -- Service tags carry phantom generic metadata at runtime and require explicit type assertions. */\n\n// ============================================================================\n// Service Class Types\n// ============================================================================\n\n/**\n * The interface returned by Service()().\n * Acts as both a type tag and a runtime lookup key.\n * Implements Fx protocol with E = never (no errors) and R = Self (requires itself).\n * When yielded, yields itself (as Fx) for proper type inference.\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * type Example = typeof Service\n * ```\n */\nexport type ServiceClass<Self, Key extends string = string> = Fx<Self, never, Self> & {\n readonly _tag: \"Service\"\n readonly key: Key\n // Phantom type\n readonly _Self: Self\n\n /**\n * Yielding the service class in a gen computation\n * returns the service instance from context.\n * Yields the ServiceClass itself (which implements Fx) for type inference.\n */\n [Symbol.iterator](): Generator<ServiceClass<Self, Key>, Self, unknown>\n}\n\n// ============================================================================\n// Service Factory\n// ============================================================================\n\n/**\n * Define a service with a unique key.\n * The returned class acts as both a type and a runtime tag for lookup.\n *\n * Usage follows a double-invocation pattern:\n * - First call provides the Self type parameter\n * - Second call provides the unique key\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.Service<string>()(\"Logger\")\n * // => service class with key \"Logger\"\n * ```\n */\nexport function Service<Self>(): <Key extends string>(key: Key) => ServiceClass<Self, Key> & (new () => Self) {\n return <Key extends string>(key: Key): ServiceClass<Self, Key> & (new () => Self) => {\n // Create the base class with proper prototype\n // oxlint-disable-next-line typescript/no-extraneous-class\n const ServiceBase = class {\n static readonly _tag = \"Service\" as const\n static readonly key: Key = key\n static readonly _Self: Self = undefined as unknown as Self\n\n static readonly [FxTypeId] = {\n _A: () => undefined as unknown as Self,\n _E: () => undefined as never,\n _R: () => undefined as unknown as Self,\n };\n\n /**\n * Yielding the class returns the class itself (for type inference).\n * The runtime intercepts this and provides the actual service instance.\n */\n static *[Symbol.iterator](): Generator<typeof ServiceBase, Self, Self> {\n // Yield the class itself - it implements Fx<Self, never, Self>\n // The runtime will recognize ServiceClass and inject the service\n const serviceInstance = yield ServiceBase\n return serviceInstance\n }\n }\n\n // Return with correct typing\n return ServiceBase as unknown as ServiceClass<Self, Key> & (new () => Self)\n }\n}\n\n/**\n * Create a service tag without class syntax.\n * Useful for simple services that don't need class inheritance.\n *\n * @example\n * ```ts\n * import { Service } from \"@nicolastoulemont/std\"\n *\n * const Logger = Service.tag<string>(\"Logger\")\n * // => plain service tag with key \"Logger\"\n * ```\n */\nexport function tag<S>(key: string): ServiceClass<S> {\n const tag: ServiceClass<S> = {\n _tag: \"Service\",\n key,\n _Self: undefined as unknown as S,\n [FxTypeId]: {\n _A: () => undefined as unknown as S,\n _E: () => undefined as never,\n _R: () => undefined as unknown as S,\n },\n *[Symbol.iterator](): Generator<ServiceClass<S>, S, S> {\n // Yield the tag itself - it implements Fx<S, never, S>\n // The runtime will recognize ServiceClass and inject the service\n const serviceInstance = yield tag\n return serviceInstance\n },\n }\n return tag\n}\n\n/* oxlint-enable no-unsafe-type-assertion */\n"],"mappings":"mHAmFA,SAAgB,GAA8F,CAC5G,MAA4B,IAAyD,CAGnF,IAAM,EAAc,KAAM,CACxB,OAAgB,KAAO,UACvB,OAAgB,IAAW,EAC3B,OAAgB,MAAc,IAAA,GAE9B,OAAiB,GAAY,CAC3B,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CAMD,QAAS,OAAO,WAAuD,CAIrE,OADwB,MAAM,IAMlC,OAAO,GAgBX,SAAgB,EAAO,EAA8B,CACnD,IAAMA,EAAuB,CAC3B,KAAM,UACN,MACA,MAAO,IAAA,IACN,GAAW,CACV,OAAU,IAAA,GACV,OAAU,IAAA,GACV,OAAU,IAAA,GACX,CACD,EAAE,OAAO,WAA8C,CAIrD,OADwB,MAAMA,GAGjC,CACD,OAAOA"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { i as Fx } from "./fx.types-
|
|
1
|
+
import { i as Fx } from "./fx.types-CpFKa-Jj.mjs";
|
|
2
2
|
|
|
3
3
|
//#region src/service/service.d.ts
|
|
4
4
|
declare namespace service_d_exports {
|
|
@@ -60,4 +60,4 @@ declare function Service<Self>(): <Key extends string>(key: Key) => ServiceClass
|
|
|
60
60
|
declare function tag<S>(key: string): ServiceClass<S>;
|
|
61
61
|
//#endregion
|
|
62
62
|
export { service_d_exports as n, ServiceClass as t };
|
|
63
|
-
//# sourceMappingURL=service-
|
|
63
|
+
//# sourceMappingURL=service-DIKUYHda.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service-
|
|
1
|
+
{"version":3,"file":"service-DIKUYHda.d.mts","names":[],"sources":["../src/service/service.ts"],"sourcesContent":[],"mappings":";;;;;;;;;;;;;;AAiDA;;;;;AAIkB,KAJN,YAIM,CAAA,IAAA,EAAA,YAAA,MAAA,GAAA,MAAA,CAAA,GAJ4C,EAI5C,CAJ+C,IAI/C,EAAA,KAAA,EAJ4D,IAI5D,CAAA,GAAA;EAO4B,SAAA,IAAA,EAAA,SAAA;EAAM,SAAA,GAAA,EATpC,GASoC;EAAnB,SAAA,KAAA,EAPf,IAOe;EAAyB;;;AAuB1D;;EAAgF,CAAA,MAAA,CAAA,QAAA,GAAA,EAvBzD,SAuByD,CAvB/C,YAuB+C,CAvBlC,IAuBkC,EAvB5B,GAuB4B,CAAA,EAvBtB,IAuBsB,EAAA,OAAA,CAAA;CAAM;;;;AA4CtF;;;;;;;;;;;;;iBA5CgB,2CAA2C,QAAQ,aAAa,MAAM,kBAAkB;;;;;;;;;;;;;iBA4CxF,qBAAqB,aAAa"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{r as e}from"../trace-ByjppUes.mjs";export{e as Trace};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{t as e}from"./chunk-6rpU2rUb.mjs";import{t}from"./fx.types-Bg-Mmdm5.mjs";import{n}from"./context-7oKePrBY.mjs";import{g as r,h as i,i as a,m as o,p as s}from"./fx.runtime-B2_rL7h_.mjs";var c=e({annotate:()=>b,attribute:()=>x,current:()=>C,currentContext:()=>w,event:()=>S,layer:()=>E,native:()=>f,resolveFxSpanOptions:()=>D,span:()=>y,withParent:()=>T});let l=0;const u=e=>[...crypto.getRandomValues(new Uint8Array(e))].map(e=>e.toString(16).padStart(2,`0`)).join(``),d=e=>({traceId:e===void 0?u(16):(`context`in e?e.context:e).traceId,spanId:`${++l}`.padStart(16,`0`)}),f=()=>({startSpan:({name:e,kind:t,parent:n})=>{let r={},i=[],a=!1;return{name:e,context:d(n),kind:t,attribute(e,t){a||(r[e]=t)},event(e,t){a||i.push(t===void 0?{name:e}:{name:e,attributes:t})},end(){a=!0}}}}),p={_tag:`NoCurrentSpanError`},m=e=>typeof e==`object`&&!!e&&`startSpan`in e&&typeof e.startSpan==`function`,h=e=>typeof e==`object`&&!!e&&`context`in e&&`attribute`in e&&`event`in e,g=e=>m(e)?e:f(),_=e=>`context`in e?e.context:e,v=(e,t,n)=>{let r=g(e.tracer),i=n?.root===!0?void 0:n?.parent??(h(e.currentSpan),e.currentSpan),a={name:t,kind:n?.kind??`internal`,attributes:{...e.spanAttributes,...n?.attributes},links:[...e.spanLinks,...n?.links??[]],...i===void 0?{}:{parent:i},...n?.root===void 0?{}:{root:n.root}},o=r.startSpan(a);for(let[e,t]of Object.entries(n?.attributes??{}))o.attribute(e,t);return o};function y(e,t,n){return r(t,t=>{let r=v(t,e,n);return{...t,currentSpan:r,currentLocalSpan:r,spanAttributes:{},spanLinks:[]}},(e,t)=>{h(t.currentLocalSpan)&&t.currentLocalSpan.end(e)})}const b=e=>o(t=>{if(h(t.currentLocalSpan))for(let[n,r]of Object.entries(e))t.currentLocalSpan.attribute(n,r);return{...t,spanAttributes:{...t.spanAttributes,...e}}}),x=(e,t)=>b({[e]:t}),S=(e,t)=>o(n=>(h(n.currentLocalSpan)&&n.currentLocalSpan.event(e,t),n)),C=()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>p,_R:()=>void 0},*[Symbol.iterator](){let e=yield*a();if(h(e.currentLocalSpan))return e.currentLocalSpan;throw yield p,Error(`Unreachable`)}}),w=()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){let e=yield*a();return h(e.currentSpan)?e.currentSpan.context:e.currentSpan===void 0?void 0:_(e.currentSpan)}}),T=e=>t=>i(t,t=>({...t,currentSpan:e})),E=e=>({_tag:`Layer`,_ROut:void 0,_E:void 0,_RIn:void 0,_Sync:void 0,build:()=>({_tag:`SyncFx`,[t]:{_A:()=>void 0,_E:()=>void 0,_R:()=>void 0},*[Symbol.iterator](){return yield*o(s(e)),n()}})}),D=(e,t)=>{if(typeof e==`string`)return{name:e,options:{}};let{name:n,attributes:r,links:i,...a}=e,o=typeof r==`function`?r(...t):r,s=typeof i==`function`?i(...t):i;return{name:n,options:{...a,...o===void 0?{}:{attributes:o},...s===void 0?{}:{links:s}}}};export{y as n,c as r,D as t};
|
|
2
|
+
//# sourceMappingURL=trace-ByjppUes.mjs.map
|
|
@@ -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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