ts-rules-composer 1.5.0 → 1.7.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.
@@ -0,0 +1,2 @@
1
+ const e=e=>Number.isFinite(e)?e:String(e),t=Symbol.for(`ts-rules-composer.node`),n=(e,n)=>(Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!1,configurable:!0}),e),r=e=>typeof e==`function`&&Object.hasOwn(e,t)?e[t]:void 0,i=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},a=()=>{let e=0,t=(t,n)=>n??i(t)??`rule #${++e}`,n=(e,i,a)=>{let c=r(e);if(!c||c.kind===`rule`)return{id:i,kind:`rule`,label:t(e,c?.label??a),...c?.params?{params:{...c.params}}:{}};switch(c.kind){case`sequence`:return{id:i,kind:`sequence`,via:c.via,steps:c.steps.map((e,t)=>n(e,`${i}.steps.${t}`))};case`branch`:return{id:i,kind:`branch`,test:t(c.test,s(c.test)),...c.ifTrue?{ifTrue:n(c.ifTrue,`${i}.ifTrue`)}:{},...c.ifFalse?{ifFalse:n(c.ifFalse,`${i}.ifFalse`)}:{}};case`all`:case`any`:return{id:i,kind:c.kind,rules:c.rules.map((e,t)=>n(e,`${i}.rules.${t}`))};case`not`:return{id:i,kind:`not`,rule:n(c.rule,`${i}.rule`)};case`fallback`:{let e=n(c.main,`${i}.main`),r=c.guard&&t(c.guard,s(c.guard));return{id:i,kind:`fallback`,main:e,...r?{guard:r}:{},fallback:n(c.fallback,`${i}.fallback`)}}case`field`:return{id:i,kind:`field`,getter:t(c.getter,s(c.getter)),rule:n(c.rule,`${i}.rule`)};case`effect`:return{id:i,kind:`effect`,label:t(c.effect,s(c.effect))};case`decorator`:{let e=c.decorator===`debug`?c.params.name:void 0;return{id:i,kind:`decorator`,decorator:c.decorator,params:{...c.params},rule:n(c.rule,`${i}.rule`,typeof e==`string`?e:a)}}case`switch`:return{id:i,kind:`switch`,selector:t(c.selector,s(c.selector)),cases:Reflect.ownKeys(c.cases).map((e,t)=>({key:String(e),node:n(c.cases[e],`${i}.cases.${t}`)})),...c.default?{default:n(c.default,`${i}.default`)}:{},...c.defaultError===void 0?{}:{defaultError:o(c.defaultError)}};default:return{id:i,kind:`rule`,label:t(e,a)}}};return n},o=e=>typeof e==`string`?e:`custom error`,s=e=>{let t=r(e);return t?.kind===`rule`?t.label:void 0},c=e=>({version:1,root:a()(e,`root`)});Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return r}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return e}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return i}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return n}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return c}});
2
+ //# sourceMappingURL=to-graph-BBdB7p5H.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"to-graph-BBdB7p5H.cjs","names":["jsonNumber","value","NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","hint","step","id","index","readLabel","rule","main","guard","debugName","key","describeError","error","toGraph"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/** A number as a JSON-safe param: `Infinity` and `NaN` would become `null`. */\nexport const jsonNumber = (value: number): number | string =>\n Number.isFinite(value) ? value : String(value);\n\n/** Behavior a decorator adds around a rule without changing what it checks. */\nexport type DecoratorName =\n | \"timeout\"\n | \"retry\"\n | \"memoize\"\n | \"debug\"\n | \"tap\"\n | \"mapError\"\n | \"lazyContext\";\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n }\n | {\n kind: \"switch\";\n selector: Fn;\n /** Copy of the cases object, keyed as `match` received it. */\n cases: Record<PropertyKey, Fn>;\n /** `match`'s default rule; at most one of `default`/`defaultError`. */\n default?: Fn;\n /** `match`'s default error value, kept raw (never stringified here). */\n defaultError?: unknown;\n }\n | {\n /** `every` is `all` (every rule must pass), `oneOf` is `any`. */\n kind: \"all\" | \"any\";\n rules: Fn[];\n }\n | { kind: \"not\"; rule: Fn }\n | {\n kind: \"fallback\";\n main: Fn;\n fallback: Fn;\n /** `onlyFallbackOn`: when set, the fallback runs only if it accepts the error. */\n guard?: Fn;\n }\n | {\n kind: \"field\";\n /** Reads the value the rule is applied to. */\n getter: Fn;\n rule: Fn;\n }\n | {\n kind: \"effect\";\n /** The side effect `tap` runs; the rule always passes. */\n effect: Fn;\n }\n | {\n kind: \"decorator\";\n decorator: DecoratorName;\n /** The decorated rule, as passed in. */\n rule: Fn;\n /** Settings worth showing, as plain JSON values. */\n params: Record<string, unknown>;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n }\n | {\n id: string;\n kind: \"switch\";\n selector: string;\n /** In `Reflect.ownKeys` order; symbol keys appear as `Symbol(desc)`. */\n cases: { key: string; node: GraphNode }[];\n /** Absent `default` and `defaultError` mean \"no match\" fails. */\n default?: GraphNode;\n defaultError?: string;\n }\n | {\n id: string;\n kind: \"all\" | \"any\";\n rules: GraphNode[];\n }\n | { id: string; kind: \"not\"; rule: GraphNode }\n | {\n id: string;\n kind: \"fallback\";\n main: GraphNode;\n fallback: GraphNode;\n guard?: string;\n }\n | { id: string; kind: \"field\"; getter: string; rule: GraphNode }\n | { id: string; kind: \"effect\"; label: string }\n | {\n id: string;\n kind: \"decorator\";\n decorator: DecoratorName;\n params: Record<string, unknown>;\n rule: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n /**\n * `hint` is a label offered by an enclosing `withDebug`: it names a leaf\n * rule that has no explicit label, ahead of the function's own name.\n */\n const build = (fn: Fn, id: string, hint?: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label ?? hint),\n ...(raw?.params ? { params: { ...raw.params } } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n case \"all\":\n case \"any\":\n return {\n id,\n kind: raw.kind,\n rules: raw.rules.map((rule, index) =>\n build(rule, `${id}.rules.${index}`),\n ),\n };\n case \"not\":\n return { id, kind: \"not\", rule: build(raw.rule, `${id}.rule`) };\n case \"fallback\": {\n // Numbered in execution order: main, then the guard, then the fallback.\n const main = build(raw.main, `${id}.main`);\n const guard = raw.guard && labelOf(raw.guard, readLabel(raw.guard));\n return {\n id,\n kind: \"fallback\",\n main,\n ...(guard ? { guard } : {}),\n fallback: build(raw.fallback, `${id}.fallback`),\n };\n }\n case \"field\": {\n const getter = labelOf(raw.getter, readLabel(raw.getter));\n return {\n id,\n kind: \"field\",\n getter,\n rule: build(raw.rule, `${id}.rule`),\n };\n }\n case \"effect\":\n return {\n id,\n kind: \"effect\",\n label: labelOf(raw.effect, readLabel(raw.effect)),\n };\n case \"decorator\": {\n const debugName =\n raw.decorator === \"debug\" ? raw.params.name : undefined;\n return {\n id,\n kind: \"decorator\",\n decorator: raw.decorator,\n params: { ...raw.params },\n rule: build(\n raw.rule,\n `${id}.rule`,\n typeof debugName === \"string\" ? debugName : hint,\n ),\n };\n }\n case \"switch\": {\n const selector = labelOf(raw.selector, readLabel(raw.selector));\n return {\n id,\n kind: \"switch\",\n selector,\n cases: Reflect.ownKeys(raw.cases).map((key, index) => ({\n key: String(key),\n node: build(raw.cases[key] as Fn, `${id}.cases.${index}`),\n })),\n ...(raw.default\n ? { default: build(raw.default, `${id}.default`) }\n : {}),\n ...(raw.defaultError !== undefined\n ? { defaultError: describeError(raw.defaultError) }\n : {}),\n };\n }\n // The node key is shared, so another version of this package could have\n // attached a kind this one does not know: describe it as a leaf.\n default:\n return { id, kind: \"rule\", label: labelOf(fn, hint) };\n }\n };\n\n return build;\n};\n\n/** Strings are shown as-is; anything else is never stringified (it could run user code). */\nconst describeError = (error: unknown) =>\n typeof error === \"string\" ? error : \"custom error\";\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAWA,MAAaA,EA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AAK,EAAK,KAAW,CACrD,IAAK,OAAOU,CAAG,EACf,KAAMX,EAAMC,EAAI,MAAMU,GAAY,GAAGP,EAAG,SAASC,GAAO,CAC1D,EAAE,EACF,GAAIJ,EAAI,QACJ,CAAE,QAASD,EAAMC,EAAI,QAAS,GAAGG,EAAG,SAAS,CAAE,EAC/C,CAAC,EACL,GAAIH,EAAI,eAAiB,IAAA,GAErB,CAAC,EADD,CAAE,aAAcW,EAAcX,EAAI,YAAY,CAAE,CAEtD,EAIF,QACE,MAAO,CAAE,KAAI,KAAM,OAAQ,MAAOH,EAAQP,EAAIW,CAAI,CAAE,CACxD,CACF,EAEA,OAAOF,CACT,EAGMY,EAAiB,GACrB,OAAOC,GAAU,SAAWA,EAAQ,eAEhCP,EAAa,GAAW,CAC5B,IAAML,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaa,EACX,IACe,CAAE,QAAS,EAAG,KAAMlB,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
@@ -0,0 +1,2 @@
1
+ const e=e=>Number.isFinite(e)?e:String(e),t=Symbol.for(`ts-rules-composer.node`),n=(e,n)=>(Object.defineProperty(e,t,{value:n,enumerable:!1,writable:!1,configurable:!0}),e),r=e=>typeof e==`function`&&Object.hasOwn(e,t)?e[t]:void 0,i=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},a=()=>{let e=0,t=(t,n)=>n??i(t)??`rule #${++e}`,n=(e,i,a)=>{let c=r(e);if(!c||c.kind===`rule`)return{id:i,kind:`rule`,label:t(e,c?.label??a),...c?.params?{params:{...c.params}}:{}};switch(c.kind){case`sequence`:return{id:i,kind:`sequence`,via:c.via,steps:c.steps.map((e,t)=>n(e,`${i}.steps.${t}`))};case`branch`:return{id:i,kind:`branch`,test:t(c.test,s(c.test)),...c.ifTrue?{ifTrue:n(c.ifTrue,`${i}.ifTrue`)}:{},...c.ifFalse?{ifFalse:n(c.ifFalse,`${i}.ifFalse`)}:{}};case`all`:case`any`:return{id:i,kind:c.kind,rules:c.rules.map((e,t)=>n(e,`${i}.rules.${t}`))};case`not`:return{id:i,kind:`not`,rule:n(c.rule,`${i}.rule`)};case`fallback`:{let e=n(c.main,`${i}.main`),r=c.guard&&t(c.guard,s(c.guard));return{id:i,kind:`fallback`,main:e,...r?{guard:r}:{},fallback:n(c.fallback,`${i}.fallback`)}}case`field`:return{id:i,kind:`field`,getter:t(c.getter,s(c.getter)),rule:n(c.rule,`${i}.rule`)};case`effect`:return{id:i,kind:`effect`,label:t(c.effect,s(c.effect))};case`decorator`:{let e=c.decorator===`debug`?c.params.name:void 0;return{id:i,kind:`decorator`,decorator:c.decorator,params:{...c.params},rule:n(c.rule,`${i}.rule`,typeof e==`string`?e:a)}}case`switch`:return{id:i,kind:`switch`,selector:t(c.selector,s(c.selector)),cases:Reflect.ownKeys(c.cases).map((e,t)=>({key:String(e),node:n(c.cases[e],`${i}.cases.${t}`)})),...c.default?{default:n(c.default,`${i}.default`)}:{},...c.defaultError===void 0?{}:{defaultError:o(c.defaultError)}};default:return{id:i,kind:`rule`,label:t(e,a)}}};return n},o=e=>typeof e==`string`?e:`custom error`,s=e=>{let t=r(e);return t?.kind===`rule`?t.label:void 0},c=e=>({version:1,root:a()(e,`root`)});export{r as a,e as i,i as n,n as r,c as t};
2
+ //# sourceMappingURL=to-graph-nf3nMDMB.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"to-graph-nf3nMDMB.js","names":["jsonNumber","value","NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","hint","step","id","index","readLabel","rule","main","guard","debugName","key","describeError","error","toGraph"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/** A number as a JSON-safe param: `Infinity` and `NaN` would become `null`. */\nexport const jsonNumber = (value: number): number | string =>\n Number.isFinite(value) ? value : String(value);\n\n/** Behavior a decorator adds around a rule without changing what it checks. */\nexport type DecoratorName =\n | \"timeout\"\n | \"retry\"\n | \"memoize\"\n | \"debug\"\n | \"tap\"\n | \"mapError\"\n | \"lazyContext\";\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n }\n | {\n kind: \"switch\";\n selector: Fn;\n /** Copy of the cases object, keyed as `match` received it. */\n cases: Record<PropertyKey, Fn>;\n /** `match`'s default rule; at most one of `default`/`defaultError`. */\n default?: Fn;\n /** `match`'s default error value, kept raw (never stringified here). */\n defaultError?: unknown;\n }\n | {\n /** `every` is `all` (every rule must pass), `oneOf` is `any`. */\n kind: \"all\" | \"any\";\n rules: Fn[];\n }\n | { kind: \"not\"; rule: Fn }\n | {\n kind: \"fallback\";\n main: Fn;\n fallback: Fn;\n /** `onlyFallbackOn`: when set, the fallback runs only if it accepts the error. */\n guard?: Fn;\n }\n | {\n kind: \"field\";\n /** Reads the value the rule is applied to. */\n getter: Fn;\n rule: Fn;\n }\n | {\n kind: \"effect\";\n /** The side effect `tap` runs; the rule always passes. */\n effect: Fn;\n }\n | {\n kind: \"decorator\";\n decorator: DecoratorName;\n /** The decorated rule, as passed in. */\n rule: Fn;\n /** Settings worth showing, as plain JSON values. */\n params: Record<string, unknown>;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n }\n | {\n id: string;\n kind: \"switch\";\n selector: string;\n /** In `Reflect.ownKeys` order; symbol keys appear as `Symbol(desc)`. */\n cases: { key: string; node: GraphNode }[];\n /** Absent `default` and `defaultError` mean \"no match\" fails. */\n default?: GraphNode;\n defaultError?: string;\n }\n | {\n id: string;\n kind: \"all\" | \"any\";\n rules: GraphNode[];\n }\n | { id: string; kind: \"not\"; rule: GraphNode }\n | {\n id: string;\n kind: \"fallback\";\n main: GraphNode;\n fallback: GraphNode;\n guard?: string;\n }\n | { id: string; kind: \"field\"; getter: string; rule: GraphNode }\n | { id: string; kind: \"effect\"; label: string }\n | {\n id: string;\n kind: \"decorator\";\n decorator: DecoratorName;\n params: Record<string, unknown>;\n rule: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n /**\n * `hint` is a label offered by an enclosing `withDebug`: it names a leaf\n * rule that has no explicit label, ahead of the function's own name.\n */\n const build = (fn: Fn, id: string, hint?: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label ?? hint),\n ...(raw?.params ? { params: { ...raw.params } } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n case \"all\":\n case \"any\":\n return {\n id,\n kind: raw.kind,\n rules: raw.rules.map((rule, index) =>\n build(rule, `${id}.rules.${index}`),\n ),\n };\n case \"not\":\n return { id, kind: \"not\", rule: build(raw.rule, `${id}.rule`) };\n case \"fallback\": {\n // Numbered in execution order: main, then the guard, then the fallback.\n const main = build(raw.main, `${id}.main`);\n const guard = raw.guard && labelOf(raw.guard, readLabel(raw.guard));\n return {\n id,\n kind: \"fallback\",\n main,\n ...(guard ? { guard } : {}),\n fallback: build(raw.fallback, `${id}.fallback`),\n };\n }\n case \"field\": {\n const getter = labelOf(raw.getter, readLabel(raw.getter));\n return {\n id,\n kind: \"field\",\n getter,\n rule: build(raw.rule, `${id}.rule`),\n };\n }\n case \"effect\":\n return {\n id,\n kind: \"effect\",\n label: labelOf(raw.effect, readLabel(raw.effect)),\n };\n case \"decorator\": {\n const debugName =\n raw.decorator === \"debug\" ? raw.params.name : undefined;\n return {\n id,\n kind: \"decorator\",\n decorator: raw.decorator,\n params: { ...raw.params },\n rule: build(\n raw.rule,\n `${id}.rule`,\n typeof debugName === \"string\" ? debugName : hint,\n ),\n };\n }\n case \"switch\": {\n const selector = labelOf(raw.selector, readLabel(raw.selector));\n return {\n id,\n kind: \"switch\",\n selector,\n cases: Reflect.ownKeys(raw.cases).map((key, index) => ({\n key: String(key),\n node: build(raw.cases[key] as Fn, `${id}.cases.${index}`),\n })),\n ...(raw.default\n ? { default: build(raw.default, `${id}.default`) }\n : {}),\n ...(raw.defaultError !== undefined\n ? { defaultError: describeError(raw.defaultError) }\n : {}),\n };\n }\n // The node key is shared, so another version of this package could have\n // attached a kind this one does not know: describe it as a leaf.\n default:\n return { id, kind: \"rule\", label: labelOf(fn, hint) };\n }\n };\n\n return build;\n};\n\n/** Strings are shown as-is; anything else is never stringified (it could run user code). */\nconst describeError = (error: unknown) =>\n typeof error === \"string\" ? error : \"custom error\";\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAWA,MAAaA,EAAc,GACzB,OAAO,SAASC,CAAK,EAAIA,EAAQ,OAAOA,CAAK,EAgJlCC,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCjLOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAMrCG,GAAS,EAAQ,EAAY,IAA6B,CAC9D,IAAMC,EAAMR,EAASF,CAAE,EAGvB,GAAI,CAACU,GAAOA,EAAI,OAAS,OACvB,MAAO,CACL,KACA,KAAM,OACN,MAAOH,EAAQP,EAAIU,GAAK,OAASC,CAAI,EACrC,GAAID,GAAK,OAAS,CAAE,OAAQ,CAAE,GAAGA,EAAI,MAAO,CAAE,EAAI,CAAC,CACrD,EAGF,OAAQA,EAAI,KAAZ,CACE,IAAK,WACH,MAAO,CACL,KACA,KAAM,WACN,IA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AAc,QAAUA,EAAI,OAAO,KAAO,IAAA,GAChD,MAAO,CACL,KACA,KAAM,YACN,UAAWA,EAAI,UACf,OAAQ,CAAE,GAAGA,EAAI,MAAO,EACxB,KAAMD,EACJC,EAAI,KACJ,GAAGG,EAAG,OACN,OAAOM,GAAc,SAAWA,EAAYR,CAC9C,CACF,CACF,CACA,IAAK,SAEH,MAAO,CACL,KACA,KAAM,SACN,SAJeJ,EAAQG,EAAI,SAAUK,EAAUL,EAAI,QAAQ,CAIpD,EACP,MAAO,QAAQ,QAAQA,EAAI,KAAK,CAAC,CAAC,KAAK,EAAK,KAAW,CACrD,IAAK,OAAOU,CAAG,EACf,KAAMX,EAAMC,EAAI,MAAMU,GAAY,GAAGP,EAAG,SAASC,GAAO,CAC1D,EAAE,EACF,GAAIJ,EAAI,QACJ,CAAE,QAASD,EAAMC,EAAI,QAAS,GAAGG,EAAG,SAAS,CAAE,EAC/C,CAAC,EACL,GAAIH,EAAI,eAAiB,IAAA,GAErB,CAAC,EADD,CAAE,aAAcW,EAAcX,EAAI,YAAY,CAAE,CAEtD,EAIF,QACE,MAAO,CAAE,KAAI,KAAM,OAAQ,MAAOH,EAAQP,EAAIW,CAAI,CAAE,CACxD,CACF,EAEA,OAAOF,CACT,EAGMY,EAAiB,GACrB,OAAOC,GAAU,SAAWA,EAAQ,eAEhCP,EAAa,GAAW,CAC5B,IAAML,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaa,EACX,IACe,CAAE,QAAS,EAAG,KAAMlB,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ts-rules-composer",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "Typescript rules engine by composition",
5
5
  "main": "./dist/index.cjs",
