Metakit / @doeixd/metakit

Expr

namespace · packages/metakit/src/expr.ts:12

export * as Expr from './expr.js'

Inspectable, pure, terminating expressions indexed by a typed environment Env (Expr<Env, A>).

  • Expr.refine attaches a symbolic Expr to an Effect Schema as both a real Schema.makeFilter runtime check and a SchemaAST annotation.
  • Expr.in builds an expression over a multi-slice environment such as { row: Account, principal: Principal } or { model: State }.
  • Expr.eval, Expr.residualize, Expr.judge, Expr.reads, and Expr.lift operate on any Expr.

In the guides

Members

Expr.all

function · packages/metakit/src/expr.ts:105

function all<
  const Terms extends ReadonlyArray<ExprInput<never, boolean | null>>,
>(...terms: Terms): ExprType<TupleEnv<Terms>, boolean | NullOf<Terms[number]>>

Conjunction in a balanced tree, preserving term order (empty = true).

Expr.any

function · packages/metakit/src/expr.ts:111

function any<
  const Terms extends ReadonlyArray<ExprInput<never, boolean | null>>,
>(...terms: Terms): ExprType<TupleEnv<Terms>, boolean | NullOf<Terms[number]>>

Disjunction in a balanced tree, preserving term order (empty = false).

Expr.EnvOfInput

type · packages/metakit/src/ops/core.ts:35

type EnvOfInput<T> = T extends Expr<infer E, unknown> ? E : unknown

Extract the Env required by an ExprInput (unknown for plain literals).

Expr.eval

function · packages/metakit/src/expr.ts:216

function eval<Env, A>(
  expr: ExprType<Env, A>,
  env: Env,
  options?: ReaderOptions,
): A

evalResult for an environment that decodes against the Schemas expr was built from, where no operand is null: it returns the value and throws the Node.Refusal. Evaluation is null-strict, so over a null or absent operand the result is null whatever A says.

Expr.evalResult

function · packages/metakit/src/expr.ts:201

function evalResult<Env, A>(
  expr: ExprType<Env, A>,
  env: Env,
  options?: ReaderOptions,
): Result.Result<A | null, Node.Refusal>

Evaluate expr against a complete environment env: its value, null where an operand was null or absent, or the Node.Refusal of an integer past ±(2^53−1), a non-finite number, an ill-typed operand or an unmatched case. A path that reads a number turns -0 into 0.

Expr.evaluate

function · packages/metakit/src/expr.ts:216

function evaluate<Env, A>(
  expr: ExprType<Env, A>,
  env: Env,
  options?: ReaderOptions,
): A

evalResult for an environment that decodes against the Schemas expr was built from, where no operand is null: it returns the value and throws the Node.Refusal. Evaluation is null-strict, so over a null or absent operand the result is null whatever A says.

Expr.EvidenceAssurance

type · packages/metakit/src/ops/lawsForeign.ts:9

type EvidenceAssurance = 'claim' | 'tested' | 'proven' | 'builtin'

Assurance level backing a foreign algebraic claim rewrite.

Expr.ExactRules

interface · packages/metakit/src/exprRules.ts:69

interface ExactRules<A> {
  readonly rules: ReadonlyArray<Refinement<A>>
  readonly unread: ReadonlyArray<UnreadCheck>
}

Result of Expr.rulesOfExact: every rule read, plus every check that could not be read.

Expr.Expr

interface · packages/metakit/src/path.ts:22

interface Expr<in Env, out A> extends Pipeable.Pipeable {
  readonly [ExprTypeId]: {
    readonly env: (env: Env) => void
    readonly out: () => A
  }
  readonly node: Node.Node
}

Pure, terminating expression reading paths from Env and producing A. Env is contravariant (phantom) so an expression over { row } widens into { row, principal } without adapters.

Expr.ExprInput

type · packages/metakit/src/ops/core.ts:25

type ExprInput<Env, A> = Expr<Env, A> | A

Either an Expr<Env, A> or a plain literal value A.

Expr.ForeignClaimKind

