@entifix/business 0.11.0 → 0.12.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.
@@ -3,7 +3,7 @@ import { Effect, Schema } from 'effect';
3
3
  import type { FragmentCatalog } from '../flow/catalog.js';
4
4
  import type { FragmentKeys } from '../flow/fragment.js';
5
5
  import { type Slip, type SlipSegment } from '../flow/slip.js';
6
- import { type CompositionRefused, type SlipViolation } from '../flow/validate.js';
6
+ import { type CompositionRefused, type FlowRequirementsUnmet, type SlipViolation } from '../flow/validate.js';
7
7
  import { type ResolutionRule, Unresolvable } from '../resolve/resolve.js';
8
8
  import type { VerifiedContext } from '../resolve/verified-context.js';
9
9
  /** A gate over what is known when the flow starts. Never over anything else. */
@@ -63,9 +63,9 @@ export interface ComposeOptions {
63
63
  * the span with `entifix.slip.version` and `entifix.slip.fragments`.
64
64
  *
65
65
  * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never
66
- * a throw. The same context, input and options always give the same slip.
66
+ * a throw; a caller who lacks only what steps require is `FlowRequirementsUnmet`. The same context, input and options always give the same slip.
67
67
  */
68
- export declare const compose: <I>(recipe: Recipe<I>, catalog: FragmentCatalog, context: VerifiedContext, input: unknown, options: ComposeOptions) => Effect.Effect<Slip, CompositionRefused | Unresolvable | Invalid>;
68
+ export declare const compose: <I>(recipe: Recipe<I>, catalog: FragmentCatalog, context: VerifiedContext, input: unknown, options: ComposeOptions) => Effect.Effect<Slip, CompositionRefused | FlowRequirementsUnmet | Unresolvable | Invalid>;
69
69
  /** One axis value, labelled so a report can say which combination broke. */
70
70
  export interface Labelled<T> {
71
71
  readonly label: string;
@@ -80,20 +80,27 @@ export interface CompositionAxes<I> {
80
80
  export interface CompositionOutcome {
81
81
  readonly context: string;
82
82
  readonly input: string;
83
- /** `composed`, `unresolvable` (the caller is offered no variant), or `refused`. */
84
- readonly outcome: 'composed' | 'unresolvable' | 'refused';
83
+ /**
84
+ * `composed`; `unresolvable`, the caller is offered no variant; `unmet`, the
85
+ * caller lacks what a step requires; or `refused`, the slip broke a rule
86
+ * that no caller could repair — a defect.
87
+ */
88
+ readonly outcome: 'composed' | 'unresolvable' | 'unmet' | 'refused';
85
89
  readonly violations: readonly SlipViolation[];
86
90
  }
87
91
  /**
88
92
  * Composes the recipe for every context × input and reports each outcome —
89
93
  * what a CI job runs to prove that every combination a recipe can produce is a
90
94
  * valid slip before it ships. An unresolvable combination is a caller who is
91
- * offered nothing, which is not a defect; a refused one is.
95
+ * offered nothing, and an unmet one a caller who lacks an entitlement, a role
96
+ * or a channel a step requires — neither is a defect, but a host asserts which
97
+ * combinations are which, since a caller wrongly left without an entitlement
98
+ * looks exactly like one rightly refused. A refused combination is a defect.
92
99
  */
93
100
  export declare const enumerateCompositions: <I>(recipe: Recipe<I>, catalog: FragmentCatalog, axes: CompositionAxes<I>) => readonly CompositionOutcome[];
94
101
  /**
95
- * Throws, listing every refused combination, unless all of them composed or
96
- * were unresolvable. Framework-neutral on purpose: any test runner reports a
102
+ * Throws, listing every refused combination, unless all of them composed,
103
+ * were unresolvable or were unmet. Framework-neutral on purpose: any test runner reports a
97
104
  * thrown error.
98
105
  */
99
106
  export declare const expectAllCompositionsValid: (outcomes: readonly CompositionOutcome[]) => void;
@@ -1 +1 @@
1
- {"version":3,"file":"compose.d.ts","sourceRoot":"","sources":["../../src/compose/compose.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,OAAO,EAAE,MAAM,eAAe,CAAC;AACtD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,oBAAoB,CAAC;AAC1D,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EACL,KAAK,IAAI,EAGT,KAAK,WAAW,EAGjB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAEnB,M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AAU,EAAE,SAAS,aAAa,EAAE,CAAC;CAC/C;AAOD;;;;;;;;GAQG;AACH,eAAO,MAAM,qBAAqB,GAAI,CAAC,EACrC,QAAQ,MAAM,CAAC,CAAC,CAAC,EACjB,SAAS,eAAe,EACxB,MAAM,eAAe,CAAC,CAAC,CAAC,KACvB,SAAS,kBAAkB,EAwC3B,CAAC;AAEJ;;;;GAIG;AACH,eAAO,MAAM,0BAA0B,GACrC,UAAU,SAAS,kBAAkB,EAAE,KACtC,IAeF,CAAC"}
@@ -2,7 +2,7 @@ import { _ as _extends } from "@swc/helpers/_/_extends";
2
2
  import { FieldProblem, Invalid } from '@entifix/core';
3
3
  import { Effect, Schema } from 'effect';
4
4
  import { SLIP_VERSION, slipSteps } from '../flow/slip.js';
5
- import { assertValidSlip, validateSlip } from '../flow/validate.js';
5
+ import { assertValidSlip, onlyUnmetRequirements, validateSlip } from '../flow/validate.js';
6
6
  import { dryRun, Unresolvable } from '../resolve/resolve.js';
7
7
  const segmentKey = (segment)=>[
8
8
  segment.vendor,
@@ -85,7 +85,7 @@ const decodeInput = (recipe, input)=>Schema.decodeUnknownEffect(recipe.input)(in
85
85
  * the span with `entifix.slip.version` and `entifix.slip.fragments`.
86
86
  *
87
87
  * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never
88
- * a throw. The same context, input and options always give the same slip.
88
+ * a throw; a caller who lacks only what steps require is `FlowRequirementsUnmet`. The same context, input and options always give the same slip.
89
89
  */ export const compose = (recipe, catalog, context, input, options)=>Effect.gen(function*() {
90
90
  var _recipe_resolve;
91
91
  const decoded = yield* decodeInput(recipe, input);
@@ -109,7 +109,10 @@ const ENUMERATED = {
109
109
  * Composes the recipe for every context × input and reports each outcome —
110
110
  * what a CI job runs to prove that every combination a recipe can produce is a
111
111
  * valid slip before it ships. An unresolvable combination is a caller who is
112
- * offered nothing, which is not a defect; a refused one is.
112
+ * offered nothing, and an unmet one a caller who lacks an entitlement, a role
113
+ * or a channel a step requires — neither is a defect, but a host asserts which
114
+ * combinations are which, since a caller wrongly left without an entitlement
115
+ * looks exactly like one rightly refused. A refused combination is a defect.
113
116
  */ export const enumerateCompositions = (recipe, catalog, axes)=>axes.contexts.flatMap((context)=>axes.inputs.map((input)=>{
114
117
  var _recipe_resolve;
115
118
  const resolved = Effect.runSync(Effect.result(resolutionOf((_recipe_resolve = recipe.resolve) != null ? _recipe_resolve : [], context.value)));
@@ -127,13 +130,13 @@ const ENUMERATED = {
127
130
  return {
128
131
  context: context.label,
129
132
  input: input.label,
130
- outcome: violations.length === 0 ? 'composed' : 'refused',
133
+ outcome: violations.length === 0 ? 'composed' : onlyUnmetRequirements(violations) ? 'unmet' : 'refused',
131
134
  violations
132
135
  };
133
136
  }));
134
137
  /**
135
- * Throws, listing every refused combination, unless all of them composed or
136
- * were unresolvable. Framework-neutral on purpose: any test runner reports a
138
+ * Throws, listing every refused combination, unless all of them composed,
139
+ * were unresolvable or were unmet. Framework-neutral on purpose: any test runner reports a
137
140
  * thrown error.
138
141
  */ export const expectAllCompositionsValid = (outcomes)=>{
139
142
  const refused = outcomes.filter((outcome)=>outcome.outcome === 'refused');
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/compose/compose.ts"],"sourcesContent":["import { FieldProblem, Invalid } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\nimport type { FragmentCatalog } from '../flow/catalog.js';\nimport type { FragmentKeys } from '../flow/fragment.js';\nimport {\n type Slip,\n SLIP_VERSION,\n type SlipResolution,\n type SlipSegment,\n type SlipStep,\n slipSteps,\n} from '../flow/slip.js';\nimport {\n assertValidSlip,\n type CompositionRefused,\n type SlipViolation,\n validateSlip,\n} from '../flow/validate.js';\nimport {\n dryRun,\n type ResolutionRule,\n Unresolvable,\n} from '../resolve/resolve.js';\nimport type { VerifiedContext } from '../resolve/verified-context.js';\n\n/** A gate over what is known when the flow starts. Never over anything else. */\nexport type RecipeGate<I> = (\n context: VerifiedContext,\n input: I,\n segment?: SlipSegment,\n) => boolean;\n\n/** One step of a recipe: a fragment by its pinned reference, as a string. */\nexport interface RecipeStep<I> {\n readonly ref: string;\n /** The step's name in the slip; defaults to the fragment id. */\n readonly step?: string;\n readonly when?: RecipeGate<I>;\n /** Parameters pinned at composition, read from the context's config. */\n readonly parameters?: (\n context: VerifiedContext,\n ) => Readonly<Record<string, unknown>>;\n}\n\n/**\n * One stage of a recipe. A `perSegment` stage is expanded once per segment the\n * start input names — one per vendor, say — each step tagged with its segment\n * and named `<segment key>:<step>`.\n */\nexport interface RecipeStage<I> {\n readonly name: string;\n readonly when?: RecipeGate<I>;\n readonly perSegment?: boolean;\n readonly steps: readonly RecipeStep<I>[];\n}\n\n/** A use case the recipe resolves, recorded on the slip as it was resolved. */\nexport interface RecipeResolution {\n readonly useCase: string;\n readonly rules: readonly ResolutionRule<unknown>[];\n}\n\n/**\n * A named template a slip is composed from. It references fragments by\n * `id@n` strings, never by import, so no domain imports another to take part in\n * a flow.\n */\nexport interface Recipe<I> {\n readonly name: string;\n /** The start input, decoded before anything else is read from it. */\n readonly input: Schema.Codec<I, unknown>;\n /** Keys the start input provides to the first steps, with their schemas. */\n readonly provides?: FragmentKeys;\n /** A checkout needs a commit point even with nothing retriable in it. */\n readonly requiresCommitPoint?: boolean;\n /** The segments a `perSegment` stage expands over. */\n readonly segments?: (input: I) => readonly SlipSegment[];\n readonly resolve?: readonly RecipeResolution[];\n readonly stages: readonly RecipeStage<I>[];\n}\n\n/** What a composition is stamped with: both are inputs, so composing is deterministic. */\nexport interface ComposeOptions {\n readonly flowId: string;\n readonly composedAt: string;\n}\n\nconst segmentKey = (segment: SlipSegment): string =>\n [segment.vendor, segment.paymentMethod].filter(Boolean).join('/');\n\nconst buildStep = <I>(\n recipeStep: RecipeStep<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n segment: SlipSegment | undefined,\n): SlipStep => {\n const fragment = catalog.get(recipeStep.ref);\n const name = recipeStep.step ?? fragment?.id ?? recipeStep.ref;\n const parameters = recipeStep.parameters?.(context);\n return {\n ref: recipeStep.ref,\n step: segment === undefined ? name : `${segmentKey(segment)}:${name}`,\n cardinality: fragment?.cardinality ?? 'one',\n ...(segment === undefined ? {} : { segment }),\n ...(fragment?.participant === undefined\n ? {}\n : { participant: fragment.participant }),\n ...(fragment?.call === undefined ? {} : { call: fragment.call }),\n ...(fragment?.compensation === undefined\n ? {}\n : { compensation: fragment.compensation }),\n ...(parameters === undefined ? {} : { parameters }),\n };\n};\n\nconst resolutionOf = (\n resolutions: readonly RecipeResolution[],\n context: VerifiedContext,\n): Effect.Effect<readonly SlipResolution[], Unresolvable> =>\n Effect.forEach(resolutions, ({ useCase, rules }) => {\n const chosen = dryRun(rules, context);\n return chosen === undefined\n ? Effect.fail(new Unresolvable({ useCase }))\n : Effect.succeed({ useCase, variant: chosen.variant, rule: chosen.rule });\n });\n\n/** Expands the recipe into an unvalidated slip. */\nconst draft = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: I,\n resolution: readonly SlipResolution[],\n options: ComposeOptions,\n): Slip => {\n const segments = recipe.segments?.(input) ?? [];\n const stages = recipe.stages\n .filter(stage => stage.when?.(context, input) ?? true)\n .map(stage => {\n const each: readonly (SlipSegment | undefined)[] =\n stage.perSegment === true ? segments : [undefined];\n return {\n name: stage.name,\n steps: each.flatMap(segment =>\n stage.steps\n .filter(\n recipeStep => recipeStep.when?.(context, input, segment) ?? true,\n )\n .map(recipeStep =>\n buildStep(recipeStep, catalog, context, segment),\n ),\n ),\n };\n })\n .filter(stage => stage.steps.length > 0);\n return {\n slipVersion: SLIP_VERSION,\n flowId: options.flowId,\n recipe: recipe.name,\n ...(recipe.requiresCommitPoint === undefined\n ? {}\n : { requiresCommitPoint: recipe.requiresCommitPoint }),\n stages,\n resolution,\n composedAt: options.composedAt,\n };\n};\n\nconst decodeInput = <I>(recipe: Recipe<I>, input: unknown) =>\n Schema.decodeUnknownEffect(recipe.input)(input).pipe(\n Effect.mapError(\n error =>\n new Invalid({\n errors: [\n FieldProblem.make({\n pointer: '',\n detail: error.message,\n code: 'invalidFlowInput',\n }),\n ],\n }),\n ),\n );\n\n/**\n * Composes a recipe into a pinned, validated slip for one caller: decodes the\n * start input, resolves the recipe's use cases, expands per-segment stages,\n * pins versions and parameters, stamps `slipVersion`, validates, and annotates\n * the span with `entifix.slip.version` and `entifix.slip.fragments`.\n *\n * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never\n * a throw. The same context, input and options always give the same slip.\n */\nexport const compose = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: unknown,\n options: ComposeOptions,\n): Effect.Effect<Slip, CompositionRefused | Unresolvable | Invalid> =>\n Effect.gen(function* () {\n const decoded = yield* decodeInput(recipe, input);\n const resolution = yield* resolutionOf(recipe.resolve ?? [], context);\n const slip = yield* assertValidSlip(\n draft(recipe, catalog, context, decoded, resolution, options),\n catalog,\n {\n context,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n yield* Effect.annotateCurrentSpan({\n 'entifix.slip.version': slip.slipVersion,\n 'entifix.slip.fragments': slipSteps(slip)\n .map(step => step.ref)\n .join(','),\n });\n return slip;\n });\n\n/** One axis value, labelled so a report can say which combination broke. */\nexport interface Labelled<T> {\n readonly label: string;\n readonly value: T;\n}\n\n/** The axes a recipe is enumerated over. */\nexport interface CompositionAxes<I> {\n readonly contexts: readonly Labelled<VerifiedContext>[];\n readonly inputs: readonly Labelled<I>[];\n}\n\n/** How one combination composed. */\nexport interface CompositionOutcome {\n readonly context: string;\n readonly input: string;\n /** `composed`, `unresolvable` (the caller is offered no variant), or `refused`. */\n readonly outcome: 'composed' | 'unresolvable' | 'refused';\n readonly violations: readonly SlipViolation[];\n}\n\nconst ENUMERATED: ComposeOptions = {\n flowId: 'enumerated',\n composedAt: '1970-01-01T00:00:00.000Z',\n};\n\n/**\n * Composes the recipe for every context × input and reports each outcome —\n * what a CI job runs to prove that every combination a recipe can produce is a\n * valid slip before it ships. An unresolvable combination is a caller who is\n * offered nothing, which is not a defect; a refused one is.\n */\nexport const enumerateCompositions = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n axes: CompositionAxes<I>,\n): readonly CompositionOutcome[] =>\n axes.contexts.flatMap(context =>\n axes.inputs.map(input => {\n const resolved = Effect.runSync(\n Effect.result(resolutionOf(recipe.resolve ?? [], context.value)),\n );\n if (resolved._tag === 'Failure')\n return {\n context: context.label,\n input: input.label,\n outcome: 'unresolvable' as const,\n violations: [],\n };\n const violations = validateSlip(\n draft(\n recipe,\n catalog,\n context.value,\n input.value,\n resolved.success,\n ENUMERATED,\n ),\n catalog,\n {\n context: context.value,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n return {\n context: context.label,\n input: input.label,\n outcome:\n violations.length === 0\n ? ('composed' as const)\n : ('refused' as const),\n violations,\n };\n }),\n );\n\n/**\n * Throws, listing every refused combination, unless all of them composed or\n * were unresolvable. Framework-neutral on purpose: any test runner reports a\n * thrown error.\n */\nexport const expectAllCompositionsValid = (\n outcomes: readonly CompositionOutcome[],\n): void => {\n const refused = outcomes.filter(outcome => outcome.outcome === 'refused');\n if (refused.length > 0)\n throw new Error(\n `${String(refused.length)} composition(s) are not valid slips:\\n` +\n refused\n .map(\n outcome =>\n ` ${outcome.context} × ${outcome.input}: ` +\n outcome.violations\n .map(violation => `${violation.tag} (${violation.detail})`)\n .join('; '),\n )\n .join('\\n'),\n );\n};\n"],"names":["FieldProblem","Invalid","Effect","Schema","SLIP_VERSION","slipSteps","assertValidSlip","validateSlip","dryRun","Unresolvable","segmentKey","segment","vendor","paymentMethod","filter","Boolean","join","buildStep","recipeStep","catalog","context","fragment","get","ref","name","step","id","parameters","undefined","cardinality","participant","call","compensation","resolutionOf","resolutions","forEach","useCase","rules","chosen","fail","succeed","variant","rule","draft","recipe","input","resolution","options","segments","stages","stage","when","map","each","perSegment","steps","flatMap","length","slipVersion","flowId","requiresCommitPoint","composedAt","decodeInput","decodeUnknownEffect","pipe","mapError","error","errors","make","pointer","detail","message","code","compose","gen","decoded","resolve","slip","provides","start","annotateCurrentSpan","ENUMERATED","enumerateCompositions","axes","contexts","inputs","resolved","runSync","result","value","_tag","label","outcome","violations","success","expectAllCompositionsValid","outcomes","refused","Error","String","violation","tag"],"mappings":";AAAA,SAASA,YAAY,EAAEC,OAAO,QAAQ,gBAAgB;AACtD,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAIxC,SAEEC,YAAY,EAIZC,SAAS,QACJ,kBAAkB;AACzB,SACEC,eAAe,EAGfC,YAAY,QACP,sBAAsB;AAC7B,SACEC,MAAM,EAENC,YAAY,QACP,wBAAwB;AAiE/B,MAAMC,aAAa,CAACC,UAClB;QAACA,QAAQC,MAAM;QAAED,QAAQE,aAAa;KAAC,CAACC,MAAM,CAACC,SAASC,IAAI,CAAC;AAE/D,MAAMC,YAAY,CAChBC,YACAC,SACAC,SACAT;QAGaO,MAAAA;IADb,MAAMG,WAAWF,QAAQG,GAAG,CAACJ,WAAWK,GAAG;IAC3C,MAAMC,QAAON,QAAAA,mBAAAA,WAAWO,IAAI,YAAfP,mBAAmBG,4BAAAA,SAAUK,EAAE,YAA/BR,OAAmCA,WAAWK,GAAG;IAC9D,MAAMI,aAAaT,WAAWS,UAAU,oBAArBT,WAAWS,UAAU,MAArBT,YAAwBE;IAC3C,OAAO;QACLG,KAAKL,WAAWK,GAAG;QACnBE,MAAMd,YAAYiB,YAAYJ,OAAO,GAAGd,WAAWC,SAAS,CAAC,EAAEa,MAAM;QACrEK,WAAW,WAAER,4BAAAA,SAAUQ,WAAW,oBAAI;OAClClB,YAAYiB,YAAY,CAAC,IAAI;QAAEjB;IAAQ,GACvCU,CAAAA,4BAAAA,SAAUS,WAAW,MAAKF,YAC1B,CAAC,IACD;QAAEE,aAAaT,SAASS,WAAW;IAAC,GACpCT,CAAAA,4BAAAA,SAAUU,IAAI,MAAKH,YAAY,CAAC,IAAI;QAAEG,MAAMV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,YAAa,GAAGA,UAAUC,GAAG,CAAC,EAAE,EAAED,UAAU9B,MAAM,CAAC,CAAC,CAAC,EACzDtD,IAAI,CAAC,OAEXA,IAAI,CAAC;AAEhB,EAAE"}
1
+ {"version":3,"sources":["../../src/compose/compose.ts"],"sourcesContent":["import { FieldProblem, Invalid } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\nimport type { FragmentCatalog } from '../flow/catalog.js';\nimport type { FragmentKeys } from '../flow/fragment.js';\nimport {\n type Slip,\n SLIP_VERSION,\n type SlipResolution,\n type SlipSegment,\n type SlipStep,\n slipSteps,\n} from '../flow/slip.js';\nimport {\n assertValidSlip,\n type CompositionRefused,\n type FlowRequirementsUnmet,\n onlyUnmetRequirements,\n type SlipViolation,\n validateSlip,\n} from '../flow/validate.js';\nimport {\n dryRun,\n type ResolutionRule,\n Unresolvable,\n} from '../resolve/resolve.js';\nimport type { VerifiedContext } from '../resolve/verified-context.js';\n\n/** A gate over what is known when the flow starts. Never over anything else. */\nexport type RecipeGate<I> = (\n context: VerifiedContext,\n input: I,\n segment?: SlipSegment,\n) => boolean;\n\n/** One step of a recipe: a fragment by its pinned reference, as a string. */\nexport interface RecipeStep<I> {\n readonly ref: string;\n /** The step's name in the slip; defaults to the fragment id. */\n readonly step?: string;\n readonly when?: RecipeGate<I>;\n /** Parameters pinned at composition, read from the context's config. */\n readonly parameters?: (\n context: VerifiedContext,\n ) => Readonly<Record<string, unknown>>;\n}\n\n/**\n * One stage of a recipe. A `perSegment` stage is expanded once per segment the\n * start input names — one per vendor, say — each step tagged with its segment\n * and named `<segment key>:<step>`.\n */\nexport interface RecipeStage<I> {\n readonly name: string;\n readonly when?: RecipeGate<I>;\n readonly perSegment?: boolean;\n readonly steps: readonly RecipeStep<I>[];\n}\n\n/** A use case the recipe resolves, recorded on the slip as it was resolved. */\nexport interface RecipeResolution {\n readonly useCase: string;\n readonly rules: readonly ResolutionRule<unknown>[];\n}\n\n/**\n * A named template a slip is composed from. It references fragments by\n * `id@n` strings, never by import, so no domain imports another to take part in\n * a flow.\n */\nexport interface Recipe<I> {\n readonly name: string;\n /** The start input, decoded before anything else is read from it. */\n readonly input: Schema.Codec<I, unknown>;\n /** Keys the start input provides to the first steps, with their schemas. */\n readonly provides?: FragmentKeys;\n /** A checkout needs a commit point even with nothing retriable in it. */\n readonly requiresCommitPoint?: boolean;\n /** The segments a `perSegment` stage expands over. */\n readonly segments?: (input: I) => readonly SlipSegment[];\n readonly resolve?: readonly RecipeResolution[];\n readonly stages: readonly RecipeStage<I>[];\n}\n\n/** What a composition is stamped with: both are inputs, so composing is deterministic. */\nexport interface ComposeOptions {\n readonly flowId: string;\n readonly composedAt: string;\n}\n\nconst segmentKey = (segment: SlipSegment): string =>\n [segment.vendor, segment.paymentMethod].filter(Boolean).join('/');\n\nconst buildStep = <I>(\n recipeStep: RecipeStep<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n segment: SlipSegment | undefined,\n): SlipStep => {\n const fragment = catalog.get(recipeStep.ref);\n const name = recipeStep.step ?? fragment?.id ?? recipeStep.ref;\n const parameters = recipeStep.parameters?.(context);\n return {\n ref: recipeStep.ref,\n step: segment === undefined ? name : `${segmentKey(segment)}:${name}`,\n cardinality: fragment?.cardinality ?? 'one',\n ...(segment === undefined ? {} : { segment }),\n ...(fragment?.participant === undefined\n ? {}\n : { participant: fragment.participant }),\n ...(fragment?.call === undefined ? {} : { call: fragment.call }),\n ...(fragment?.compensation === undefined\n ? {}\n : { compensation: fragment.compensation }),\n ...(parameters === undefined ? {} : { parameters }),\n };\n};\n\nconst resolutionOf = (\n resolutions: readonly RecipeResolution[],\n context: VerifiedContext,\n): Effect.Effect<readonly SlipResolution[], Unresolvable> =>\n Effect.forEach(resolutions, ({ useCase, rules }) => {\n const chosen = dryRun(rules, context);\n return chosen === undefined\n ? Effect.fail(new Unresolvable({ useCase }))\n : Effect.succeed({ useCase, variant: chosen.variant, rule: chosen.rule });\n });\n\n/** Expands the recipe into an unvalidated slip. */\nconst draft = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: I,\n resolution: readonly SlipResolution[],\n options: ComposeOptions,\n): Slip => {\n const segments = recipe.segments?.(input) ?? [];\n const stages = recipe.stages\n .filter(stage => stage.when?.(context, input) ?? true)\n .map(stage => {\n const each: readonly (SlipSegment | undefined)[] =\n stage.perSegment === true ? segments : [undefined];\n return {\n name: stage.name,\n steps: each.flatMap(segment =>\n stage.steps\n .filter(\n recipeStep => recipeStep.when?.(context, input, segment) ?? true,\n )\n .map(recipeStep =>\n buildStep(recipeStep, catalog, context, segment),\n ),\n ),\n };\n })\n .filter(stage => stage.steps.length > 0);\n return {\n slipVersion: SLIP_VERSION,\n flowId: options.flowId,\n recipe: recipe.name,\n ...(recipe.requiresCommitPoint === undefined\n ? {}\n : { requiresCommitPoint: recipe.requiresCommitPoint }),\n stages,\n resolution,\n composedAt: options.composedAt,\n };\n};\n\nconst decodeInput = <I>(recipe: Recipe<I>, input: unknown) =>\n Schema.decodeUnknownEffect(recipe.input)(input).pipe(\n Effect.mapError(\n error =>\n new Invalid({\n errors: [\n FieldProblem.make({\n pointer: '',\n detail: error.message,\n code: 'invalidFlowInput',\n }),\n ],\n }),\n ),\n );\n\n/**\n * Composes a recipe into a pinned, validated slip for one caller: decodes the\n * start input, resolves the recipe's use cases, expands per-segment stages,\n * pins versions and parameters, stamps `slipVersion`, validates, and annotates\n * the span with `entifix.slip.version` and `entifix.slip.fragments`.\n *\n * An unknown `id@n` is a `CompositionRefused` carrying `UnknownFragment`, never\n * a throw; a caller who lacks only what steps require is `FlowRequirementsUnmet`. The same context, input and options always give the same slip.\n */\nexport const compose = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n context: VerifiedContext,\n input: unknown,\n options: ComposeOptions,\n): Effect.Effect<\n Slip,\n CompositionRefused | FlowRequirementsUnmet | Unresolvable | Invalid\n> =>\n Effect.gen(function* () {\n const decoded = yield* decodeInput(recipe, input);\n const resolution = yield* resolutionOf(recipe.resolve ?? [], context);\n const slip = yield* assertValidSlip(\n draft(recipe, catalog, context, decoded, resolution, options),\n catalog,\n {\n context,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n yield* Effect.annotateCurrentSpan({\n 'entifix.slip.version': slip.slipVersion,\n 'entifix.slip.fragments': slipSteps(slip)\n .map(step => step.ref)\n .join(','),\n });\n return slip;\n });\n\n/** One axis value, labelled so a report can say which combination broke. */\nexport interface Labelled<T> {\n readonly label: string;\n readonly value: T;\n}\n\n/** The axes a recipe is enumerated over. */\nexport interface CompositionAxes<I> {\n readonly contexts: readonly Labelled<VerifiedContext>[];\n readonly inputs: readonly Labelled<I>[];\n}\n\n/** How one combination composed. */\nexport interface CompositionOutcome {\n readonly context: string;\n readonly input: string;\n /**\n * `composed`; `unresolvable`, the caller is offered no variant; `unmet`, the\n * caller lacks what a step requires; or `refused`, the slip broke a rule\n * that no caller could repair — a defect.\n */\n readonly outcome: 'composed' | 'unresolvable' | 'unmet' | 'refused';\n readonly violations: readonly SlipViolation[];\n}\n\nconst ENUMERATED: ComposeOptions = {\n flowId: 'enumerated',\n composedAt: '1970-01-01T00:00:00.000Z',\n};\n\n/**\n * Composes the recipe for every context × input and reports each outcome —\n * what a CI job runs to prove that every combination a recipe can produce is a\n * valid slip before it ships. An unresolvable combination is a caller who is\n * offered nothing, and an unmet one a caller who lacks an entitlement, a role\n * or a channel a step requires — neither is a defect, but a host asserts which\n * combinations are which, since a caller wrongly left without an entitlement\n * looks exactly like one rightly refused. A refused combination is a defect.\n */\nexport const enumerateCompositions = <I>(\n recipe: Recipe<I>,\n catalog: FragmentCatalog,\n axes: CompositionAxes<I>,\n): readonly CompositionOutcome[] =>\n axes.contexts.flatMap(context =>\n axes.inputs.map(input => {\n const resolved = Effect.runSync(\n Effect.result(resolutionOf(recipe.resolve ?? [], context.value)),\n );\n if (resolved._tag === 'Failure')\n return {\n context: context.label,\n input: input.label,\n outcome: 'unresolvable' as const,\n violations: [],\n };\n const violations = validateSlip(\n draft(\n recipe,\n catalog,\n context.value,\n input.value,\n resolved.success,\n ENUMERATED,\n ),\n catalog,\n {\n context: context.value,\n ...(recipe.provides === undefined ? {} : { start: recipe.provides }),\n },\n );\n return {\n context: context.label,\n input: input.label,\n outcome:\n violations.length === 0\n ? ('composed' as const)\n : onlyUnmetRequirements(violations)\n ? ('unmet' as const)\n : ('refused' as const),\n violations,\n };\n }),\n );\n\n/**\n * Throws, listing every refused combination, unless all of them composed,\n * were unresolvable or were unmet. Framework-neutral on purpose: any test runner reports a\n * thrown error.\n */\nexport const expectAllCompositionsValid = (\n outcomes: readonly CompositionOutcome[],\n): void => {\n const refused = outcomes.filter(outcome => outcome.outcome === 'refused');\n if (refused.length > 0)\n throw new Error(\n `${String(refused.length)} composition(s) are not valid slips:\\n` +\n refused\n .map(\n outcome =>\n ` ${outcome.context} × ${outcome.input}: ` +\n outcome.violations\n .map(violation => `${violation.tag} (${violation.detail})`)\n .join('; '),\n )\n .join('\\n'),\n );\n};\n"],"names":["FieldProblem","Invalid","Effect","Schema","SLIP_VERSION","slipSteps","assertValidSlip","onlyUnmetRequirements","validateSlip","dryRun","Unresolvable","segmentKey","segment","vendor","paymentMethod","filter","Boolean","join","buildStep","recipeStep","catalog","context","fragment","get","ref","name","step","id","parameters","undefined","cardinality","participant","call","compensation","resolutionOf","resolutions","forEach","useCase","rules","chosen","fail","succeed","variant","rule","draft","recipe","input","resolution","options","segments","stages","stage","when","map","each","perSegment","steps","flatMap","length","slipVersion","flowId","requiresCommitPoint","composedAt","decodeInput","decodeUnknownEffect","pipe","mapError","error","errors","make","pointer","detail","message","code","compose","gen","decoded","resolve","slip","provides","start","annotateCurrentSpan","ENUMERATED","enumerateCompositions","axes","contexts","inputs","resolved","runSync","result","value","_tag","label","outcome","violations","success","expectAllCompositionsValid","outcomes","refused","Error","String","violation","tag"],"mappings":";AAAA,SAASA,YAAY,EAAEC,OAAO,QAAQ,gBAAgB;AACtD,SAASC,MA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AO,YAAdhC,kBAAkB,EAAE,EAAExB,QAAQqE,KAAK;YAEhE,IAAIH,SAASI,IAAI,KAAK,WACpB,OAAO;gBACLtE,SAASA,QAAQuE,KAAK;gBACtB9C,OAAOA,MAAM8C,KAAK;gBAClBC,SAAS;gBACTC,YAAY,EAAE;YAChB;YACF,MAAMA,aAAatF,aACjBoC,MACEC,QACAzB,SACAC,QAAQqE,KAAK,EACb5C,MAAM4C,KAAK,EACXH,SAASQ,OAAO,EAChBb,aAEF9D,SACA;gBACEC,SAASA,QAAQqE,KAAK;eAClB7C,OAAOkC,QAAQ,KAAKlD,YAAY,CAAC,IAAI;gBAAEmD,OAAOnC,OAAOkC,QAAQ;YAAC;YAGtE,OAAO;gBACL1D,SAASA,QAAQuE,KAAK;gBACtB9C,OAAOA,MAAM8C,KAAK;gBAClBC,SACEC,WAAWpC,MAAM,KAAK,IACjB,aACDnD,sBAAsBuF,cACnB,UACA;gBACTA;YACF;QACF,IACA;AAEJ;;;;CAIC,GACD,OAAO,MAAME,6BAA6B,CACxCC;IAEA,MAAMC,UAAUD,SAASlF,MAAM,CAAC8E,CAAAA,UAAWA,QAAQA,OAAO,KAAK;IAC/D,IAAIK,QAAQxC,MAAM,GAAG,GACnB,MAAM,IAAIyC,MACR,GAAGC,OAAOF,QAAQxC,MAAM,EAAE,sCAAsC,CAAC,GAC/DwC,QACG7C,GAAG,CACFwC,CAAAA,UACE,CAAC,EAAE,EAAEA,QAAQxE,OAAO,CAAC,GAAG,EAAEwE,QAAQ/C,KAAK,CAAC,EAAE,CAAC,GAC3C+C,QAAQC,UAAU,CACfzC,GAAG,CAACgD,CAAAA,YAAa,GAAGA,UAAUC,GAAG,CAAC,EAAE,EAAED,UAAU9B,MAAM,CAAC,CAAC,CAAC,EACzDtD,IAAI,CAAC,OAEXA,IAAI,CAAC;AAEhB,EAAE"}
@@ -0,0 +1,137 @@
1
+ import { type EndpointIdempotency, type EndpointSchema, type EntifixEnvelopeLink, type EntifixFailure, type Entity, type EntityConstructor, type EntityId, type FailureClass, type FilterGroup, type MetaUseCase, type UseCaseConstructor } from '@entifix/core';
2
+ import type { Effect } from 'effect';
3
+ import type { RequestPrincipal } from '../request/request-context.js';
4
+ import type { ResolutionRule } from '../resolve/resolve.js';
5
+ import type { VerifiedContext } from '../resolve/verified-context.js';
6
+ /** The five generic verbs an entity's endpoints can serve. */
7
+ export type EntityApiVerb = 'list' | 'get' | 'create' | 'update' | 'delete';
8
+ /**
9
+ * Who may reach an entity's endpoints. The permission is derived from the
10
+ * entity and the verb, so it is never written here.
11
+ */
12
+ export type EntityApiGuard = {
13
+ readonly kind: 'public';
14
+ } | {
15
+ readonly kind: 'permission';
16
+ } | {
17
+ readonly kind: 'organization';
18
+ } | {
19
+ readonly kind: 'crossing';
20
+ readonly organization: boolean;
21
+ };
22
+ /** The affordances an entity's endpoints derive from the verbs they serve. */
23
+ export interface EntityApiLinks {
24
+ readonly record: (id: EntityId) => EntifixEnvelopeLink[];
25
+ readonly collection: () => EntifixEnvelopeLink[];
26
+ }
27
+ /** What a `prepare`, an override or a verb knows about the caller. */
28
+ export interface EntityApiContext {
29
+ readonly organizationId?: string;
30
+ readonly principal?: RequestPrincipal;
31
+ readonly verified?: VerifiedContext;
32
+ readonly links: EntityApiLinks;
33
+ }
34
+ /** What an override's handler receives: the decoded parts of its request. */
35
+ export interface EntityApiRequest {
36
+ readonly params?: {
37
+ readonly id?: string;
38
+ };
39
+ readonly payload?: unknown;
40
+ }
41
+ /**
42
+ * Which records of an entity a caller may see: every one, none, or those a
43
+ * filter keeps ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).
44
+ * A filter is conjoined onto the load request, so a query string can only
45
+ * narrow it further and no `or` in it can escape.
46
+ */
47
+ export type Narrowing<T extends Entity> = 'unscoped' | 'nothing' | FilterGroup<T>;
48
+ /**
49
+ * A read's narrowing as ordered resolver rules over the verified context: the
50
+ * first variant the caller is entitled to and whose predicate holds builds the
51
+ * narrowing. A caller no rule matches sees **nothing** — the direction a
52
+ * missing rule must fail in.
53
+ */
54
+ export type NarrowingRules<T extends Entity> = readonly ResolutionRule<(context: VerifiedContext) => Narrowing<T>>[];
55
+ /**
56
+ * One verb served by a handler of the host's instead of the generic one. It
57
+ * keeps the group's path and links, and may change the guard, the payload,
58
+ * the failures and the idempotency the verb declares.
59
+ */
60
+ export interface EntityVerbOverride<R> {
61
+ readonly guard?: EntityApiGuard;
62
+ readonly idempotent?: EndpointIdempotency;
63
+ readonly errors?: readonly FailureClass[];
64
+ /** The body the verb takes instead of an entity envelope. */
65
+ readonly payload?: EndpointSchema;
66
+ readonly handler: (request: EntityApiRequest, context: EntityApiContext) => Effect.Effect<unknown, EntifixFailure, R>;
67
+ }
68
+ /**
69
+ * A `@useCase()` verb's endpoint: its path, method, permission and contract
70
+ * come from the declaration, and only who may call it and what it does are
71
+ * written here.
72
+ */
73
+ export interface VerbEndpoint<R> {
74
+ readonly useCase: MetaUseCase;
75
+ /** Defaults to the group's write guard. */
76
+ readonly guard?: EntityApiGuard;
77
+ readonly idempotent?: EndpointIdempotency;
78
+ readonly handler: (request: EntityApiRequest, context: EntityApiContext) => Effect.Effect<unknown, EntifixFailure, R>;
79
+ /**
80
+ * The same verb over a selection, for a record-bound verb that also sits in
81
+ * a collection cell (`alsoAt`): one permission for one act, whether it is
82
+ * asked of a record or of twenty. Required exactly when that cell is
83
+ * declared; its request carries the selection as its payload.
84
+ */
85
+ readonly bulk?: (request: EntityApiRequest, context: EntityApiContext) => Effect.Effect<unknown, EntifixFailure, R>;
86
+ }
87
+ /** Serve a `@useCase()` class's verb on its entity's endpoints. */
88
+ export declare const verbEndpoint: <const O extends Omit<VerbEndpoint<any>, "useCase">>(useCaseClass: UseCaseConstructor, options: O) => O & {
89
+ readonly useCase: MetaUseCase;
90
+ };
91
+ /** What an entity's endpoints serve, and under which rules. */
92
+ export interface EntityApiOptions<T extends Entity, R> {
93
+ readonly verbs: readonly EntityApiVerb[];
94
+ /** One guard for every verb, or one for the reads and one for the writes. */
95
+ readonly guard: EntityApiGuard | {
96
+ readonly read: EntityApiGuard;
97
+ readonly write: EntityApiGuard;
98
+ };
99
+ /** Narrows the reads, and the facet counts, to what this caller may see. */
100
+ readonly narrowing?: NarrowingRules<T>;
101
+ /** Serve `$facets` beside the list, under the list's guard and narrowing. */
102
+ readonly facets?: boolean;
103
+ /** Runs on every generic create and update, before the save. */
104
+ readonly prepare?: (entity: T, context: EntityApiContext & {
105
+ readonly verb: 'create' | 'update';
106
+ }) => Effect.Effect<T, EntifixFailure, R>;
107
+ /** The business failures `prepare` may answer with, for the contract. */
108
+ readonly errors?: readonly FailureClass[];
109
+ readonly override?: Partial<Record<EntityApiVerb, EntityVerbOverride<R>>>;
110
+ /**
111
+ * The entity's `@useCase()` verbs, one endpoint each. Every verb the entity
112
+ * declares must be here and none another entity declares, or serving the
113
+ * declaration throws.
114
+ */
115
+ readonly useCases?: readonly VerbEndpoint<R>[];
116
+ }
117
+ /**
118
+ * An entity's endpoints as a value: which verbs, behind which guards, with
119
+ * which handlers. Declaring them needs no HTTP — a domain's cell declares, and
120
+ * the shell serves the declaration with `entityApi`
121
+ * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
122
+ */
123
+ export interface EntityApiDeclaration<T extends Entity, K extends string, O extends EntityApiOptions<T, any>> {
124
+ readonly entity: EntityConstructor<T>;
125
+ readonly key: K;
126
+ readonly options: O;
127
+ }
128
+ /** `O`, with every key `Shape` does not name typed `never`. */
129
+ type Exact<O, Shape> = O & Record<Exclude<keyof O, keyof Shape>, never>;
130
+ /**
131
+ * Declare an entity's endpoints, to be served by the shell. An option the
132
+ * declaration does not know is a compile error rather than a value nobody
133
+ * reads — `compositions` included, which the shell adds when it serves.
134
+ */
135
+ export declare const defineEntityApi: <T extends Entity, const K extends string, const O extends EntityApiOptions<T, any>>(entity: EntityConstructor<T>, key: K, options: Exact<O, EntityApiOptions<T, any>>) => EntityApiDeclaration<T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,CAAC,CAAC,KAC1C,oBAAoB,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,CAA+B,CAAC"}
@@ -0,0 +1,17 @@
1
+ import { _ as _extends } from "@swc/helpers/_/_extends";
2
+ import { extractUseCase } from '@entifix/core';
3
+ /** Serve a `@useCase()` class's verb on its entity's endpoints. */ export const verbEndpoint = (useCaseClass, options)=>_extends({}, options, {
4
+ useCase: extractUseCase(useCaseClass)
5
+ });
6
+ /**
7
+ * Declare an entity's endpoints, to be served by the shell. An option the
8
+ * declaration does not know is a compile error rather than a value nobody
9
+ * reads — `compositions` included, which the shell adds when it serves.
10
+ */ export const defineEntityApi = (entity, key, // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options
11
+ options)=>({
12
+ entity,
13
+ key,
14
+ options
15
+ });
16
+
17
+ //# sourceMappingURL=entity-api.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/entity-api/entity-api.ts"],"sourcesContent":["import {\n type EndpointIdempotency,\n type EndpointSchema,\n type EntifixEnvelopeLink,\n type EntifixFailure,\n type Entity,\n type EntityConstructor,\n type EntityId,\n extractUseCase,\n type FailureClass,\n type FilterGroup,\n type MetaUseCase,\n type UseCaseConstructor,\n} from '@entifix/core';\nimport type { Effect } from 'effect';\n\nimport type { RequestPrincipal } from '../request/request-context.js';\nimport type { ResolutionRule } from '../resolve/resolve.js';\nimport type { VerifiedContext } from '../resolve/verified-context.js';\n\n/** The five generic verbs an entity's endpoints can serve. */\nexport type EntityApiVerb = 'list' | 'get' | 'create' | 'update' | 'delete';\n\n/**\n * Who may reach an entity's endpoints. The permission is derived from the\n * entity and the verb, so it is never written here.\n */\nexport type EntityApiGuard =\n | { readonly kind: 'public' }\n | { readonly kind: 'permission' }\n | { readonly kind: 'organization' }\n | { readonly kind: 'crossing'; readonly organization: boolean };\n\n/** The affordances an entity's endpoints derive from the verbs they serve. */\nexport interface EntityApiLinks {\n readonly record: (id: EntityId) => EntifixEnvelopeLink[];\n readonly collection: () => EntifixEnvelopeLink[];\n}\n\n/** What a `prepare`, an override or a verb knows about the caller. */\nexport interface EntityApiContext {\n readonly organizationId?: string;\n readonly principal?: RequestPrincipal;\n readonly verified?: VerifiedContext;\n readonly links: EntityApiLinks;\n}\n\n/** What an override's handler receives: the decoded parts of its request. */\nexport interface EntityApiRequest {\n readonly params?: { readonly id?: string };\n readonly payload?: unknown;\n}\n\n/**\n * Which records of an entity a caller may see: every one, none, or those a\n * filter keeps ([ADR 0015](../../../../../docs/adr/0015-composed-flows-and-use-case-resolution.md)).\n * A filter is conjoined onto the load request, so a query string can only\n * narrow it further and no `or` in it can escape.\n */\nexport type Narrowing<T extends Entity> =\n 'unscoped' | 'nothing' | FilterGroup<T>;\n\n/**\n * A read's narrowing as ordered resolver rules over the verified context: the\n * first variant the caller is entitled to and whose predicate holds builds the\n * narrowing. A caller no rule matches sees **nothing** — the direction a\n * missing rule must fail in.\n */\nexport type NarrowingRules<T extends Entity> = readonly ResolutionRule<\n (context: VerifiedContext) => Narrowing<T>\n>[];\n\n/**\n * One verb served by a handler of the host's instead of the generic one. It\n * keeps the group's path and links, and may change the guard, the payload,\n * the failures and the idempotency the verb declares.\n */\nexport interface EntityVerbOverride<R> {\n readonly guard?: EntityApiGuard;\n readonly idempotent?: EndpointIdempotency;\n readonly errors?: readonly FailureClass[];\n /** The body the verb takes instead of an entity envelope. */\n readonly payload?: EndpointSchema;\n readonly handler: (\n request: EntityApiRequest,\n context: EntityApiContext,\n ) => Effect.Effect<unknown, EntifixFailure, R>;\n}\n\n/**\n * A `@useCase()` verb's endpoint: its path, method, permission and contract\n * come from the declaration, and only who may call it and what it does are\n * written here.\n */\nexport interface VerbEndpoint<R> {\n readonly useCase: MetaUseCase;\n /** Defaults to the group's write guard. */\n readonly guard?: EntityApiGuard;\n readonly idempotent?: EndpointIdempotency;\n readonly handler: (\n request: EntityApiRequest,\n context: EntityApiContext,\n ) => Effect.Effect<unknown, EntifixFailure, R>;\n /**\n * The same verb over a selection, for a record-bound verb that also sits in\n * a collection cell (`alsoAt`): one permission for one act, whether it is\n * asked of a record or of twenty. Required exactly when that cell is\n * declared; its request carries the selection as its payload.\n */\n readonly bulk?: (\n request: EntityApiRequest,\n context: EntityApiContext,\n ) => Effect.Effect<unknown, EntifixFailure, R>;\n}\n\n/** Serve a `@useCase()` class's verb on its entity's endpoints. */\nexport const verbEndpoint = <\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n const O extends Omit<VerbEndpoint<any>, 'useCase'>,\n>(\n useCaseClass: UseCaseConstructor,\n options: O,\n): O & { readonly useCase: MetaUseCase } => ({\n ...options,\n useCase: extractUseCase(useCaseClass),\n});\n\n/** What an entity's endpoints serve, and under which rules. */\nexport interface EntityApiOptions<T extends Entity, R> {\n readonly verbs: readonly EntityApiVerb[];\n /** One guard for every verb, or one for the reads and one for the writes. */\n readonly guard:\n | EntityApiGuard\n | { readonly read: EntityApiGuard; readonly write: EntityApiGuard };\n /** Narrows the reads, and the facet counts, to what this caller may see. */\n readonly narrowing?: NarrowingRules<T>;\n /** Serve `$facets` beside the list, under the list's guard and narrowing. */\n readonly facets?: boolean;\n /** Runs on every generic create and update, before the save. */\n readonly prepare?: (\n entity: T,\n context: EntityApiContext & { readonly verb: 'create' | 'update' },\n ) => Effect.Effect<T, EntifixFailure, R>;\n /** The business failures `prepare` may answer with, for the contract. */\n readonly errors?: readonly FailureClass[];\n readonly override?: Partial<Record<EntityApiVerb, EntityVerbOverride<R>>>;\n /**\n * The entity's `@useCase()` verbs, one endpoint each. Every verb the entity\n * declares must be here and none another entity declares, or serving the\n * declaration throws.\n */\n readonly useCases?: readonly VerbEndpoint<R>[];\n}\n\n/**\n * An entity's endpoints as a value: which verbs, behind which guards, with\n * which handlers. Declaring them needs no HTTP — a domain's cell declares, and\n * the shell serves the declaration with `entityApi`\n * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n */\nexport interface EntityApiDeclaration<\n T extends Entity,\n K extends string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n O extends EntityApiOptions<T, any>,\n> {\n readonly entity: EntityConstructor<T>;\n readonly key: K;\n readonly options: O;\n}\n\n/** `O`, with every key `Shape` does not name typed `never`. */\ntype Exact<O, Shape> = O & Record<Exclude<keyof O, keyof Shape>, never>;\n\n/**\n * Declare an entity's endpoints, to be served by the shell. An option the\n * declaration does not know is a compile error rather than a value nobody\n * reads — `compositions` included, which the shell adds when it serves.\n */\nexport const defineEntityApi = <\n T extends Entity,\n const K extends string,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n const O extends EntityApiOptions<T, any>,\n>(\n entity: EntityConstructor<T>,\n key: K,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- inferred from the options\n options: Exact<O, EntityApiOptions<T, any>>,\n): EntityApiDeclaration<T, K, O> => ({ entity, key, options });\n"],"names":["extractUseCase","verbEndpoint","useCaseClass","options","useCase","defineEntityApi","entity","key"],"mappings":";AAAA,SAQEA,cAAc,QAKT,gBAAgB;AAsGvB,iEAAiE,GACjE,OAAO,MAAMC,eAAe,CAI1BC,cACAC,UAC2C,aACxCA;QACHC,SAASJ,eAAeE;OACvB;AAiDH;;;;CAIC,GACD,OAAO,MAAMG,kBAAkB,CAM7BC,QACAC,KACA,2FAA2F;AAC3FJ,UACmC,CAAA;QAAEG;QAAQC;QAAKJ;IAAQ,CAAA,EAAG"}
@@ -0,0 +1,2 @@
1
+ export * from './entity-api.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/entity-api/index.ts"],"names":[],"mappings":"AAAA,cAAc,iBAAiB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './entity-api.js';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/entity-api/index.ts"],"sourcesContent":["export * from './entity-api.js';\n"],"names":[],"mappings":"AAAA,cAAc,kBAAkB"}
@@ -62,6 +62,12 @@ export declare const SlipStage: Schema.Struct<{
62
62
  }>>;
63
63
  }>;
64
64
  export type SlipStage = typeof SlipStage.Type;
65
+ /** Who may receive what the flow announces — the envelope's audience. */
66
+ export declare const SlipAudienceEntry: Schema.Struct<{
67
+ readonly kind: Schema.Literals<readonly ["organization", "party", "flow"]>;
68
+ readonly id: Schema.String;
69
+ readonly digest: Schema.optionalKey<Schema.String>;
70
+ }>;
65
71
  /** Which variant each use case resolved to, and by which rule. */
66
72
  export declare const SlipResolution: Schema.Struct<{
67
73
  readonly useCase: Schema.String;
@@ -111,6 +117,15 @@ export declare const Slip: Schema.Struct<{
111
117
  readonly rule: Schema.Number;
112
118
  }>>;
113
119
  readonly composedAt: Schema.String;
120
+ /**
121
+ * Who the flow's `flow.*` events reach beside the flow itself — the
122
+ * organizations and parties it acts for, pinned when it was composed.
123
+ */
124
+ readonly audience: Schema.optionalKey<Schema.$Array<Schema.Struct<{
125
+ readonly kind: Schema.Literals<readonly ["organization", "party", "flow"]>;
126
+ readonly id: Schema.String;
127
+ readonly digest: Schema.optionalKey<Schema.String>;
128
+ }>>>;
114
129
  }>;
115
130
  export type Slip = typeof Slip.Type;
116
131
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"slip.d.ts","sourceRoot":"","sources":["../../src/flow/slip.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC;;;;GAIG;AACH,eAAO,MAAM,YAAY,EAAG,CAAU,CAAC;AAOvC,mFAAmF;AACnF,eAAO,MAAM,WAAW;;;EAGtB,CAAC;AACH,MAAM,MAAM,WAAW,GAAG,OAAO,WAAW,CAAC,IAAI,CAAC;AAElD,4EAA4E;AAC5E,eAAO,MAAM,QAAQ;IACnB,uDAAuD;;IAEvD,gFAAgF;;;;;;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C;AAElD,4EAA4E;AAC5E,eAAO,MAAM,QAAQ;IACnB,uDAAuD;;IAEvD,gFAAgF;;;;;;;;;;;;;;;;IAOhF,sEAAsE;;EAEtE,CAAC;AACH,MAAM,MAAM,QAAQ,GAAG,OAAO,QAAQ,CAAC,IAAI,CAAC;AAE5C,eAAO,MAAM,SAAS;;;QAdpB,uDAAuD;;QAEvD,gFAAgF;;;;;;;;;;;;;;;;QAOhF,sEAAsE;;;EAQtE,CAAC;AACH,MAAM,MAAM,SAAS,GAAG,OAAO,SAAS,CAAC,IAAI,CAAC;AAE9C,yEAAyE;AACzE,eAAO,MAAM,iBAAiB;;;;EAI5B,CAAC;AAEH,kEAAkE;AAClE,eAAO,MAAM,cAAc;;;;EAIzB,CAAC;AACH,MAAM,MAAM,cAAc,GAAG,OAAO,cAAc,CAAC,IAAI,CAAC;AAExD;;;;GAIG;AACH,eAAO,MAAM,IAAI;;;;IAIf,kFAAkF;;;;;YA5ClF,uDAAuD;;YAEvD,gFAAgF;;;;;;;;;;;;;;;;YAOhF,sEAAsE;;;;;;;;;;IAwCtE;;;OAGG;;;;;;EAEH,CAAC;AACH,MAAM,MAAM,IAAI,GAAG,OAAO,IAAI,CAAC,IAAI,CAAC;AAEpC;;;;GAIG;AACH,eAAO,MAAM,UAAU,GACrB,OAAO,OAAO,KACb,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,eAAe,CAQnC,CAAC;AAEJ,4DAA4D;AAC5D,eAAO,MAAM,UAAU,GAAI,MAAM,IAAI,KAAG,OACT,CAAC;AAEhC,kDAAkD;AAClD,eAAO,MAAM,SAAS,GAAI,MAAM,IAAI,KAAG,SAAS,QAAQ,EACb,CAAC"}
package/dist/flow/slip.js CHANGED
@@ -37,6 +37,15 @@ export const SlipStage = Schema.Struct({
37
37
  name: Schema.String,
38
38
  steps: Schema.Array(SlipStep)
39
39
  });
40
+ /** Who may receive what the flow announces — the envelope's audience. */ export const SlipAudienceEntry = Schema.Struct({
41
+ kind: Schema.Literals([
42
+ 'organization',
43
+ 'party',
44
+ 'flow'
45
+ ]),
46
+ id: Schema.String,
47
+ digest: Schema.optionalKey(Schema.String)
48
+ });
40
49
  /** Which variant each use case resolved to, and by which rule. */ export const SlipResolution = Schema.Struct({
41
50
  useCase: Schema.String,
42
51
  variant: Schema.String,
@@ -53,7 +62,11 @@ export const SlipStage = Schema.Struct({
53
62
  /** The recipe demands a commit point even with no retriable step (a checkout). */ requiresCommitPoint: Schema.optionalKey(Schema.Boolean),
54
63
  stages: Schema.Array(SlipStage),
55
64
  resolution: Schema.Array(SlipResolution),
56
- composedAt: Schema.String
65
+ composedAt: Schema.String,
66
+ /**
67
+ * Who the flow's `flow.*` events reach beside the flow itself — the
68
+ * organizations and parties it acts for, pinned when it was composed.
69
+ */ audience: Schema.optionalKey(Schema.Array(SlipAudienceEntry))
57
70
  });
58
71
  /**
59
72
  * Decodes a stored or received slip. An unknown `slipVersion`, like any shape
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/flow/slip.ts"],"sourcesContent":["import { ProtocolFailure } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\n/**\n * The grammar version a slip is written in. An interpreter branches on it, so a\n * flow that started under one grammar finishes under that grammar even after\n * the next one ships.\n */\nexport const SLIP_VERSION = 1 as const;\n\nconst Call = Schema.Struct({\n method: Schema.Literals(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']),\n path: Schema.String,\n});\n\n/** Tags that place a step in a segment of the flow: whose lines, which payment. */\nexport const SlipSegment = Schema.Struct({\n vendor: Schema.optionalKey(Schema.String),\n paymentMethod: Schema.optionalKey(Schema.String),\n});\nexport type SlipSegment = typeof SlipSegment.Type;\n\n/** One pinned step: a fragment reference and everything resolved for it. */\nexport const SlipStep = Schema.Struct({\n /** `id@version`, pinned when the slip was composed. */\n ref: Schema.String,\n /** Unique within the slip; what an Activity is named after (`segment:step`). */\n step: Schema.String,\n cardinality: Schema.Literals(['one', 'perVendor', 'perLine']),\n segment: Schema.optionalKey(SlipSegment),\n participant: Schema.optionalKey(Schema.String),\n call: Schema.optionalKey(Call),\n compensation: Schema.optionalKey(Call),\n /** Configuration pinned at composition — a hold's expiry, a limit. */\n parameters: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),\n});\nexport type SlipStep = typeof SlipStep.Type;\n\nexport const SlipStage = Schema.Struct({\n name: Schema.String,\n steps: Schema.Array(SlipStep),\n});\nexport type SlipStage = typeof SlipStage.Type;\n\n/** Which variant each use case resolved to, and by which rule. */\nexport const SlipResolution = Schema.Struct({\n useCase: Schema.String,\n variant: Schema.String,\n rule: Schema.Number,\n});\nexport type SlipResolution = typeof SlipResolution.Type;\n\n/**\n * A routing slip: ordered stages of pinned steps, composed once at start and\n * stored as the flow's payload. Changing a recipe or a fragment never changes a\n * flow that has already started.\n */\nexport const Slip = Schema.Struct({\n slipVersion: Schema.Literal(SLIP_VERSION),\n flowId: Schema.String,\n recipe: Schema.String,\n /** The recipe demands a commit point even with no retriable step (a checkout). */\n requiresCommitPoint: Schema.optionalKey(Schema.Boolean),\n stages: Schema.Array(SlipStage),\n resolution: Schema.Array(SlipResolution),\n composedAt: Schema.String,\n});\nexport type Slip = typeof Slip.Type;\n\n/**\n * Decodes a stored or received slip. An unknown `slipVersion`, like any shape\n * the grammar does not describe, is a protocol failure: an interpreter must\n * never guess at a grammar it was not built for.\n */\nexport const decodeSlip = (\n input: unknown,\n): Effect.Effect<Slip, ProtocolFailure> =>\n Schema.decodeUnknownEffect(Slip)(input).pipe(\n Effect.mapError(\n error =>\n new ProtocolFailure({\n reason: `the slip does not decode: ${error.message}`,\n }),\n ),\n );\n\n/** Encodes a slip as the workflow payload it travels as. */\nexport const encodeSlip = (slip: Slip): unknown =>\n Schema.encodeSync(Slip)(slip);\n\n/** Every step of a slip, in the order it runs. */\nexport const slipSteps = (slip: Slip): readonly SlipStep[] =>\n slip.stages.flatMap(stage => stage.steps);\n"],"names":["ProtocolFailure","Effect","Schema","SLIP_VERSION","Call","Struct","method","Literals","path","String","SlipSegment","vendor","optionalKey","paymentMethod","SlipStep","ref","step","cardinality","segment","participant","call","compensation","parameters","Record","Unknown","SlipStage","name","steps","Array","SlipResolution","useCase","variant","rule","Number","Slip","slipVersion","Literal","flowId","recipe","requiresCommitPoint","Boolean","stages","resolution","composedAt","decodeSlip","input","decodeUnknownEffect","pipe","mapError","error","reason","message","encodeSlip","slip","encodeSync","slipSteps","flatMap","stage"],"mappings":"AAAA,SAASA,eAAe,QAAQ,gBAAgB;AAChD,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAExC;;;;CAIC,GACD,OAAO,MAAMC,eAAe,EAAW;AAEvC,MAAMC,OAAOF,OAAOG,MAAM,CAAC;IACzBC,QAAQJ,OAAOK,QAAQ,CAAC;QAAC;QAAO;QAAQ;QAAO;QAAS;KAAS;IACjEC,MAAMN,OAAOO,MAAM;AACrB;AAEA,iFAAiF,GACjF,OAAO,MAAMC,cAAcR,OAAOG,MAAM,CAAC;IACvCM,QAAQT,OAAOU,WAAW,CAACV,OAAOO,MAAM;IACxCI,eAAeX,OAAOU,WAAW,CAACV,OAAOO,MAAM;AACjD,GAAG;AAGH,0EAA0E,GAC1E,OAAO,MAAMK,WAAWZ,OAAOG,MAAM,CAAC;IACpC,qDAAqD,GACrDU,KAAKb,OAAOO,MAAM;IAClB,8EAA8E,GAC9EO,MAAMd,OAAOO,MAAM;IACnBQ,aAAaf,OAAOK,QAAQ,CAAC;QAAC;QAAO;QAAa;KAAU;IAC5DW,SAAShB,OAAOU,WAAW,CAACF;IAC5BS,aAAajB,OAAOU,WAAW,CAACV,OAAOO,MAAM;IAC7CW,MAAMlB,OAAOU,WAAW,CAACR;IACzBiB,cAAcnB,OAAOU,WAAW,CAACR;IACjC,oEAAoE,GACpEkB,YAAYpB,OAAOU,WAAW,CAACV,OAAOqB,MAAM,CAACrB,OAAOO,MAAM,EAAEP,OAAOsB,OAAO;AAC5E,GAAG;AAGH,OAAO,MAAMC,YAAYvB,OAAOG,MAAM,CAAC;IACrCqB,MAAMxB,OAAOO,MAAM;IACnBkB,OAAOzB,OAAO0B,KAAK,CAACd;AACtB,GAAG;AAGH,gEAAgE,GAChE,OAAO,MAAMe,iBAAiB3B,OAAOG,MAAM,CAAC;IAC1CyB,SAAS5B,OAAOO,MAAM;IACtBsB,SAAS7B,OAAOO,MAAM;IACtBuB,MAAM9B,OAAO+B,MAAM;AACrB,GAAG;AAGH;;;;CAIC,GACD,OAAO,MAAMC,OAAOhC,OAAOG,MAAM,CAAC;IAChC8B,aAAajC,OAAOkC,OAAO,CAACjC;IAC5BkC,QAAQnC,OAAOO,MAAM;IACrB6B,QAAQpC,OAAOO,MAAM;IACrB,gFAAgF,GAChF8B,qBAAqBrC,OAAOU,WAAW,CAACV,OAAOsC,OAAO;IACtDC,QAAQvC,OAAO0B,KAAK,CAACH;IACrBiB,YAAYxC,OAAO0B,KAAK,CAACC;IACzBc,YAAYzC,OAAOO,MAAM;AAC3B,GAAG;AAGH;;;;CAIC,GACD,OAAO,MAAMmC,aAAa,CACxBC,QAEA3C,OAAO4C,mBAAmB,CAACZ,MAAMW,OAAOE,IAAI,CAC1C9C,OAAO+C,QAAQ,CACbC,CAAAA,QACE,IAAIjD,gBAAgB;YAClBkD,QAAQ,CAAC,0BAA0B,EAAED,MAAME,OAAO,EAAE;QACtD,KAEJ;AAEJ,0DAA0D,GAC1D,OAAO,MAAMC,aAAa,CAACC,OACzBnD,OAAOoD,UAAU,CAACpB,MAAMmB,MAAM;AAEhC,gDAAgD,GAChD,OAAO,MAAME,YAAY,CAACF,OACxBA,KAAKZ,MAAM,CAACe,OAAO,CAACC,CAAAA,QAASA,MAAM9B,KAAK,EAAE"}
1
+ {"version":3,"sources":["../../src/flow/slip.ts"],"sourcesContent":["import { ProtocolFailure } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\n/**\n * The grammar version a slip is written in. An interpreter branches on it, so a\n * flow that started under one grammar finishes under that grammar even after\n * the next one ships.\n */\nexport const SLIP_VERSION = 1 as const;\n\nconst Call = Schema.Struct({\n method: Schema.Literals(['GET', 'POST', 'PUT', 'PATCH', 'DELETE']),\n path: Schema.String,\n});\n\n/** Tags that place a step in a segment of the flow: whose lines, which payment. */\nexport const SlipSegment = Schema.Struct({\n vendor: Schema.optionalKey(Schema.String),\n paymentMethod: Schema.optionalKey(Schema.String),\n});\nexport type SlipSegment = typeof SlipSegment.Type;\n\n/** One pinned step: a fragment reference and everything resolved for it. */\nexport const SlipStep = Schema.Struct({\n /** `id@version`, pinned when the slip was composed. */\n ref: Schema.String,\n /** Unique within the slip; what an Activity is named after (`segment:step`). */\n step: Schema.String,\n cardinality: Schema.Literals(['one', 'perVendor', 'perLine']),\n segment: Schema.optionalKey(SlipSegment),\n participant: Schema.optionalKey(Schema.String),\n call: Schema.optionalKey(Call),\n compensation: Schema.optionalKey(Call),\n /** Configuration pinned at composition — a hold's expiry, a limit. */\n parameters: Schema.optionalKey(Schema.Record(Schema.String, Schema.Unknown)),\n});\nexport type SlipStep = typeof SlipStep.Type;\n\nexport const SlipStage = Schema.Struct({\n name: Schema.String,\n steps: Schema.Array(SlipStep),\n});\nexport type SlipStage = typeof SlipStage.Type;\n\n/** Who may receive what the flow announces — the envelope's audience. */\nexport const SlipAudienceEntry = Schema.Struct({\n kind: Schema.Literals(['organization', 'party', 'flow']),\n id: Schema.String,\n digest: Schema.optionalKey(Schema.String),\n});\n\n/** Which variant each use case resolved to, and by which rule. */\nexport const SlipResolution = Schema.Struct({\n useCase: Schema.String,\n variant: Schema.String,\n rule: Schema.Number,\n});\nexport type SlipResolution = typeof SlipResolution.Type;\n\n/**\n * A routing slip: ordered stages of pinned steps, composed once at start and\n * stored as the flow's payload. Changing a recipe or a fragment never changes a\n * flow that has already started.\n */\nexport const Slip = Schema.Struct({\n slipVersion: Schema.Literal(SLIP_VERSION),\n flowId: Schema.String,\n recipe: Schema.String,\n /** The recipe demands a commit point even with no retriable step (a checkout). */\n requiresCommitPoint: Schema.optionalKey(Schema.Boolean),\n stages: Schema.Array(SlipStage),\n resolution: Schema.Array(SlipResolution),\n composedAt: Schema.String,\n /**\n * Who the flow's `flow.*` events reach beside the flow itself — the\n * organizations and parties it acts for, pinned when it was composed.\n */\n audience: Schema.optionalKey(Schema.Array(SlipAudienceEntry)),\n});\nexport type Slip = typeof Slip.Type;\n\n/**\n * Decodes a stored or received slip. An unknown `slipVersion`, like any shape\n * the grammar does not describe, is a protocol failure: an interpreter must\n * never guess at a grammar it was not built for.\n */\nexport const decodeSlip = (\n input: unknown,\n): Effect.Effect<Slip, ProtocolFailure> =>\n Schema.decodeUnknownEffect(Slip)(input).pipe(\n Effect.mapError(\n error =>\n new ProtocolFailure({\n reason: `the slip does not decode: ${error.message}`,\n }),\n ),\n );\n\n/** Encodes a slip as the workflow payload it travels as. */\nexport const encodeSlip = (slip: Slip): unknown =>\n Schema.encodeSync(Slip)(slip);\n\n/** Every step of a slip, in the order it runs. */\nexport const slipSteps = (slip: Slip): readonly SlipStep[] =>\n slip.stages.flatMap(stage => stage.steps);\n"],"names":["ProtocolFailure","Effect","Schema","SLIP_VERSION","Call","Struct","method","Literals","path","String","SlipSegment","vendor","optionalKey","paymentMethod","SlipStep","ref","step","cardinality","segment","participant","call","compensation","parameters","Record","Unknown","SlipStage","name","steps","Array","SlipAudienceEntry","kind","id","digest","SlipResolution","useCase","variant","rule","Number","Slip","slipVersion","Literal","flowId","recipe","requiresCommitPoint","Boolean","stages","resolution","composedAt","audience","decodeSlip","input","decodeUnknownEffect","pipe","mapError","error","reason","message","encodeSlip","slip","encodeSync","slipSteps","flatMap","stage"],"mappings":"AAAA,SAASA,eAAe,QAAQ,gBAAgB;AAChD,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAExC;;;;CAIC,GACD,OAAO,MAAMC,eAAe,EAAW;AAEvC,MAAMC,OAAOF,OAAOG,MAAM,CAAC;IACzBC,QAAQJ,OAAOK,QAAQ,CAAC;QAAC;QAAO;QAAQ;QAAO;QAAS;KAAS;IACjEC,M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OAAOG,MAAM,CAAC;IAChCkC,aAAarC,OAAOsC,OAAO,CAACrC;IAC5BsC,QAAQvC,OAAOO,MAAM;IACrBiC,QAAQxC,OAAOO,MAAM;IACrB,gFAAgF,GAChFkC,qBAAqBzC,OAAOU,WAAW,CAACV,OAAO0C,OAAO;IACtDC,QAAQ3C,OAAO0B,KAAK,CAACH;IACrBqB,YAAY5C,OAAO0B,KAAK,CAACK;IACzBc,YAAY7C,OAAOO,MAAM;IACzB;;;GAGC,GACDuC,UAAU9C,OAAOU,WAAW,CAACV,OAAO0B,KAAK,CAACC;AAC5C,GAAG;AAGH;;;;CAIC,GACD,OAAO,MAAMoB,aAAa,CACxBC,QAEAhD,OAAOiD,mBAAmB,CAACb,MAAMY,OAAOE,IAAI,CAC1CnD,OAAOoD,QAAQ,CACbC,CAAAA,QACE,IAAItD,gBAAgB;YAClBuD,QAAQ,CAAC,0BAA0B,EAAED,MAAME,OAAO,EAAE;QACtD,KAEJ;AAEJ,0DAA0D,GAC1D,OAAO,MAAMC,aAAa,CAACC,OACzBxD,OAAOyD,UAAU,CAACrB,MAAMoB,MAAM;AAEhC,gDAAgD,GAChD,OAAO,MAAME,YAAY,CAACF,OACxBA,KAAKb,MAAM,CAACgB,OAAO,CAACC,CAAAA,QAASA,MAAMnC,KAAK,EAAE"}
@@ -43,7 +43,28 @@ declare const CompositionRefused_base: Schema.Class<CompositionRefused, Schema.T
43
43
  */
44
44
  export declare class CompositionRefused extends CompositionRefused_base {
45
45
  }
46
- /** Validates a slip, failing with {@link CompositionRefused} on any violation. */
47
- export declare const assertValidSlip: (slip: Slip, catalog: FragmentCatalog, options?: ValidateSlipOptions) => Effect.Effect<Slip, CompositionRefused>;
46
+ declare const FlowRequirementsUnmet_base: Schema.Class<FlowRequirementsUnmet, Schema.TaggedStruct<"FlowRequirementsUnmet", {
47
+ readonly violations: Schema.$Array<Schema.Struct<{
48
+ readonly tag: Schema.String;
49
+ readonly step: Schema.optionalKey<Schema.String>;
50
+ readonly detail: Schema.String;
51
+ }>>;
52
+ }>, import("effect/Cause").YieldableError & import("@entifix/core").FailureFacts<"flowRequirementsUnmet", "forbidden">>;
53
+ /**
54
+ * A flow this caller is not offered: every rule the slip broke is a step's
55
+ * requirement — an entitlement, a role, a party role or a channel — that the
56
+ * verified context lacks. The recipe is sound; the caller may not run it, so
57
+ * it is `forbidden` rather than a slip that could not be built.
58
+ */
59
+ export declare class FlowRequirementsUnmet extends FlowRequirementsUnmet_base {
60
+ }
61
+ /** Every violation is a requirement the caller lacks, and there is one. */
62
+ export declare const onlyUnmetRequirements: (violations: readonly SlipViolation[]) => boolean;
63
+ /**
64
+ * Validates a slip, failing on any violation: with {@link FlowRequirementsUnmet}
65
+ * when the caller lacks only what steps require, and otherwise with
66
+ * {@link CompositionRefused}, which carries every violation.
67
+ */
68
+ export declare const assertValidSlip: (slip: Slip, catalog: FragmentCatalog, options?: ValidateSlipOptions) => Effect.Effect<Slip, CompositionRefused | FlowRequirementsUnmet>;
48
69
  export {};
49
70
  //# sourceMappingURL=validate.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"validate.d.ts","sourceRoot":"","sources":["../../src/flow/validate.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,QAAQ,CAAC;AAExC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,cAAc,CAAC;AACpD,OAAO,EAEL,KAAK,YAAY,EACjB,KAAK,oBAAoB,EAE1B,MAAM,eAAe,CAAC;AACvB,OAAO,EAAE,KAAK,IAAI,EAA4B,MAAM,WAAW,CAAC;AAEhE,+CAA+C;AAC/C,MAAM,WAAW,aAAa;IAC5B,QAAQ,CAAC,GAAG,EACR,iBAAiB,GACjB,eAAe,GACf,oBAAoB,GACpB,uBAAuB,GACvB,0BAA0B,GAC1B,0BAA0B,GAC1B,kBAAkB,GAClB,qBAAqB,GACrB,kBAAkB,GAClB,kBAAkB,CAAC;IACvB,iDAAiD;IACjD,QAAQ,CAAC,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BAAqB,GAChC,YAAY,SAAS,aAAa,EAAE,KACnC,OAEkE,CAAC;AAEtE;;;;GAIG;AACH,eAAO,MAAM,eAAe,GAC1B,MAAM,IAAI,EACV,SAAS,eAAe,EACxB,UAAS,mBAAwB,KAChC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,kBAAkB,GAAG,qBAAqB,CAQhE,CAAC"}
@@ -116,9 +116,28 @@ const SlipViolationSchema = Schema.Struct({
116
116
  message: ({ violations })=>`the flow cannot be composed: ${violations.map((v)=>v.tag).join(', ')}`
117
117
  }) {
118
118
  }
119
- /** Validates a slip, failing with {@link CompositionRefused} on any violation. */ export const assertValidSlip = (slip, catalog, options = {})=>{
119
+ /**
120
+ * A flow this caller is not offered: every rule the slip broke is a step's
121
+ * requirement — an entitlement, a role, a party role or a channel — that the
122
+ * verified context lacks. The recipe is sound; the caller may not run it, so
123
+ * it is `forbidden` rather than a slip that could not be built.
124
+ */ export class FlowRequirementsUnmet extends Failure.forbidden()('FlowRequirementsUnmet', 'flowRequirementsUnmet', {
125
+ violations: Schema.Array(SlipViolationSchema)
126
+ }, {
127
+ message: ({ violations })=>`the flow is not offered to this caller: ${violations.map((v)=>v.detail).join('; ')}`
128
+ }) {
129
+ }
130
+ /** Every violation is a requirement the caller lacks, and there is one. */ export const onlyUnmetRequirements = (violations)=>violations.length > 0 && violations.every((violation)=>violation.tag === 'UnmetRequirement');
131
+ /**
132
+ * Validates a slip, failing on any violation: with {@link FlowRequirementsUnmet}
133
+ * when the caller lacks only what steps require, and otherwise with
134
+ * {@link CompositionRefused}, which carries every violation.
135
+ */ export const assertValidSlip = (slip, catalog, options = {})=>{
120
136
  const violations = validateSlip(slip, catalog, options);
121
- return violations.length === 0 ? Effect.succeed(slip) : Effect.fail(new CompositionRefused({
137
+ if (violations.length === 0) return Effect.succeed(slip);
138
+ return Effect.fail(onlyUnmetRequirements(violations) ? new FlowRequirementsUnmet({
139
+ violations
140
+ }) : new CompositionRefused({
122
141
  violations
123
142
  }));
124
143
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/flow/validate.ts"],"sourcesContent":["import { Failure } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\nimport type { FragmentCatalog } from './catalog.js';\nimport {\n type FragmentDescriptor,\n type FragmentKeys,\n type FragmentRequirements,\n jsonSchemaOf,\n} from './fragment.js';\nimport { type Slip, type SlipStep, slipSteps } from './slip.js';\n\n/** One rule a slip broke, named by its tag. */\nexport interface SlipViolation {\n readonly tag:\n | 'UnknownFragment'\n | 'TooManyPivots'\n | 'MissingCommitPoint'\n | 'RetriableBeforeCommit'\n | 'CompensatableAfterCommit'\n | 'IrreversibleBeforeCommit'\n | 'WaitBeforeCommit'\n | 'ExcludedFromSegment'\n | 'UnsatisfiedInput'\n | 'UnmetRequirement';\n /** The step that broke it, when one step did. */\n readonly step?: string;\n readonly detail: string;\n}\n\n/** The facts of a verified context a slip's requirements are checked against. */\nexport interface RequirementFacts {\n readonly entitlements?: readonly string[];\n readonly roles?: readonly string[];\n readonly partyRole?: string;\n readonly channel?: string;\n}\n\nexport interface ValidateSlipOptions {\n /** The facts the caller was verified with; requirements go unchecked without them. */\n readonly context?: RequirementFacts;\n /** Keys the flow's start input provides, with their schemas. */\n readonly start?: FragmentKeys;\n}\n\nconst sameSchema = (\n a: Schema.Codec<unknown, unknown>,\n b: Schema.Codec<unknown, unknown>,\n): boolean =>\n a === b ||\n JSON.stringify(jsonSchemaOf(a)) === JSON.stringify(jsonSchemaOf(b));\n\n/** The requirements `facts` do not meet, described; empty when all are met. */\nexport const unmetRequirements = (\n requires: FragmentRequirements,\n facts: RequirementFacts,\n): string[] => {\n const missing: string[] = [];\n for (const entitlement of requires.entitlements ?? [])\n if (!(facts.entitlements ?? []).includes(entitlement))\n missing.push(`entitlement '${entitlement}'`);\n for (const role of requires.roles ?? [])\n if (!(facts.roles ?? []).includes(role)) missing.push(`role '${role}'`);\n if (\n requires.partyRoles !== undefined &&\n !requires.partyRoles.includes(facts.partyRole ?? '')\n )\n missing.push(`party role in ${requires.partyRoles.join(', ')}`);\n if (\n requires.channels !== undefined &&\n !requires.channels.includes(facts.channel ?? '')\n )\n missing.push(`channel in ${requires.channels.join(', ')}`);\n return missing;\n};\n\n/**\n * Checks a slip against its catalog and returns **every** violation, one tag\n * per rule, rather than throwing at the first — so a CI job enumerating every\n * composition reports them all in one run. Pure: no clock, no I/O.\n */\nexport const validateSlip = (\n slip: Slip,\n catalog: FragmentCatalog,\n options: ValidateSlipOptions = {},\n): readonly SlipViolation[] => {\n const violations: SlipViolation[] = [];\n const resolved: {\n readonly step: SlipStep;\n readonly fragment: FragmentDescriptor;\n }[] = [];\n\n for (const step of slipSteps(slip)) {\n const fragment = catalog.get(step.ref);\n if (fragment === undefined)\n violations.push({\n tag: 'UnknownFragment',\n step: step.step,\n detail: `'${step.ref}' is not in the catalog`,\n });\n else resolved.push({ step, fragment });\n }\n\n const pivots = resolved.filter(({ fragment }) => fragment.kind === 'pivot');\n if (pivots.length > 1)\n violations.push({\n tag: 'TooManyPivots',\n detail: `the slip has ${String(pivots.length)} pivots (${pivots\n .map(({ step }) => step.step)\n .join(', ')}); a flow has one point of no return`,\n });\n\n const commitAt = resolved.findIndex(\n ({ fragment }) => fragment.kind === 'pivot',\n );\n const hasRetriable = resolved.some(\n ({ fragment }) => fragment.kind === 'retriable',\n );\n if (commitAt === -1 && (hasRetriable || slip.requiresCommitPoint === true))\n violations.push({\n tag: 'MissingCommitPoint',\n detail:\n 'the slip needs one commit point — a pivot, or flow.commit@1 — before its first retriable step',\n });\n\n const provided = new Map<string, Schema.Codec<unknown, unknown>>(\n Object.entries(options.start ?? {}),\n );\n\n resolved.forEach(({ step, fragment }, index) => {\n const beforeCommit = commitAt === -1 || index < commitAt;\n const afterCommit = commitAt !== -1 && index > commitAt;\n\n if (fragment.kind === 'retriable' && commitAt !== -1 && index < commitAt)\n violations.push({\n tag: 'RetriableBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' is retriable and runs before the commit point, where a failure must compensate`,\n });\n if (fragment.kind === 'compensatable' && afterCommit)\n violations.push({\n tag: 'CompensatableAfterCommit',\n step: step.step,\n detail: `'${step.ref}' is compensatable and runs after the commit point, where nothing is undone`,\n });\n if (\n fragment.irreversible === true &&\n fragment.kind !== 'pivot' &&\n beforeCommit\n )\n violations.push({\n tag: 'IrreversibleBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' cannot be undone and runs before the commit point`,\n });\n if (fragment.kind === 'wait' && beforeCommit)\n violations.push({\n tag: 'WaitBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' waits before the commit point, holding uncommitted state for as long as it waits`,\n });\n\n for (const [tag, values] of Object.entries(fragment.excludedFrom ?? {})) {\n const value = (\n step.segment as Record<string, string | undefined> | undefined\n )?.[tag];\n if (value !== undefined && values.includes(value))\n violations.push({\n tag: 'ExcludedFromSegment',\n step: step.step,\n detail: `'${step.ref}' may not run in a segment whose ${tag} is '${value}'`,\n });\n }\n\n for (const [key, schema] of Object.entries(fragment.consumes ?? {})) {\n const earlier = provided.get(key);\n if (earlier === undefined)\n violations.push({\n tag: 'UnsatisfiedInput',\n step: step.step,\n detail: `'${step.ref}' consumes '${key}', which nothing before it provides`,\n });\n else if (!sameSchema(earlier, schema))\n violations.push({\n tag: 'UnsatisfiedInput',\n step: step.step,\n detail: `'${step.ref}' consumes '${key}' with a schema other than the one provided`,\n });\n }\n for (const [key, schema] of Object.entries(fragment.provides ?? {}))\n provided.set(key, schema);\n\n if (options.context !== undefined && fragment.requires !== undefined) {\n const missing = unmetRequirements(fragment.requires, options.context);\n if (missing.length > 0)\n violations.push({\n tag: 'UnmetRequirement',\n step: step.step,\n detail: `'${step.ref}' requires ${missing.join(', ')}`,\n });\n }\n });\n\n return violations;\n};\n\nconst SlipViolationSchema = Schema.Struct({\n tag: Schema.String,\n step: Schema.optionalKey(Schema.String),\n detail: Schema.String,\n});\n\n/**\n * A flow that cannot be composed for this caller: the slip broke at least one\n * rule. Every violation travels with it.\n */\nexport class CompositionRefused extends Failure.declined<CompositionRefused>()(\n 'CompositionRefused',\n 'flowNotComposable',\n { violations: Schema.Array(SlipViolationSchema) },\n {\n message: ({ violations }) =>\n `the flow cannot be composed: ${violations.map(v => v.tag).join(', ')}`,\n },\n) {}\n\n/** Validates a slip, failing with {@link CompositionRefused} on any violation. */\nexport const assertValidSlip = (\n slip: Slip,\n catalog: FragmentCatalog,\n options: ValidateSlipOptions = {},\n): Effect.Effect<Slip, CompositionRefused> => {\n const violations = validateSlip(slip, catalog, options);\n return violations.length === 0\n ? Effect.succeed(slip)\n : Effect.fail(new CompositionRefused({ violations }));\n};\n"],"names":["Failure","Effect","Schema","jsonSchemaOf","slipSteps","sameSchema","a","b","JSON","stringify","unmetRequirements","requires","facts","missing","entitlement","entitlements","includes","push","role","roles","partyRoles","undefined","partyRole","join","channels","channel","validateSlip","slip","catalog","options","violations","resolved","step","fragment","get","ref","tag","detail","pivots","filter","kind","length","String","map","commitAt","findIndex","hasRetriable","some","requiresCommitPoint","provided","Map","Object","entries","start","forEach","index","beforeCommit","afterCommit","irreversible","values","excludedFrom","value","segment","key","schema","consumes","earlier","provides","set","context","SlipViolationSchema","Struct","optionalKey","CompositionRefused","declined","Array","message","v","assertValidSlip","succeed","fail"],"mappings":"AAAA,SAASA,OAAO,QAAQ,gBAAgB;AACxC,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAGxC,SAIEC,YAAY,QACP,gBAAgB;AACvB,SAAmCC,SAAS,QAAQ,YAAY;AAmChE,MAAMC,aAAa,CACjBC,GACAC,IAEAD,MAAMC,KACNC,KAAKC,SAAS,CAACN,aAAaG,QAAQE,KAAKC,SAAS,CAACN,aAAaI;AAElE,6EAA6E,GAC7E,OAAO,MAAMG,oBAAoB,CAC/BC,UACAC;QAG0BD,wBAClBC,qBAEWD,iBACXC,cAGwBA,kBAKFA;IAb9B,MAAMC,UAAoB,EAAE;IAC5B,KAAK,MAAMC,gBAAeH,yBAAAA,SAASI,YAAY,YAArB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IAAKA,EAAEzC,GAAG,EAAEb,IAAI,CAAC,OAAO;AAC3E;AACC;AAEH,gFAAgF,GAChF,OAAO,MAAMuD,kBAAkB,CAC7BnD,MACAC,SACAC,UAA+B,CAAC,CAAC;IAEjC,MAAMC,aAAaJ,aAAaC,MAAMC,SAASC;IAC/C,OAAOC,WAAWW,MAAM,KAAK,IACzBxC,OAAO8E,OAAO,CAACpD,QACf1B,OAAO+E,IAAI,CAAC,IAAIP,mBAAmB;QAAE3C;IAAW;AACtD,EAAE"}
1
+ {"version":3,"sources":["../../src/flow/validate.ts"],"sourcesContent":["import { Failure } from '@entifix/core';\nimport { Effect, Schema } from 'effect';\n\nimport type { FragmentCatalog } from './catalog.js';\nimport {\n type FragmentDescriptor,\n type FragmentKeys,\n type FragmentRequirements,\n jsonSchemaOf,\n} from './fragment.js';\nimport { type Slip, type SlipStep, slipSteps } from './slip.js';\n\n/** One rule a slip broke, named by its tag. */\nexport interface SlipViolation {\n readonly tag:\n | 'UnknownFragment'\n | 'TooManyPivots'\n | 'MissingCommitPoint'\n | 'RetriableBeforeCommit'\n | 'CompensatableAfterCommit'\n | 'IrreversibleBeforeCommit'\n | 'WaitBeforeCommit'\n | 'ExcludedFromSegment'\n | 'UnsatisfiedInput'\n | 'UnmetRequirement';\n /** The step that broke it, when one step did. */\n readonly step?: string;\n readonly detail: string;\n}\n\n/** The facts of a verified context a slip's requirements are checked against. */\nexport interface RequirementFacts {\n readonly entitlements?: readonly string[];\n readonly roles?: readonly string[];\n readonly partyRole?: string;\n readonly channel?: string;\n}\n\nexport interface ValidateSlipOptions {\n /** The facts the caller was verified with; requirements go unchecked without them. */\n readonly context?: RequirementFacts;\n /** Keys the flow's start input provides, with their schemas. */\n readonly start?: FragmentKeys;\n}\n\nconst sameSchema = (\n a: Schema.Codec<unknown, unknown>,\n b: Schema.Codec<unknown, unknown>,\n): boolean =>\n a === b ||\n JSON.stringify(jsonSchemaOf(a)) === JSON.stringify(jsonSchemaOf(b));\n\n/** The requirements `facts` do not meet, described; empty when all are met. */\nexport const unmetRequirements = (\n requires: FragmentRequirements,\n facts: RequirementFacts,\n): string[] => {\n const missing: string[] = [];\n for (const entitlement of requires.entitlements ?? [])\n if (!(facts.entitlements ?? []).includes(entitlement))\n missing.push(`entitlement '${entitlement}'`);\n for (const role of requires.roles ?? [])\n if (!(facts.roles ?? []).includes(role)) missing.push(`role '${role}'`);\n if (\n requires.partyRoles !== undefined &&\n !requires.partyRoles.includes(facts.partyRole ?? '')\n )\n missing.push(`party role in ${requires.partyRoles.join(', ')}`);\n if (\n requires.channels !== undefined &&\n !requires.channels.includes(facts.channel ?? '')\n )\n missing.push(`channel in ${requires.channels.join(', ')}`);\n return missing;\n};\n\n/**\n * Checks a slip against its catalog and returns **every** violation, one tag\n * per rule, rather than throwing at the first — so a CI job enumerating every\n * composition reports them all in one run. Pure: no clock, no I/O.\n */\nexport const validateSlip = (\n slip: Slip,\n catalog: FragmentCatalog,\n options: ValidateSlipOptions = {},\n): readonly SlipViolation[] => {\n const violations: SlipViolation[] = [];\n const resolved: {\n readonly step: SlipStep;\n readonly fragment: FragmentDescriptor;\n }[] = [];\n\n for (const step of slipSteps(slip)) {\n const fragment = catalog.get(step.ref);\n if (fragment === undefined)\n violations.push({\n tag: 'UnknownFragment',\n step: step.step,\n detail: `'${step.ref}' is not in the catalog`,\n });\n else resolved.push({ step, fragment });\n }\n\n const pivots = resolved.filter(({ fragment }) => fragment.kind === 'pivot');\n if (pivots.length > 1)\n violations.push({\n tag: 'TooManyPivots',\n detail: `the slip has ${String(pivots.length)} pivots (${pivots\n .map(({ step }) => step.step)\n .join(', ')}); a flow has one point of no return`,\n });\n\n const commitAt = resolved.findIndex(\n ({ fragment }) => fragment.kind === 'pivot',\n );\n const hasRetriable = resolved.some(\n ({ fragment }) => fragment.kind === 'retriable',\n );\n if (commitAt === -1 && (hasRetriable || slip.requiresCommitPoint === true))\n violations.push({\n tag: 'MissingCommitPoint',\n detail:\n 'the slip needs one commit point — a pivot, or flow.commit@1 — before its first retriable step',\n });\n\n const provided = new Map<string, Schema.Codec<unknown, unknown>>(\n Object.entries(options.start ?? {}),\n );\n\n resolved.forEach(({ step, fragment }, index) => {\n const beforeCommit = commitAt === -1 || index < commitAt;\n const afterCommit = commitAt !== -1 && index > commitAt;\n\n if (fragment.kind === 'retriable' && commitAt !== -1 && index < commitAt)\n violations.push({\n tag: 'RetriableBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' is retriable and runs before the commit point, where a failure must compensate`,\n });\n if (fragment.kind === 'compensatable' && afterCommit)\n violations.push({\n tag: 'CompensatableAfterCommit',\n step: step.step,\n detail: `'${step.ref}' is compensatable and runs after the commit point, where nothing is undone`,\n });\n if (\n fragment.irreversible === true &&\n fragment.kind !== 'pivot' &&\n beforeCommit\n )\n violations.push({\n tag: 'IrreversibleBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' cannot be undone and runs before the commit point`,\n });\n if (fragment.kind === 'wait' && beforeCommit)\n violations.push({\n tag: 'WaitBeforeCommit',\n step: step.step,\n detail: `'${step.ref}' waits before the commit point, holding uncommitted state for as long as it waits`,\n });\n\n for (const [tag, values] of Object.entries(fragment.excludedFrom ?? {})) {\n const value = (\n step.segment as Record<string, string | undefined> | undefined\n )?.[tag];\n if (value !== undefined && values.includes(value))\n violations.push({\n tag: 'ExcludedFromSegment',\n step: step.step,\n detail: `'${step.ref}' may not run in a segment whose ${tag} is '${value}'`,\n });\n }\n\n for (const [key, schema] of Object.entries(fragment.consumes ?? {})) {\n const earlier = provided.get(key);\n if (earlier === undefined)\n violations.push({\n tag: 'UnsatisfiedInput',\n step: step.step,\n detail: `'${step.ref}' consumes '${key}', which nothing before it provides`,\n });\n else if (!sameSchema(earlier, schema))\n violations.push({\n tag: 'UnsatisfiedInput',\n step: step.step,\n detail: `'${step.ref}' consumes '${key}' with a schema other than the one provided`,\n });\n }\n for (const [key, schema] of Object.entries(fragment.provides ?? {}))\n provided.set(key, schema);\n\n if (options.context !== undefined && fragment.requires !== undefined) {\n const missing = unmetRequirements(fragment.requires, options.context);\n if (missing.length > 0)\n violations.push({\n tag: 'UnmetRequirement',\n step: step.step,\n detail: `'${step.ref}' requires ${missing.join(', ')}`,\n });\n }\n });\n\n return violations;\n};\n\nconst SlipViolationSchema = Schema.Struct({\n tag: Schema.String,\n step: Schema.optionalKey(Schema.String),\n detail: Schema.String,\n});\n\n/**\n * A flow that cannot be composed for this caller: the slip broke at least one\n * rule. Every violation travels with it.\n */\nexport class CompositionRefused extends Failure.declined<CompositionRefused>()(\n 'CompositionRefused',\n 'flowNotComposable',\n { violations: Schema.Array(SlipViolationSchema) },\n {\n message: ({ violations }) =>\n `the flow cannot be composed: ${violations.map(v => v.tag).join(', ')}`,\n },\n) {}\n\n/**\n * A flow this caller is not offered: every rule the slip broke is a step's\n * requirement — an entitlement, a role, a party role or a channel — that the\n * verified context lacks. The recipe is sound; the caller may not run it, so\n * it is `forbidden` rather than a slip that could not be built.\n */\nexport class FlowRequirementsUnmet extends Failure.forbidden<FlowRequirementsUnmet>()(\n 'FlowRequirementsUnmet',\n 'flowRequirementsUnmet',\n { violations: Schema.Array(SlipViolationSchema) },\n {\n message: ({ violations }) =>\n `the flow is not offered to this caller: ${violations.map(v => v.detail).join('; ')}`,\n },\n) {}\n\n/** Every violation is a requirement the caller lacks, and there is one. */\nexport const onlyUnmetRequirements = (\n violations: readonly SlipViolation[],\n): boolean =>\n violations.length > 0 &&\n violations.every(violation => violation.tag === 'UnmetRequirement');\n\n/**\n * Validates a slip, failing on any violation: with {@link FlowRequirementsUnmet}\n * when the caller lacks only what steps require, and otherwise with\n * {@link CompositionRefused}, which carries every violation.\n */\nexport const assertValidSlip = (\n slip: Slip,\n catalog: FragmentCatalog,\n options: ValidateSlipOptions = {},\n): Effect.Effect<Slip, CompositionRefused | FlowRequirementsUnmet> => {\n const violations = validateSlip(slip, catalog, options);\n if (violations.length === 0) return Effect.succeed(slip);\n return Effect.fail(\n onlyUnmetRequirements(violations)\n ? new FlowRequirementsUnmet({ violations })\n : new CompositionRefused({ violations }),\n );\n};\n"],"names":["Failure","Effect","Schema","jsonSchemaOf","slipSteps","sameSchema","a","b","JSON","stringify","unmetRequirements","requires","facts","missing","entitlement","entitlements","includes","push","role","roles","partyRoles","undefined","partyRole","join","channels","channel","validateSlip","slip","catalog","options","violations","resolved","step","fragment","get","ref","tag","detail","pivots","filter","kind","length","String","map","commitAt","findIndex","hasRetriable","some","requiresCommitPoint","provided","Map","Object","entries","start","forEach","index","beforeCommit","afterCommit","irreversible","values","excludedFrom","value","segment","key","schema","consumes","earlier","provides","set","context","SlipViolationSchema","Struct","optionalKey","CompositionRefused","declined","Array","message","v","FlowRequirementsUnmet","forbidden","onlyUnmetRequirements","every","violation","assertValidSlip","succeed","fail"],"mappings":"AAAA,SAASA,OAAO,QAAQ,gBAAgB;AACxC,SAASC,MAAM,EAAEC,MAAM,QAAQ,SAAS;AAGxC,SAIEC,YAAY,QACP,gBAAgB;AACvB,SAAmCC,SAAS,QAAQ,YAAY;AAmChE,MAAMC,aAAa,CACjBC,GACAC,IAEAD,MAAMC,KACNC,KAAKC,SAAS,CAACN,aAAaG,QAAQE,KAAKC,SAAS,CAACN,aAAaI;AAElE,6EAA6E,GAC7E,OAAO,MAAMG,oBAAoB,CAC/BC,UACAC;QAG0BD,wBAClBC,qBAEWD,iBACXC,cAGwBA,kBAKFA;IAb9B,MAAMC,UAAoB,EAAE;IAC5B,KAAK,MAAMC,gBAAeH,yBAAAA,SAASI,YAAY,YAArBJ,yBAAyB,EAAE,CACnD,IAAI,CAAC,EAACC,sBAAAA,MAAMG,YAAY,YAAlBH,sBAAsB,EAAE,EAAEI,QAAQ,CAACF,cACvCD,QAAQI,IAAI,CAAC,CAAC,aAAa,EAAEH,YAAY,CAAC,CAAC;IAC/C,KAAK,MAAMI,SAAQP,kBAAAA,SAASQ,KAAK,YAAdR,kBAAkB,EAAE,CACrC,IAAI,CAAC,EAACC,eAAAA,MAAMO,KAAK,YAAXP,eAAe,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MAAM,EAAEd,IAAI,CAAC,OAAO;AACzF;AACC;AAEH,yEAAyE,GACzE,OAAO,MAAMyD,wBAAwB,CACnClD,aAEAA,WAAWW,MAAM,GAAG,KACpBX,WAAWmD,KAAK,CAACC,CAAAA,YAAaA,UAAU9C,GAAG,KAAK,oBAAoB;AAEtE;;;;CAIC,GACD,OAAO,MAAM+C,kBAAkB,CAC7BxD,MACAC,SACAC,UAA+B,CAAC,CAAC;IAEjC,MAAMC,aAAaJ,aAAaC,MAAMC,SAASC;IAC/C,IAAIC,WAAWW,MAAM,KAAK,GAAG,OAAOxC,OAAOmF,OAAO,CAACzD;IACnD,OAAO1B,OAAOoF,IAAI,CAChBL,sBAAsBlD,cAClB,IAAIgD,sBAAsB;QAAEhD;IAAW,KACvC,IAAI2C,mBAAmB;QAAE3C;IAAW;AAE5C,EAAE"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './entity-api/index.js';
1
2
  export * from './health/health-registry.js';
2
3
  export * from './idempotency/index.js';
3
4
  export * from './repository/config.repository.js';
@@ -6,6 +7,7 @@ export * from './repository/entity-facet-counter.js';
6
7
  export * from './repository/entity-link-resolver.repository.js';
7
8
  export * from './repository/entity-mixins.repository.js';
8
9
  export * from './repository/entity-repository-factory.js';
10
+ export * from './request/index.js';
9
11
  export * from './resolve/index.js';
10
12
  export * from './sessions/one-time-token-store.js';
11
13
  export * from './sessions/session-store.js';
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,mCAAmC,CAAC;AAClD,cAAc,mCAAmC,CAAC;AAClD,cAAc,sCAAsC,CAAC;AACrD,cAAc,iDAAiD,CAAC;AAChE,cAAc,0CAA0C,CAAC;AACzD,cAAc,2CAA2C,CAAC;AAC1D,cAAc,oBAAoB,CAAC;AACnC,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,6BAA6B,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC;AACtC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,wBAAwB,CAAC;AACvC,cAAc,mCAAmC,CAAC;AAClD,cAAc,mCAAmC,CAAC;AAClD,cAAc,sCAAsC,CAAC;AACrD,cAAc,iDAAiD,CAAC;AAChE,cAAc,0CAA0C,CAAC;AACzD,cAAc,2CAA2C,CAAC;AAC1D,cAAc,oBAAoB,CAAC;AACnC,cAAc,oBAAoB,CAAC;AACnC,cAAc,oCAAoC,CAAC;AACnD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,oBAAoB,CAAC;AACnC,cAAc,4BAA4B,CAAC;AAC3C,cAAc,2BAA2B,CAAC;AAC1C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,4BAA4B,CAAC;AAC3C,cAAc,yBAAyB,CAAC;AACxC,cAAc,0BAA0B,CAAC;AACzC,cAAc,0BAA0B,CAAC;AACzC,cAAc,6BAA6B,CAAC"}
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ export * from './entity-api/index.js';
1
2
  export * from './health/health-registry.js';
2
3
  export * from './idempotency/index.js';
3
4
  export * from './repository/config.repository.js';
@@ -6,6 +7,7 @@ export * from './repository/entity-facet-counter.js';
6
7
  export * from './repository/entity-link-resolver.repository.js';
7
8
  export * from './repository/entity-mixins.repository.js';
8
9
  export * from './repository/entity-repository-factory.js';
10
+ export * from './request/index.js';
9
11
  export * from './resolve/index.js';
10
12
  export * from './sessions/one-time-token-store.js';
11
13
  export * from './sessions/session-store.js';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './health/health-registry.js';\nexport * from './idempotency/index.js';\nexport * from './repository/config.repository.js';\nexport * from './repository/entity.repository.js';\nexport * from './repository/entity-facet-counter.js';\nexport * from './repository/entity-link-resolver.repository.js';\nexport * from './repository/entity-mixins.repository.js';\nexport * from './repository/entity-repository-factory.js';\nexport * from './resolve/index.js';\nexport * from './sessions/one-time-token-store.js';\nexport * from './sessions/session-store.js';\nexport * from './shutdown/shutdown-registry.js';\nexport * from './tenancy/index.js';\nexport * from './tokens/token-failures.js';\nexport * from './tokens/token-service.js';\nexport * from './use-case/delete/index.js';\nexport * from './use-case/facets/index.js';\nexport * from './use-case/get/index.js';\nexport * from './use-case/load/index.js';\nexport * from './use-case/save/index.js';\nexport * from './wiring/wiring-registry.js';\n"],"names":[],"mappings":"AAAA,cAAc,8BAA8B;AAC5C,cAAc,yBAAyB;AACvC,cAAc,oCAAoC;AAClD,cAAc,oCAAoC;AAClD,cAAc,uCAAuC;AACrD,cAAc,kDAAkD;AAChE,cAAc,2CAA2C;AACzD,cAAc,4CAA4C;AAC1D,cAAc,qBAAqB;AACnC,cAAc,qCAAqC;AACnD,cAAc,8BAA8B;AAC5C,cAAc,kCAAkC;AAChD,cAAc,qBAAqB;AACnC,cAAc,6BAA6B;AAC3C,cAAc,4BAA4B;AAC1C,cAAc,6BAA6B;AAC3C,cAAc,6BAA6B;AAC3C,cAAc,0BAA0B;AACxC,cAAc,2BAA2B;AACzC,cAAc,2BAA2B;AACzC,cAAc,8BAA8B"}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["export * from './entity-api/index.js';\nexport * from './health/health-registry.js';\nexport * from './idempotency/index.js';\nexport * from './repository/config.repository.js';\nexport * from './repository/entity.repository.js';\nexport * from './repository/entity-facet-counter.js';\nexport * from './repository/entity-link-resolver.repository.js';\nexport * from './repository/entity-mixins.repository.js';\nexport * from './repository/entity-repository-factory.js';\nexport * from './request/index.js';\nexport * from './resolve/index.js';\nexport * from './sessions/one-time-token-store.js';\nexport * from './sessions/session-store.js';\nexport * from './shutdown/shutdown-registry.js';\nexport * from './tenancy/index.js';\nexport * from './tokens/token-failures.js';\nexport * from './tokens/token-service.js';\nexport * from './use-case/delete/index.js';\nexport * from './use-case/facets/index.js';\nexport * from './use-case/get/index.js';\nexport * from './use-case/load/index.js';\nexport * from './use-case/save/index.js';\nexport * from './wiring/wiring-registry.js';\n"],"names":[],"mappings":"AAAA,cAAc,wBAAwB;AACtC,cAAc,8BAA8B;AAC5C,cAAc,yBAAyB;AACvC,cAAc,oCAAoC;AAClD,cAAc,oCAAoC;AAClD,cAAc,uCAAuC;AACrD,cAAc,kDAAkD;AAChE,cAAc,2CAA2C;AACzD,cAAc,4CAA4C;AAC1D,cAAc,qBAAqB;AACnC,cAAc,qBAAqB;AACnC,cAAc,qCAAqC;AACnD,cAAc,8BAA8B;AAC5C,cAAc,kCAAkC;AAChD,cAAc,qBAAqB;AACnC,cAAc,6BAA6B;AAC3C,cAAc,4BAA4B;AAC1C,cAAc,6BAA6B;AAC3C,cAAc,6BAA6B;AAC3C,cAAc,0BAA0B;AACxC,cAAc,2BAA2B;AACzC,cAAc,2BAA2B;AACzC,cAAc,8BAA8B"}
@@ -0,0 +1,2 @@
1
+ export * from './request-context.js';
2
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/request/index.ts"],"names":[],"mappings":"AAAA,cAAc,sBAAsB,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './request-context.js';
2
+
3
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/index.ts"],"sourcesContent":["export * from './request-context.js';\n"],"names":[],"mappings":"AAAA,cAAc,uBAAuB"}
@@ -0,0 +1,86 @@
1
+ import { Context } from 'effect';
2
+ import type { TokenClaims } from '../tokens/token-service.js';
3
+ /**
4
+ * The authenticated subject as a service sees it, rebuilt by the shell from a
5
+ * verified token and nothing else. It lives here rather than in the shell so a
6
+ * handler reads it through {@link RequestPrincipalTag} without importing the
7
+ * transport.
8
+ */
9
+ export interface RequestPrincipal {
10
+ readonly userId: TokenClaims['userId'];
11
+ readonly subject: string;
12
+ readonly sessionId: string;
13
+ readonly roles: readonly string[];
14
+ /**
15
+ * The organization this request acts for — the storage routing key, absent
16
+ * for a caller with no tenant scope (a buyer, or an operator). Kept out of
17
+ * `attributes` deliberately: attributes are policy inputs, this decides which
18
+ * database a handler reads.
19
+ */
20
+ readonly organizationId?: string;
21
+ /**
22
+ * Which population the caller belongs to — buyer, vendor staff, or platform
23
+ * staff. Carried so a handler never has to infer it from an absent
24
+ * `organizationId`, which a buyer and an operator share.
25
+ *
26
+ * Context, not a grant: what the caller may *do* still comes from `roles`
27
+ * through the policy decision port.
28
+ */
29
+ readonly partyRole?: string;
30
+ /**
31
+ * The party behind the account — the `Individual` id, absent for an account
32
+ * with no party record.
33
+ *
34
+ * Same rule as the two fields above: it comes from the verified token and
35
+ * never from anything the caller sets on the request. It says *whose* records
36
+ * these are, which is what a route scoping a read to its caller needs; it
37
+ * says nothing about what may be done with them.
38
+ */
39
+ readonly partyId?: string;
40
+ /**
41
+ * When the verified token stops being valid, as a Unix timestamp in seconds.
42
+ *
43
+ * Every REST route is already bounded by it implicitly — verification is
44
+ * stateless, so the next call after expiry simply fails. A **held-open**
45
+ * response has no next call, so a held-open stream reads it and closes the
46
+ * connection there. Absent when the token carries no
47
+ * `exp`, which a signed one always does; the guard is for the type, not for a
48
+ * case the fleet produces.
49
+ */
50
+ readonly expiresAt?: number;
51
+ /**
52
+ * What the caller's active organization was provisioned for, off the
53
+ * verified token. Context for a resolver, never a
54
+ * grant: a variant requires an entitlement before its predicate is read.
55
+ */
56
+ readonly entitlements?: readonly string[];
57
+ readonly attributes: Readonly<Record<string, unknown>>;
58
+ }
59
+ declare const RequestPrincipalTag_base: Context.ServiceClass<RequestPrincipalTag, "@entifix/business/RequestPrincipal", RequestPrincipal>;
60
+ /**
61
+ * The verified caller of the current request, provided by the shell's
62
+ * `session`, `permission` and `organization` guards
63
+ * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
64
+ * Absent on a `public`, `crossing` or `fleet` endpoint: no session was read.
65
+ */
66
+ export declare class RequestPrincipalTag extends RequestPrincipalTag_base {
67
+ }
68
+ declare const OrganizationIdTag_base: Context.ServiceClass<OrganizationIdTag, "@entifix/business/OrganizationId", string>;
69
+ /**
70
+ * The organization the current request acts for. From the session's active
71
+ * organization on an `organization` endpoint, and from `x-organization-id` on a
72
+ * `crossing` endpoint that lets the caller name it — never from a path, a query
73
+ * or a body.
74
+ */
75
+ export declare class OrganizationIdTag extends OrganizationIdTag_base {
76
+ }
77
+ declare const IdempotencyKeyTag_base: Context.ServiceClass<IdempotencyKeyTag, "@entifix/business/IdempotencyKey", string>;
78
+ /**
79
+ * The request's `Idempotency-Key`, decoded by the shell on an endpoint
80
+ * declared `idempotent: 'unit'`. The handler's unit of work claims it in the
81
+ * same transaction as its write.
82
+ */
83
+ export declare class IdempotencyKeyTag extends IdempotencyKeyTag_base {
84
+ }
85
+ export {};
86
+ //# sourceMappingURL=request-context.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"request-context.d.ts","sourceRoot":"","sources":["../../src/request/request-context.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,QAAQ,CAAC;AAEjC,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,4BAA4B,CAAC;AAE9D;;;;;GAKG;AACH,MAAM,WAAW,gBAAgB;IAC/B,QAAQ,CAAC,MAAM,EAAE,WAAW,CAAC,QAAQ,CAAC,CAAC;IACvC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAC;IACzB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAC;IAC3B,QAAQ,CAAC,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IAClC;;;;;OAKG;IACH,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACjC;;;;;;;OAOG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;;;;;OAQG;IACH,QAAQ,CAAC,OAAO,CAAC,EAAE,MAAM,CAAC;IAC1B;;;;;;;;;OASG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,MAAM,CAAC;IAC5B;;;;OAIG;IACH,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;IAC1C,QAAQ,CAAC,UAAU,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,CAAC;CACxD;;AAED;;;;;GAKG;AACH,qBAAa,mBAAoB,SAAQ,wBAGA;CAAG;;AAE5C;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,sBAGA;CAAG;;AAE1C;;;;GAIG;AACH,qBAAa,iBAAkB,SAAQ,sBAGA;CAAG"}
@@ -0,0 +1,23 @@
1
+ import { Context } from 'effect';
2
+ /**
3
+ * The verified caller of the current request, provided by the shell's
4
+ * `session`, `permission` and `organization` guards
5
+ * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).
6
+ * Absent on a `public`, `crossing` or `fleet` endpoint: no session was read.
7
+ */ export class RequestPrincipalTag extends Context.Service()('@entifix/business/RequestPrincipal') {
8
+ }
9
+ /**
10
+ * The organization the current request acts for. From the session's active
11
+ * organization on an `organization` endpoint, and from `x-organization-id` on a
12
+ * `crossing` endpoint that lets the caller name it — never from a path, a query
13
+ * or a body.
14
+ */ export class OrganizationIdTag extends Context.Service()('@entifix/business/OrganizationId') {
15
+ }
16
+ /**
17
+ * The request's `Idempotency-Key`, decoded by the shell on an endpoint
18
+ * declared `idempotent: 'unit'`. The handler's unit of work claims it in the
19
+ * same transaction as its write.
20
+ */ export class IdempotencyKeyTag extends Context.Service()('@entifix/business/IdempotencyKey') {
21
+ }
22
+
23
+ //# sourceMappingURL=request-context.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../src/request/request-context.ts"],"sourcesContent":["import { Context } from 'effect';\n\nimport type { TokenClaims } from '../tokens/token-service.js';\n\n/**\n * The authenticated subject as a service sees it, rebuilt by the shell from a\n * verified token and nothing else. It lives here rather than in the shell so a\n * handler reads it through {@link RequestPrincipalTag} without importing the\n * transport.\n */\nexport interface RequestPrincipal {\n readonly userId: TokenClaims['userId'];\n readonly subject: string;\n readonly sessionId: string;\n readonly roles: readonly string[];\n /**\n * The organization this request acts for — the storage routing key, absent\n * for a caller with no tenant scope (a buyer, or an operator). Kept out of\n * `attributes` deliberately: attributes are policy inputs, this decides which\n * database a handler reads.\n */\n readonly organizationId?: string;\n /**\n * Which population the caller belongs to — buyer, vendor staff, or platform\n * staff. Carried so a handler never has to infer it from an absent\n * `organizationId`, which a buyer and an operator share.\n *\n * Context, not a grant: what the caller may *do* still comes from `roles`\n * through the policy decision port.\n */\n readonly partyRole?: string;\n /**\n * The party behind the account — the `Individual` id, absent for an account\n * with no party record.\n *\n * Same rule as the two fields above: it comes from the verified token and\n * never from anything the caller sets on the request. It says *whose* records\n * these are, which is what a route scoping a read to its caller needs; it\n * says nothing about what may be done with them.\n */\n readonly partyId?: string;\n /**\n * When the verified token stops being valid, as a Unix timestamp in seconds.\n *\n * Every REST route is already bounded by it implicitly — verification is\n * stateless, so the next call after expiry simply fails. A **held-open**\n * response has no next call, so a held-open stream reads it and closes the\n * connection there. Absent when the token carries no\n * `exp`, which a signed one always does; the guard is for the type, not for a\n * case the fleet produces.\n */\n readonly expiresAt?: number;\n /**\n * What the caller's active organization was provisioned for, off the\n * verified token. Context for a resolver, never a\n * grant: a variant requires an entitlement before its predicate is read.\n */\n readonly entitlements?: readonly string[];\n readonly attributes: Readonly<Record<string, unknown>>;\n}\n\n/**\n * The verified caller of the current request, provided by the shell's\n * `session`, `permission` and `organization` guards\n * ([ADR 0020](../../../../../docs/adr/0020-endpoints-are-descriptors-and-the-shell-builds-an-httpapi.md)).\n * Absent on a `public`, `crossing` or `fleet` endpoint: no session was read.\n */\nexport class RequestPrincipalTag extends Context.Service<\n RequestPrincipalTag,\n RequestPrincipal\n>()('@entifix/business/RequestPrincipal') {}\n\n/**\n * The organization the current request acts for. From the session's active\n * organization on an `organization` endpoint, and from `x-organization-id` on a\n * `crossing` endpoint that lets the caller name it — never from a path, a query\n * or a body.\n */\nexport class OrganizationIdTag extends Context.Service<\n OrganizationIdTag,\n string\n>()('@entifix/business/OrganizationId') {}\n\n/**\n * The request's `Idempotency-Key`, decoded by the shell on an endpoint\n * declared `idempotent: 'unit'`. The handler's unit of work claims it in the\n * same transaction as its write.\n */\nexport class IdempotencyKeyTag extends Context.Service<\n IdempotencyKeyTag,\n string\n>()('@entifix/business/IdempotencyKey') {}\n"],"names":["Context","RequestPrincipalTag","Service","OrganizationIdTag","IdempotencyKeyTag"],"mappings":"AAAA,SAASA,OAAO,QAAQ,SAAS;AA6DjC;;;;;CAKC,GACD,OAAO,MAAMC,4BAA4BD,QAAQE,OAAO,GAGpD;AAAuC;AAE3C;;;;;CAKC,GACD,OAAO,MAAMC,0BAA0BH,QAAQE,OAAO,GAGlD;AAAqC;AAEzC;;;;CAIC,GACD,OAAO,MAAME,0BAA0BJ,QAAQE,OAAO,GAGlD;AAAqC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@entifix/business",
3
- "version": "0.11.0",
3
+ "version": "0.12.0",
4
4
  "description": "The ports every adapter implements — repository, session, token, health — and the generic get, load, save and delete use-cases.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -66,7 +66,7 @@
66
66
  },
67
67
  "dependencies": {
68
68
  "@swc/helpers": "0.5.23",
69
- "@entifix/core": "0.11.0"
69
+ "@entifix/core": "0.12.0"
70
70
  },
71
71
  "peerDependencies": {
72
72
  "effect": "^4.0.6"