6
6
  "module": "./dist/index.js",
@@ -1,2 +0,0 @@
1
- const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});export{t as n,o as t};
2
- //# sourceMappingURL=to-graph-Dd9xksGt.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"to-graph-Dd9xksGt.js","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n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K,EAAa,GAAW,CAC5B,IAAMJ,EAAMR,EAASF,CAAE,EACvB,OAAOU,GAAK,OAAS,OAASA,EAAI,MAAQ,IAAA,EAC5C,EAeaK,EACX,IACe,CAAE,QAAS,EAAG,KAAMV,EAAc,CAAC,CAACW,EAAM,MAAM,CAAE,G"}
@@ -1,2 +0,0 @@
1
- const e=Symbol.for(`ts-rules-composer.node`),t=(t,n)=>(Object.defineProperty(t,e,{value:n,enumerable:!1,writable:!1,configurable:!0}),t),n=t=>typeof t==`function`&&Object.hasOwn(t,e)?t[e]:void 0,r=e=>{let{name:t}=e;return t===``||t===`anonymous`||t.startsWith(`bound `)?void 0:t},i=()=>{let e=0,t=(t,n)=>n??r(t)??`rule #${++e}`,i=(e,r)=>{let o=n(e);if(!o||o.kind===`rule`)return{id:r,kind:`rule`,label:t(e,o?.label),...o?.params?{params:o.params}:{}};switch(o.kind){case`sequence`:return{id:r,kind:`sequence`,via:o.via,steps:o.steps.map((e,t)=>i(e,`${r}.steps.${t}`))};case`branch`:return{id:r,kind:`branch`,test:t(o.test,a(o.test)),...o.ifTrue?{ifTrue:i(o.ifTrue,`${r}.ifTrue`)}:{},...o.ifFalse?{ifFalse:i(o.ifFalse,`${r}.ifFalse`)}:{}}}};return i},a=e=>{let t=n(e);return t?.kind===`rule`?t.label:void 0},o=e=>({version:1,root:i()(e,`root`)});Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return t}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return o}});
2
- //# sourceMappingURL=to-graph-Dilv6lBr.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"to-graph-Dilv6lBr.cjs","names":["NODE_KEY","attachNode","fn","node","readNode","usableName","name","createBuilder","unlabelled","labelOf","explicit","build","raw","step","id","index","readLabel","toGraph","rule"],"sources":["../src/lib/graph/node.ts","../src/lib/graph/labels.ts","../src/lib/graph/to-graph.ts"],"sourcesContent":["/**\n * Graph node primitives.\n *\n * This module must not import from `combinators/` or `helpers/`: combinators\n * import it, and `helpers/` and `combinators/` already depend on each other.\n */\n\n/** Any function a combinator may hold as a child (rule, predicate, accessor). */\nexport type Fn = (...args: never[]) => unknown;\n\n/**\n * Structure recorded by a combinator at construction time. Children are the\n * original functions passed in (before any safety wrapping), so they can be\n * inspected later. Internal: the public, JSON-safe form is {@link GraphNode}.\n */\nexport type RawNode =\n | {\n /** A rule given an explicit label by `named`. */\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n kind: \"sequence\";\n /** Steps in execution order (`composeRules` runs its array reversed). */\n steps: Fn[];\n via: \"pipeRules\" | \"composeRules\";\n }\n | {\n kind: \"branch\";\n /**\n * `when` has only `ifTrue`, `unless` only `ifFalse`, `ifElse` both. A\n * missing side passes. (Not named `then`/`else`: an object with a\n * `then` key is treated as a promise by `await`.)\n */\n test: Fn;\n ifTrue?: Fn;\n ifFalse?: Fn;\n };\n\n/** Public, JSON-serializable graph. Built by `toGraph`. */\nexport type GraphNode =\n | {\n id: string;\n kind: \"rule\";\n label: string;\n params?: Record<string, unknown>;\n }\n | {\n id: string;\n kind: \"sequence\";\n via: \"pipeRules\" | \"composeRules\";\n steps: GraphNode[];\n }\n | {\n id: string;\n kind: \"branch\";\n test: string;\n ifTrue?: GraphNode;\n ifFalse?: GraphNode;\n };\n\nexport type RuleGraph = { version: 1; root: GraphNode };\n\n/**\n * Registry symbol, so ESM and CJS copies of the package (or several copies of\n * one version) read each other's metadata.\n */\nexport const NODE_KEY: unique symbol = Symbol.for(\n \"ts-rules-composer.node\",\n) as never;\n\ntype WithNode = { [NODE_KEY]?: RawNode };\n\n/**\n * Records `node` on `fn` and returns the same function. The property is\n * non-enumerable, so spreading, `Object.keys` and `JSON.stringify` are\n * unaffected. A later call replaces an earlier one.\n */\nexport const attachNode = <F extends Fn>(fn: F, node: RawNode): F => {\n Object.defineProperty(fn, NODE_KEY, {\n value: node,\n enumerable: false,\n writable: false,\n configurable: true,\n });\n return fn;\n};\n\n/** Returns the node recorded on `fn`, or `undefined` for plain functions. */\nexport const readNode = (fn: unknown): RawNode | undefined =>\n typeof fn === \"function\" && Object.hasOwn(fn, NODE_KEY)\n ? (fn as WithNode)[NODE_KEY]\n : undefined;\n","/**\n * The function's own name, unless it carries no information: empty,\n * \"anonymous\", or the \"bound x\" name given by `Function.prototype.bind`.\n */\nexport const usableName = (fn: { name: string }): string | undefined => {\n const { name } = fn;\n return name === \"\" || name === \"anonymous\" || name.startsWith(\"bound \")\n ? undefined\n : name;\n};\n","import type { Rule } from \"../types\";\nimport { usableName } from \"./labels\";\nimport { type Fn, type GraphNode, type RuleGraph, readNode } from \"./node\";\n\n/**\n * Builds the public graph. Unlabelled functions get `rule #n`, numbered in\n * depth-first order (a branch's predicate before its sides) so that the same\n * pipeline always yields the same labels.\n */\nconst createBuilder = () => {\n let unlabelled = 0;\n const labelOf = (fn: Fn, explicit?: string) =>\n explicit ?? usableName(fn) ?? `rule #${++unlabelled}`;\n\n const build = (fn: Fn, id: string): GraphNode => {\n const raw = readNode(fn);\n\n // Any function without a recorded structure is a leaf rule.\n if (!raw || raw.kind === \"rule\") {\n return {\n id,\n kind: \"rule\",\n label: labelOf(fn, raw?.label),\n ...(raw?.params ? { params: raw.params } : {}),\n };\n }\n\n switch (raw.kind) {\n case \"sequence\":\n return {\n id,\n kind: \"sequence\",\n via: raw.via,\n steps: raw.steps.map((step, index) =>\n build(step, `${id}.steps.${index}`),\n ),\n };\n case \"branch\": {\n const test = labelOf(raw.test, readLabel(raw.test));\n return {\n id,\n kind: \"branch\",\n test,\n ...(raw.ifTrue ? { ifTrue: build(raw.ifTrue, `${id}.ifTrue`) } : {}),\n ...(raw.ifFalse\n ? { ifFalse: build(raw.ifFalse, `${id}.ifFalse`) }\n : {}),\n };\n }\n }\n };\n\n return build;\n};\n\nconst readLabel = (fn: Fn) => {\n const raw = readNode(fn);\n return raw?.kind === \"rule\" ? raw.label : undefined;\n};\n\n/**\n * Describes a rule as a JSON-serializable graph, without running it.\n *\n * Rules built with this package's combinators are described structurally; any\n * other function (including your own wrappers) is a single leaf rule.\n *\n * @example\n * const graph = toGraph(pipeRules([hasItems, withinLimit]));\n * // { version: 1, root: { kind: \"sequence\", steps: [...] } }\n * @caveats\n * - Nothing is executed: rules, predicates and accessors are never called.\n * - Anonymous functions are labelled `rule #n`; use `named` for a real name.\n */\nexport const toGraph = <TInput, TError, TContext>(\n rule: Rule<TInput, TError, TContext>,\n): RuleGraph => ({ version: 1, root: createBuilder()(rule, \"root\") });\n"],"mappings":"AAoEA,MAAaA,EAA0B,OAAO,IAC5C,wBACF,EASaC,GAA4B,EAAO,KAC9C,OAAO,eAAeC,EAAIF,EAAU,CAClC,MAAOG,EACP,WAAY,GACZ,SAAU,GACV,aAAc,EAChB,CAAC,EACMD,GAIIE,EAAY,GACvB,OAAOF,GAAO,YAAc,OAAO,OAAOA,EAAIF,CAAQ,EACjDE,EAAgBF,GACjB,IAAA,GCzFOK,EAAc,GAA6C,CACtE,GAAM,CAAE,QAASH,EACjB,OAAOI,IAAS,IAAMA,IAAS,aAAeA,EAAK,WAAW,QAAQ,EAClE,IAAA,GACAA,CACN,ECAMC,MAAsB,CAC1B,IAAIC,EAAa,EACXC,GAAW,EAAQ,IACvBC,GAAYL,EAAWH,CAAE,GAAK,SAAS,EAAEM,IAErCG,GAAS,EAAQ,IAA0B,CAC/C,IAAMC,EAAMR,EAASF,CAAE,EAGvB,GAAI,CAACU,GAAOA,EAAI,OAAS,OACvB,MAAO,CACL,KACA,KAAM,OACN,MAAOH,EAAQP,EAAIU,GAAK,KAAK,EAC7B,GAAIA,GAAK,OAAS,CAAE,OAAQA,EAAI,MAAO,EAAI,CAAC,CAC9C,EAGF,OAAQA,EAAI,KAAZ,CACE,IAAK,WACH,MAAO,CACL,KACA,KAAM,WACN,IAAKA,EAAI,IACT,MAAOA,EAAI,MAAM,KAAK,EAAM,IAC1BD,EAAME,EAAM,GAAGC,EAAG,SAASC,GAAO,CACpC,CACF,EACF,IAAK,SAEH,MAAO,C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