type · packages/metakit/src/ops/lawsForeign.ts:12

type ForeignClaimKind =
  | 'identity'
  | 'absorbing'
  | 'idempotent'
  | 'total'
  | 'commutative'
  | 'associative'
  | 'invertible'
  | 'monotone'

Foreign algebraic claim kinds gated by ForeignRewritePolicy.

Expr.ForeignImplementation

interface · packages/metakit/src/nodeTree.ts:64

interface ForeignImplementation {
  readonly run: (
    args: ReadonlyArray<unknown>,
    foreign?: ForeignImplementations,
  ) => unknown
}

One implementation of a foreign operation.

Expr.ForeignImplementations

type · packages/metakit/src/nodeTree.ts:76

type ForeignImplementations = Readonly<Record<string, ForeignImplementation>>

The implementations a reader is given, by id@version (Node.foreignName), so two versions of one operation each have theirs.

Expr.ForeignRewriteEvidence

class · packages/metakit/src/ops/lawsForeign.ts:87

class ForeignRewriteEvidence {}

Opaque evidence authorizing algebraic rewrites for a specific foreign operation descriptor bound to a specific JS implementation function. Only attestClaims creates it, for a claim whose equation held; rebinding the operation or any binding it was checked through, or changing the claim, invalidates it.

Expr.ForeignRewritePolicy

type · packages/metakit/src/ops/lawsForeign.ts:177

type ForeignRewritePolicy = Data.TaggedEnum<{
  readonly Trusted: {}
  readonly Verified: {
    readonly evidence: ReadonlyArray<ForeignRewriteEvidence>
    readonly minAssurance: EvidenceAssurance
  }
}>

Trust policy controlling whether a reader answers from a foreign operation's declared claims: the rewrites of residualize and judge, Transition.can, Pairs.commutes and Pairs.idempotent, the checker's bounds from a monotone claim, and what reorders or inverts a reduce fold.

  • Absent (undefined): applies no claim.
  • Expr.RewritePolicy.trusted: applies declared op.claims without checking them. A claim that is false of the implementation then gives wrong answers from every reader above; use verified to have claims checked.
  • Expr.RewritePolicy.verified(evidence, { minAssurance? }): applies a claim rewrite only when evidence holds a genuine ForeignRewriteEvidence instance matching the exact operation descriptor, bound implementation, current claim value, recorded dependency bindings, and claim at or above minAssurance (default 'tested'). Conservative fallback preserves the original call (Unknown in judge) when evidence is absent, insufficient, or invalidated by rebinding.

Expr.fromNode

function · packages/metakit/src/ops/core.ts:51

function fromNode<Env, A>(node: Node.Node): Expr<Env, A>

Wrap a raw Node as a typed Expr<Env, A>.

Expr.holds

function · packages/metakit/src/expr.ts:226

function holds<Env>(
  expr: ExprType<Env, boolean | null>,
  env: Env,
  options?: ReaderOptions,
): boolean

Whether the rule expr holds of env: only where it evaluates to true, never on null or a refusal.

Expr.implies

function · packages/metakit/src/expr.ts:120

function implies<
  C extends ExprInput<never, boolean | null>,
  T extends ExprInput<never, boolean | null>,
>(
  condition: C,
  then: T,
): ExprType<EnvOfInput<C> & EnvOfInput<T>, boolean | NullOf<C> | NullOf<T>>

Logical implication (condition => then, equivalent to !condition || then).

Expr.in

function · packages/metakit/src/expr.ts:179

function in<Shape extends Readonly<Record<string, Schema.Top>>, A>(shape: Shape, build: (env: {
    readonly [K in keyof Shape & string]: PathAccessor<Path.EnvOf<Shape>, Shape[K]['Type']>;
}) => ExprInput<Path.EnvOf<Shape>, A>): ExprType<Path.EnvOf<Shape>, A>;

Build an Expr over a multi-slice environment declared as { slice: Schema }, such as { row: Account, principal: Principal } or { model: Account }.

Expr.inEnv

function · packages/metakit/src/expr.ts:179

function inEnv<Shape extends Readonly<Record<string, Schema.Top>>, A>(
  shape: Shape,
  build: (env: {
    readonly [K in keyof Shape & string]: PathAccessor<
      Path.EnvOf<Shape>,
      Shape[K]['Type']
    >
  }) => ExprInput<Path.EnvOf<Shape>, A>,
): ExprType<Path.EnvOf<Shape>, A>

Build an Expr over a multi-slice environment declared as { slice: Schema }, such as { row: Account, principal: Principal } or { model: Account }.

Expr.isExpr

function · packages/metakit/src/ops/core.ts:59

function isExpr(value: unknown): value is Expr<never, unknown>

True when value is an Expr (including a Path).

Expr.judge

function · packages/metakit/src/expr.ts:259

function judge<Env>(
  expr: ExprType<Env, boolean | null>,
  partialEnv: NoInfer<PartialEnv<Env>>,
  options?: ReaderOptions,
): Verdict<Node.Refusal>

Partially evaluate a boolean expr and say whether it holds: True where it is known to be true, False where it is known to be false, null or refused (the refusal is the witness), Unknown where it cannot tell. A foreign call with no implementation given is Unknown. An omitted optional struct key is unknown in the partial environment.

Expr.lift

function · packages/metakit/src/expr.ts:190

function lift<Outer, Inner, A>(
  path: PathType<Outer, Inner>,
  expr: ExprType<Inner, A>,
): ExprType<Outer, A>

Lift an Expr<Inner, A> along Path<Outer, Inner> into Expr<Outer, A>.

Expr.lit

function · packages/metakit/src/expr.ts:83

function lit<const A extends PlainLiteral>(value: A): ExprType<unknown, A>

Construct a constant expression.

Expr.match

function · packages/metakit/src/exprMatch.ts:84

function match<
  Env,
  K extends string,
  const Cases extends {
    readonly [P in K]: ExprInput<never, unknown>
  },
>(
  on: ExprType<Env, K>,
  cases: Cases & {
    readonly [P in Exclude<keyof Cases, K>]: never
  },
): ExprType<
  Env & UnionToIntersection<EnvOfInput<Cases[keyof Cases]>>,
  ValueOfInput<Cases[keyof Cases]>
>

Exhaustive literal Match over a string union expression: one case for each value and no other, checked by the types and again where the expression is built. A null on gives null.

Expr.matchOrElse

function · packages/metakit/src/exprMatch.ts:115

function matchOrElse<
  Env,
  K extends string | null,
  const Cases extends {
    readonly [P in Exclude<K, null>]?: ExprInput<never, unknown>
  },
  const Fallback extends ExprInput<never, unknown>,
>(
  on: ExprType<Env, K>,
  cases: Cases,
  otherwise: Fallback,
): ExprType<
  Env &
    UnionToIntersection<EnvOfInput<Exclude<Cases[keyof Cases], undefined>>> &
    EnvOfInput<Fallback>,
  ValueOfInput<Exclude<Cases[keyof Cases], undefined>> | ValueOfInput<Fallback>
>

Partial literal Match with an explicit fallback branch, which takes null and every value no case names.

Expr.matchTags

function · packages/metakit/src/exprMatch.ts:289

function matchTags<
  Env,
  U extends {
    readonly _tag: string
  } | null,
  const Cases extends {
    readonly [Tag in Exclude<U, null>['_tag']]?: (
      variant: PathAccessor<
        Env,
        Extract<
          Exclude<U, null>,
          {
            readonly _tag: Tag
          }
        >
      >,
    ) => ExprInput<never, unknown>
  },
  const Fallback extends ExprInput<never, unknown>,
>(
  on: PathType<Env, U>,
  cases: Cases & {
    readonly [P in Exclude<keyof Cases, Exclude<U, null>['_tag']>]: never
  },
  otherwise: Fallback,
): ExprType<
  Env &
    UnionToIntersection<
      EnvOfInput<ReturnType<Exclude<Cases[keyof Cases], undefined>>>
    > &
    EnvOfInput<Fallback>,
  | ValueOfInput<ReturnType<Exclude<Cases[keyof Cases], undefined>>>
  | ValueOfInput<Fallback>
>

Partial tagged-union Match with an explicit fallback branch, which handles null and any tag not named in cases.

Expr.matchTagsExhaustive

function · packages/metakit/src/exprMatch.ts:267

function matchTagsExhaustive<
  Env,
  U extends {
    readonly _tag: string
  },
  const Cases extends {
    readonly [Tag in U['_tag']]: (
      variant: PathAccessor<
        Env,
        Extract<
          U,
          {
            readonly _tag: Tag
          }
        >
      >,
    ) => ExprInput<never, unknown>
  },
>(
  on: PathType<Env, U>,
  cases: Cases & {
    readonly [P in Exclude<keyof Cases, U['_tag']>]: never
  },
): ExprType<
  Env & UnionToIntersection<EnvOfInput<ReturnType<Cases[keyof Cases]>>>,
  ValueOfInput<ReturnType<Cases[keyof Cases]>>
>

Exhaustive tagged-union Match over a Path to a union of Schema.TaggedStructs. Each branch receives a narrowed PathAccessor for that variant's payload fields and lowers directly to Node.Match over subject._tag, so JS eval, prepare, residualize, judge, reads, Artifact, and Fn all work without a second AST.

Expr.not

const · packages/metakit/src/expr.ts:117

const not: <X extends ExprInput<never, boolean | null>>(
  value: X,
) => Path.Expr<EnvOfInput<X>, boolean | NullOf<X>>

Logical negation.

Expr.opaque

function · packages/metakit/src/expr.ts:157

function opaque<Env, A>(
  options: {
    readonly name?: string
    readonly reads?: ReadonlyArray<PathType<Env, unknown>>
  },
  run: (env: Env) => A,
): ExprType<Env, A>

First-class escape hatch for arbitrary JavaScript logic.

Declaring reads lets partial evaluation run the function once those paths are known, and lets footprint analyses stay precise. Omitting reads declares Footprint.All (unbounded reads). Every static checker treats an Opaque node soundly as Unknown.

Expr.PartialEnv

type · packages/metakit/src/expr.ts:233

type PartialEnv<Env> =
  Env extends ReadonlyArray<unknown>
    ? Env
    : Env extends object
      ? {
          readonly [K in keyof Env]?: PartialEnv<Env[K]>
        }
      : Env

Partially known environment where any top-level slice or nested field may be omitted.

Expr.PlainLiteral

type · packages/metakit/src/expr.ts:74

type PlainLiteral =
  | string
  | number
  | boolean
  | null
  | readonly PlainLiteral[]
  | {
      readonly [key: string]: PlainLiteral
    }

What lit takes: a string, number, boolean, null, or an array or object type of these. An interface or class (Date, Map, Set, Option) has no index signature, so it is refused at the call.

Expr.ReaderOptions

interface · packages/metakit/src/expr.ts:65

interface ReaderOptions {
  readonly foreign?: ForeignImplementations | undefined
  readonly rewritePolicy?: ForeignRewritePolicy | undefined
}

What evaluation, residualize, judge and every reader that answers from a custom operation's claims (Pairs.commutes, Pairs.idempotent, the Abstract checks, reduceProperties) take besides what they read: the implementations of the foreign operations it calls, by id, and an optional rewritePolicy (Expr.RewritePolicy.trusted or Expr.RewritePolicy.verified(evidence); trusted applies claims unchecked, so a false claim gives wrong answers from every reader here). When rewritePolicy is omitted, no claim is applied. A call with no implementation is refused by evaluation and Unknown to judge.

Expr.reads

function · packages/metakit/src/expr.ts:270

function reads<Env, A>(
  expr: ExprType<Env, A>,
): Option.Option<ReadonlyArray<ReadonlyArray<string>>>

Static read footprint of expr. Returns Option.some(paths) when every read is known, or Option.none() when an Opaque term declares no reads.

Expr.refine

function · packages/metakit/src/exprRules.ts:26

function refine<S extends Schema.Top>(
  build: (
    $: PathAccessor<S['Type'], S['Type']>,
  ) => ExprInput<S['Type'], boolean | null>,
  options?: {
    readonly message?: string
  },
): (schema: S) => S['Rebuild']

Attach a symbolic Expr invariant to an Effect Schema.

Compiles to a real Schema.makeFilter (so Schema.decodeUnknownSync enforces it at runtime) AND stores the Expr Node in the filter's SchemaAST annotations (so SQL, Zone, Z3, and Forms read the AST straight off the Schema).

Expr.Refinement

interface · packages/metakit/src/exprRules.ts:49

interface Refinement<A> {
  readonly at: ReadonlyArray<string>
  readonly expr: ExprType<A, boolean>
  readonly message: Option.Option<string>
}

One rule Expr.rulesOf reads off a Schema.

Expr.REFINEMENT_ANNOTATION_KEY

const · packages/metakit/src/exprRules.ts:16

const REFINEMENT_ANNOTATION_KEY: 'metakit/expr'

Annotation key under which Expr.refine stores its Node on a SchemaAST.Filter.

Expr.refinementsOf

function · packages/metakit/src/exprRules.ts:104

function refinementsOf<S extends Schema.Top>(
  schema: S,
): ReadonlyArray<ExprType<S['Type'], boolean>>

The expressions of Expr.rulesOf, in the same order.

Expr.residualize

function · packages/metakit/src/expr.ts:245

function residualize<Env, A>(
  expr: ExprType<Env, A>,
  partialEnv: NoInfer<PartialEnv<Env>>,
  options?: ReaderOptions,
): ExprType<Env, A>

Partially evaluate expr against a partially known environment, returning the simplified residual Expr. A whole struct read stays open until the environment supplies all declared keys, including optional keys.

Expr.RewritePolicy

const · packages/metakit/src/ops/lawsForeign.ts:188

const RewritePolicy = { trusted, verified, applies, $match, $is }

Constructors and matchers for ForeignRewritePolicy.

Expr.rulesOf

function · packages/metakit/src/exprRules.ts:100

function rulesOf<S extends Schema.Top>(
  schema: S,
): ReadonlyArray<Refinement<S['Type']>>

Read every rule attached to schema, with where it sits and its message: each Expr.refine and each built-in Effect numeric bound (isGreaterThan, isGreaterThanOrEqualTo, isLessThan, isLessThanOrEqualTo, and isBetween, which gives one rule per side), on the schema itself, on nested struct properties, and under Schema.optional, Schema.optionalKey, and Schema.NullOr (guarded with Null.isNull(at) || rule so absent or null values pass). Checks on multi-branch non-nullish unions are not read.

Expr.rulesOfExact

function · packages/metakit/src/exprRules.ts:79

function rulesOfExact<S extends Schema.Top>(schema: S): ExactRules<S['Type']>

Read every rule attached to schema, along with any checks rulesOf could not express as an Expr (such as effect/schema/isInt, custom filters, or checks inside multi-branch non-nullish unions).

Expr.show

function · packages/metakit/src/exprShow.ts:66

function show<Env, A>(expr: ExprType<Env, A>): string

Format an Expr into a readable string for debugging, logs, and diagnostics.

Expr.UnreadCheck

interface · packages/metakit/src/exprRules.ts:59

interface UnreadCheck {
  readonly at: ReadonlyArray<string>
  readonly id: Option.Option<string>
  readonly describe: string
}

One check Expr.rulesOfExact could not express as an Expr.

Expr.when

function · packages/metakit/src/expr.ts:130

function when<
  C extends ExprInput<never, boolean | null>,
  const T extends ExprInput<never, unknown>,
  const E extends ExprInput<never, unknown>,
>(
  cond: C,
  branches: {
    readonly then: T
    readonly else: E
  },
): ExprType<
  EnvOfInput<C> & EnvOfInput<T> & EnvOfInput<E>,
  ValueOfInput<T> | ValueOfInput<E> | NullOf<C>
>

Two-way conditional expression; a null condition gives null.