@cullet/erp-core 1.0.11 → 1.2.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.
Files changed (118) hide show
  1. package/KIT_CONTEXT.md +1 -0
  2. package/README.md +128 -1
  3. package/dist/app-error.d.ts +108 -0
  4. package/dist/application/index.d.ts +2 -0
  5. package/dist/application/index.js +3 -0
  6. package/dist/domain/index.d.ts +3 -0
  7. package/dist/domain/index.js +3 -0
  8. package/dist/domain-event-contracts.d.ts +27 -0
  9. package/dist/domain-event-contracts.js +22 -0
  10. package/dist/domain-event-contracts.js.map +1 -0
  11. package/dist/domain-exception.d.ts +7 -0
  12. package/dist/domain-exception.js +12 -0
  13. package/dist/domain-exception.js.map +1 -0
  14. package/dist/errors/index.d.ts +2 -1
  15. package/dist/errors/index.js +4 -2
  16. package/dist/exceptions/index.d.ts +5 -0
  17. package/dist/exceptions/index.js +7 -0
  18. package/dist/gate-engine-registry.d.ts +81 -0
  19. package/dist/gate-engine-registry.js +2 -1
  20. package/dist/gate-engine-registry.js.map +1 -1
  21. package/dist/gate-types.d.ts +3 -139
  22. package/dist/gate-v1-payload.schema.js +3 -143
  23. package/dist/gate-v1-payload.schema.js.map +1 -1
  24. package/dist/hashing.js +49 -0
  25. package/dist/hashing.js.map +1 -0
  26. package/dist/immutable.d.ts +6 -0
  27. package/dist/immutable.js +54 -0
  28. package/dist/immutable.js.map +1 -0
  29. package/dist/index.d.ts +21 -200
  30. package/dist/index.js +21 -251
  31. package/dist/index.js.map +1 -1
  32. package/dist/invalid-state-transition-exception.js +30 -0
  33. package/dist/invalid-state-transition-exception.js.map +1 -0
  34. package/dist/invariant-violation-exception.js +11 -0
  35. package/dist/invariant-violation-exception.js.map +1 -0
  36. package/dist/not-found-error.js +54 -0
  37. package/dist/not-found-error.js.map +1 -0
  38. package/dist/outcome.d.ts +140 -0
  39. package/dist/outcome.js +1 -1
  40. package/dist/parse-gate-payload.d.ts +4 -78
  41. package/dist/path.d.ts +90 -0
  42. package/dist/plugin.d.ts +85 -0
  43. package/dist/plugin.js +74 -0
  44. package/dist/plugin.js.map +1 -0
  45. package/dist/plugins/index.d.ts +2 -0
  46. package/dist/plugins/index.js +2 -0
  47. package/dist/policies/engines/index.d.ts +3 -2
  48. package/dist/policies/engines/v1/gate/index.d.ts +2 -1
  49. package/dist/policies/engines/v1/gate/index.js +2 -1
  50. package/dist/policies/engines/v1/gate/index.js.map +1 -1
  51. package/dist/policies/index.d.ts +6 -3
  52. package/dist/policies/index.js +2 -1
  53. package/dist/policy-service.d.ts +4 -86
  54. package/dist/policy-service.js +8 -16
  55. package/dist/policy-service.js.map +1 -1
  56. package/dist/result/index.d.ts +2 -0
  57. package/dist/result/index.js +3 -0
  58. package/dist/result.js +118 -0
  59. package/dist/result.js.map +1 -0
  60. package/dist/ruleset-registry.js +42 -0
  61. package/dist/ruleset-registry.js.map +1 -0
  62. package/dist/rulesets/index.d.ts +2 -0
  63. package/dist/rulesets/index.js +2 -0
  64. package/dist/temporal-guards.js +15 -0
  65. package/dist/temporal-guards.js.map +1 -0
  66. package/dist/temporal-use-case.d.ts +304 -0
  67. package/dist/temporal-use-case.js +150 -0
  68. package/dist/temporal-use-case.js.map +1 -0
  69. package/dist/unexpected-error.js +179 -0
  70. package/dist/unexpected-error.js.map +1 -0
  71. package/dist/use-case.js +91 -0
  72. package/dist/use-case.js.map +1 -0
  73. package/dist/uuid-identifier.d.ts +230 -0
  74. package/dist/uuid-identifier.js +60 -0
  75. package/dist/uuid-identifier.js.map +1 -0
  76. package/dist/validation-code.d.ts +23 -0
  77. package/dist/validation-code.js +1 -223
  78. package/dist/validation-code.js.map +1 -1
  79. package/dist/validation-error.d.ts +3 -128
  80. package/dist/validation-error.js +2 -52
  81. package/dist/validation-error.js.map +1 -1
  82. package/dist/validation-exception.d.ts +50 -0
  83. package/dist/validation-exception.js +24 -0
  84. package/dist/validation-exception.js.map +1 -0
  85. package/dist/value-object-ruleset.contracts.d.ts +36 -0
  86. package/dist/value-object.js +191 -0
  87. package/dist/value-object.js.map +1 -0
  88. package/dist/version.d.ts +10 -0
  89. package/dist/versioning/index.d.ts +3 -0
  90. package/dist/versioning/index.js +3 -0
  91. package/meta.json +18 -3
  92. package/package.json +37 -4
  93. package/src/application/index.ts +1 -0
  94. package/src/core/application/commands/index.ts +1 -0
  95. package/src/core/application/index.ts +12 -3
  96. package/src/core/application/ports/index.ts +2 -2
  97. package/src/core/application/ports/policy-port.ts +13 -3
  98. package/src/core/application/ports/repository.port.ts +37 -1
  99. package/src/core/application/temporal/temporal-use-case.ts +14 -2
  100. package/src/core/application/use-case.ts +133 -2
  101. package/src/core/domain/rulesets/index.ts +7 -0
  102. package/src/core/domain/uuid-identifier.ts +72 -0
  103. package/src/core/domain/value-object.ts +37 -5
  104. package/src/core/exceptions/index.ts +13 -0
  105. package/src/core/index.ts +15 -12
  106. package/src/core/plugins/index.ts +7 -0
  107. package/src/core/plugins/plugin.ts +99 -0
  108. package/src/core/plugins/types.ts +53 -0
  109. package/src/core/versioning/index.ts +14 -0
  110. package/src/domain/index.ts +7 -0
  111. package/src/examples/application/cancel-order.example.ts +124 -0
  112. package/src/examples/application/in-memory-account-repository.example.ts +73 -0
  113. package/src/exceptions/index.ts +1 -0
  114. package/src/plugins/index.ts +1 -0
  115. package/src/result/index.ts +2 -0
  116. package/src/rulesets/index.ts +1 -0
  117. package/src/version.ts +1 -1
  118. package/src/versioning/index.ts +1 -0
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/core/application/policy-error-mapper.ts","../src/core/shared/aggregate-version.ts","../src/core/versioning/version.ts","../src/core/domain/entity.ts","../src/core/shared/immutable.ts","../src/core/domain/value-object.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.0.11\";\n","import {\n type AppError,\n BusinessRuleViolationError,\n NotFoundError,\n UnexpectedError,\n} from \"../errors/index.js\";\nimport type { PolicyEvaluationError } from \"../policies/index.js\";\n\nexport function mapPolicyEvaluationError(err: PolicyEvaluationError): AppError {\n switch (err.kind) {\n case \"INVALID_CONTEXT\":\n return new BusinessRuleViolationError(\n `policy.${err.stage.toLowerCase()}`,\n err.message,\n { policyKey: err.policyKey, stage: err.stage },\n { cause: err.cause },\n );\n case \"INVALID_POLICY_KEY\":\n return new BusinessRuleViolationError(\n \"policy.invalid_key\",\n err.message,\n { rawPolicyKey: err.rawPolicyKey },\n { cause: err.cause },\n );\n case \"POLICY_NOT_FOUND\":\n return new NotFoundError(\n \"Policy\",\n { policyKey: err.policyKey },\n { cause: err.cause },\n );\n case \"POLICY_DEFINITION_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyDefinition\",\n {\n policyKey: err.policyKey,\n contextVersion: err.contextVersion,\n asOf: err.asOf.toISOString(),\n },\n { cause: err.cause },\n );\n case \"POLICY_VARIANT_NOT_FOUND\":\n return new NotFoundError(\n \"PolicyVariant\",\n {\n policyKey: err.policyKey,\n policyKind: err.policyKind,\n payloadSchemaVersion: err.payloadSchemaVersion,\n },\n { cause: err.cause },\n );\n case \"ENGINE_FAILURE\":\n return new UnexpectedError(err.message, err.cause, {\n metadata: {\n policyKey: err.policyKey,\n engine: err.engine,\n engineVersion: err.engineVersion,\n },\n });\n }\n}\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\nfunction assertValidAggregateVersion(aggregateVersion: number): void {\n if (!Number.isInteger(aggregateVersion) || aggregateVersion < 0) {\n throw new InvariantViolationException(\n `aggregateVersion must be a non-negative integer. Received: ${aggregateVersion}`,\n );\n }\n}\n\nexport { assertValidAggregateVersion };\n","type ContractVersion = `${number}.${number}`;\n\ntype VersionedTarget = {\n readonly prototype: object;\n};\n\nconst CONTRACT_VERSION_PROPERTY = \"CONTRACT_VERSION\" as const;\nconst CONTRACT_VERSION_PATTERN = /^\\d+\\.\\d+$/;\n\nfunction version<const TVersion extends ContractVersion>(\n contractVersion: TVersion,\n) {\n if (!CONTRACT_VERSION_PATTERN.test(contractVersion)) {\n throw new TypeError(\n `Invalid contract version \"${contractVersion}\". Expected MAJOR.MINOR.`,\n );\n }\n\n return (target: VersionedTarget): void => {\n Object.defineProperty(target, CONTRACT_VERSION_PROPERTY, {\n value: contractVersion,\n writable: false,\n configurable: false,\n enumerable: false,\n });\n };\n}\n\nexport {\n CONTRACT_VERSION_PROPERTY,\n type ContractVersion,\n version,\n type VersionedTarget,\n};\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\nimport { assertValidAggregateVersion } from \"../shared/aggregate-version.js\";\nimport { assertValidDate, cloneDate } from \"../shared/temporal-guards.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * The minimal persisted shape needed to reconstitute an {@link Entity}.\n *\n * This is the contract between storage and the domain: a repository maps a row\n * (or document) onto these four fields and hands them to a subclass constructor.\n * `aggregateVersion` travels with the state so optimistic-concurrency checks\n * survive a round-trip through the database.\n */\ninterface EntityState<TIdentifier> {\n readonly id: TIdentifier;\n readonly createdAt: Date;\n readonly updatedAt: Date;\n readonly aggregateVersion: number;\n}\n\n/**\n * Base class for domain entities — objects defined by a stable identity rather\n * than by their attributes. Two entities are \"the same\" when their `id`\n * matches, even if every other field differs; this is the opposite of a\n * {@link ValueObject}, which is defined entirely by its contents.\n *\n * The class owns the bookkeeping common to every aggregate root: a creation\n * timestamp that never changes, a last-modified timestamp, and an\n * `aggregateVersion` counter used for optimistic concurrency control. All three\n * are validated on construction and the dates are defensively cloned, so an\n * entity can never be built into — or leak — an inconsistent temporal state.\n *\n * @typeParam TIdentifier - The identity type (e.g. a branded string id or a VO).\n */\n@version(\"1.0\")\nabstract class Entity<TIdentifier> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n private readonly _id: TIdentifier;\n private readonly _createdAt: Date;\n private _updatedAt: Date;\n private _aggregateVersion: number;\n\n /**\n * Reconstitutes an entity from its persisted {@link EntityState}.\n *\n * Validates the temporal invariants up front so an invalid entity is\n * impossible to construct: both dates must be valid, the aggregate version\n * must be a non-negative integer, and `updatedAt` may not predate\n * `createdAt`. Both dates are cloned on the way in so a later mutation of\n * the caller's `Date` objects cannot reach into the entity's internal state.\n *\n * Declared `protected` because entities are reconstituted through a\n * subclass factory, never instantiated directly by application code.\n *\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected constructor(state: EntityState<TIdentifier>) {\n assertValidDate(\"createdAt\", state.createdAt);\n assertValidDate(\"updatedAt\", state.updatedAt);\n assertValidAggregateVersion(state.aggregateVersion);\n\n if (state.updatedAt.getTime() < state.createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._id = state.id;\n this._createdAt = cloneDate(state.createdAt);\n this._updatedAt = cloneDate(state.updatedAt);\n this._aggregateVersion = state.aggregateVersion;\n }\n\n /** The entity's stable identity — the basis for equality between entities. */\n public get id(): TIdentifier {\n return this._id;\n }\n\n /**\n * When the entity was first created.\n *\n * Returns a clone so callers cannot mutate the entity's internal `Date`;\n * the value is fixed at construction and never changes thereafter.\n */\n public get createdAt(): Date {\n return cloneDate(this._createdAt);\n }\n\n /**\n * When the entity was last modified.\n *\n * Returns a clone for the same encapsulation reason as {@link createdAt};\n * the underlying value advances only through {@link markAsModified}.\n */\n public get updatedAt(): Date {\n return cloneDate(this._updatedAt);\n }\n\n /**\n * Monotonic counter incremented on every mutation, used for optimistic\n * concurrency control: a writer reads this value, and the persistence layer\n * rejects the write if the stored version has moved on in the meantime.\n */\n public get aggregateVersion(): number {\n return this._aggregateVersion;\n }\n\n /**\n * The schema/contract version stamped on this entity type by the\n * `@version` decorator — used to detect and migrate state persisted under\n * an older shape.\n */\n public get contractVersion(): ContractVersion {\n return Entity.CONTRACT_VERSION;\n }\n\n /**\n * The single seam through which an entity records a mutation: it advances\n * `updatedAt` and bumps {@link aggregateVersion} by one. Subclasses must\n * call this from every state-changing method so the version counter stays\n * an accurate optimistic-lock token.\n *\n * @param updatedAt - The modification instant; defaults to now. Validated\n * and required not to predate `createdAt`, preserving the same invariant\n * the constructor enforces.\n * @returns The new aggregate version after the increment.\n * @throws {InvariantViolationException} When `updatedAt` is earlier than `createdAt`.\n */\n protected markAsModified(updatedAt: Date = new Date()): number {\n assertValidDate(\"updatedAt\", updatedAt);\n\n if (updatedAt.getTime() < this._createdAt.getTime()) {\n throw new InvariantViolationException(\n \"updatedAt cannot be earlier than createdAt\",\n );\n }\n\n this._updatedAt = cloneDate(updatedAt);\n this._aggregateVersion += 1;\n\n return this._aggregateVersion;\n }\n}\n\nexport { Entity, type EntityState };\n","import { InvariantViolationException } from \"../exceptions/invariant-violation-exception.js\";\n\ntype PrimitiveValue =\n | bigint\n | boolean\n | null\n | number\n | string\n | symbol\n | undefined;\n\ntype DeepReadonly<T> = T extends PrimitiveValue | Date\n ? T\n : T extends readonly (infer TItem)[]\n ? readonly DeepReadonly<TItem>[]\n : { readonly [TKey in keyof T]: DeepReadonly<T[TKey]> };\n\nfunction deepFreeze<T>(value: T): T {\n return deepFreezeInternal(value, new WeakSet<object>());\n}\n\nfunction deepFreezeInternal<T>(value: T, seen: WeakSet<object>): T {\n // Primitives and `null` need no freezing. `Date` is intentionally returned\n // as-is: `Object.freeze` cannot stop a Date's mutators (`setTime`,\n // `setFullYear`, …) because they write an internal slot, not an own\n // property — freezing it is a no-op against mutation. `makeImmutable`\n // already hands us a `structuredClone` copy, so the caller's original Date\n // is never aliased; deep-freezing of nested Dates is deliberately skipped.\n if (typeof value !== \"object\" || value === null || value instanceof Date) {\n return value;\n }\n\n // A value already on `seen` has been visited on this pass (cyclic graph or a\n // shared reference); revisiting it would recurse forever.\n if (seen.has(value)) {\n return value;\n }\n seen.add(value);\n\n if (Array.isArray(value)) {\n for (const item of value) {\n deepFreezeInternal(item, seen);\n }\n\n return Object.freeze(value);\n }\n\n const objectValue = value as Record<PropertyKey, object | PrimitiveValue>;\n\n for (const propertyKey of Reflect.ownKeys(objectValue)) {\n deepFreezeInternal(objectValue[propertyKey], seen);\n }\n\n return Object.freeze(value);\n}\n\nfunction makeImmutable<T>(value: T): DeepReadonly<T> {\n if (typeof value !== \"object\" || value === null) {\n return value as DeepReadonly<T>;\n }\n\n let snapshot: T;\n try {\n snapshot = structuredClone(value);\n } catch (error) {\n // `structuredClone` throws `DataCloneError` for functions, symbols and\n // class instances. Surface it as a domain invariant instead of leaking\n // a host-specific runtime error to callers building value objects.\n throw new InvariantViolationException(\n `makeImmutable requires a structured-cloneable value: ${\n error instanceof Error ? error.message : String(error)\n }`,\n );\n }\n\n return deepFreeze(snapshot) as DeepReadonly<T>;\n}\n\nexport { deepFreeze, makeImmutable, type DeepReadonly };\n","import { type DeepReadonly, makeImmutable } from \"../shared/immutable.js\";\nimport { type ContractVersion, version } from \"../versioning/version.js\";\n\n/**\n * Base class for value objects — domain concepts defined entirely by their\n * contents, with no identity of their own. Two value objects are\n * interchangeable when they hold equal data, which is the opposite of an\n * {@link Entity} (compared by id). Money, a CPF, a date range: replacing one\n * instance with an equal one changes nothing about the model.\n *\n * Immutability is the defining guarantee here. The wrapped `value` is\n * deep-frozen on construction, so a value object can be shared freely without\n * any risk of a consumer mutating shared state. Subclasses seal the instance\n * itself with {@link finalize} once their own fields are set.\n *\n * @typeParam T - The shape of the wrapped data.\n * @typeParam P - The primitive form produced by {@link toPrimitive} / {@link toJSON}.\n */\n@version(\"1.0\")\nabstract class ValueObject<T, P> {\n declare public static readonly CONTRACT_VERSION: ContractVersion;\n\n /** The wrapped data, deep-frozen so it can never be mutated after construction. */\n public readonly value: DeepReadonly<T>;\n\n /**\n * Wraps `value`, deep-freezing it so the value object is immutable from the\n * moment it exists. Declared `protected` because value objects are built\n * through a validating subclass factory, never instantiated directly.\n */\n protected constructor(value: T) {\n this.value = makeImmutable(value);\n }\n\n /**\n * The schema/contract version stamped on this value-object type by the\n * `@version` decorator — used to detect state persisted under an older shape.\n */\n public get contractVersion(): ContractVersion {\n return ValueObject.CONTRACT_VERSION;\n }\n\n /**\n * Freezes the instance shell, blocking reassignment of any own field.\n *\n * `value` is already deep-frozen by the constructor, so the wrapped data is\n * immutable regardless. The instance itself is NOT frozen automatically\n * because a subclass may still need to assign its own fields after\n * `super(value)` runs. Call `finalize()` at the very end of the subclass\n * constructor (after all fields are set) to make the whole value object\n * immutable.\n */\n protected finalize(): void {\n Object.freeze(this);\n }\n\n /**\n * Hook for `JSON.stringify`. Delegates to {@link toPrimitive} so a value\n * object serializes to its primitive form rather than exposing the internal\n * `value` wrapper.\n */\n public toJSON(): P {\n return this.toPrimitive();\n }\n\n /**\n * Compares this value object with another by content. Because value objects\n * carry no identity, subclasses implement equality over the wrapped data\n * (typically the primitive form), so two independently constructed instances\n * holding the same data are considered equal.\n */\n public abstract equals(other: this): boolean;\n\n /**\n * Projects the value object down to a plain, serializable primitive form —\n * the representation suitable for persistence, transport, or comparison.\n */\n public abstract toPrimitive(): P;\n}\n\nexport { type DeepReadonly, ValueObject };\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":"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"}
1
+ {"version":3,"file":"index.js","names":["version","version"],"sources":["../src/version.ts","../src/index.ts"],"sourcesContent":["// Versao do kit, sincronizada com package.json por scripts/sync-kit-version.mjs.\n// Nao edite a mao: rode `npm run sync-kit-version` (ou e regenerado no release).\n//\n// Mantemos a versao aqui, dentro de src/, para que a copia full-control seja\n// auto-contida: ao copiar so o conteudo de src/, o entry nao depende de um\n// `../package.json` que deixaria de existir no projeto consumidor.\nexport const version = \"1.2.0\";\n","import { version } from \"./version.js\";\n\nexport * from \"./core/index.js\";\n\nexport const ERP_CORE_NAME = \"erp-core\";\nexport const ERP_CORE_VERSION = version;\n\nexport const erpCoreRelease = {\n name: ERP_CORE_NAME,\n version: ERP_CORE_VERSION,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAMA,MAAaA,YAAU;;;ACFvB,MAAa,gBAAgB;AAC7B,MAAa,mBAAmBC;AAEhC,MAAa,iBAAiB;CAC1B,MAAM;CACN,SAAS;AACb"}
@@ -0,0 +1,30 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/business-rule-violation-exception.ts
3
+ var BusinessRuleViolationException = class extends DomainException {
4
+ constructor(rule, message) {
5
+ super(message);
6
+ this.rule = rule;
7
+ }
8
+ };
9
+ //#endregion
10
+ //#region src/core/exceptions/entity-not-found-exception.ts
11
+ var EntityNotFoundException = class extends DomainException {
12
+ constructor(entityName, identifier) {
13
+ super(`${entityName} with identifier ${identifier} was not found.`);
14
+ this.entityName = entityName;
15
+ this.identifier = identifier;
16
+ }
17
+ };
18
+ //#endregion
19
+ //#region src/core/exceptions/invalid-state-transition-exception.ts
20
+ var InvalidStateTransitionException = class extends DomainException {
21
+ constructor(from, to, message) {
22
+ super(message);
23
+ this.from = from;
24
+ this.to = to;
25
+ }
26
+ };
27
+ //#endregion
28
+ export { EntityNotFoundException as n, BusinessRuleViolationException as r, InvalidStateTransitionException as t };
29
+
30
+ //# sourceMappingURL=invalid-state-transition-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invalid-state-transition-exception.js","names":[],"sources":["../src/core/exceptions/business-rule-violation-exception.ts","../src/core/exceptions/entity-not-found-exception.ts","../src/core/exceptions/invalid-state-transition-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass BusinessRuleViolationException extends DomainException {\n constructor(\n public readonly rule: string,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { BusinessRuleViolationException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass EntityNotFoundException extends DomainException {\n constructor(\n public readonly entityName: string,\n public readonly identifier: string,\n ) {\n super(`${entityName} with identifier ${identifier} was not found.`);\n }\n}\n\nexport { EntityNotFoundException };\n","import { DomainException } from \"./domain-exception.js\";\n\nclass InvalidStateTransitionException<\n TState extends string = string,\n> extends DomainException {\n constructor(\n public readonly from: TState,\n public readonly to: TState,\n message: string,\n ) {\n super(message);\n }\n}\n\nexport { InvalidStateTransitionException };\n"],"mappings":";;AAEA,IAAM,iCAAN,cAA6C,gBAAgB;CACzD,YACI,MACA,SACF;EACE,MAAM,OAAO;EAHG,KAAA,OAAA;CAIpB;AACJ;;;ACPA,IAAM,0BAAN,cAAsC,gBAAgB;CAClD,YACI,YACA,YACF;EACE,MAAM,GAAG,WAAW,mBAAmB,WAAW,gBAAgB;EAHlD,KAAA,aAAA;EACA,KAAA,aAAA;CAGpB;AACJ;;;ACPA,IAAM,kCAAN,cAEU,gBAAgB;CACtB,YACI,MACA,IACA,SACF;EACE,MAAM,OAAO;EAJG,KAAA,OAAA;EACA,KAAA,KAAA;CAIpB;AACJ"}
@@ -0,0 +1,11 @@
1
+ import { t as DomainException } from "./domain-exception.js";
2
+ //#region src/core/exceptions/invariant-violation-exception.ts
3
+ var InvariantViolationException = class extends DomainException {
4
+ constructor(message) {
5
+ super(message);
6
+ }
7
+ };
8
+ //#endregion
9
+ export { InvariantViolationException as t };
10
+
11
+ //# sourceMappingURL=invariant-violation-exception.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"invariant-violation-exception.js","names":[],"sources":["../src/core/exceptions/invariant-violation-exception.ts"],"sourcesContent":["import { DomainException } from \"./domain-exception.js\";\n\nclass InvariantViolationException extends DomainException {\n constructor(message: string) {\n super(message);\n }\n}\n\nexport { InvariantViolationException };\n"],"mappings":";;AAEA,IAAM,8BAAN,cAA0C,gBAAgB;CACtD,YAAY,SAAiB;EACzB,MAAM,OAAO;CACjB;AACJ"}
@@ -0,0 +1,54 @@
1
+ import { i as ErrorCodes, n as AppError } from "./unexpected-error.js";
2
+ //#region src/core/errors/business-rule-violation-error.ts
3
+ var BusinessRuleViolationError = class extends AppError {
4
+ constructor(rule, message, detail, options) {
5
+ const baseMetadata = detail ? {
6
+ rule,
7
+ detail
8
+ } : { rule };
9
+ const mergedMetadata = options?.metadata ? {
10
+ ...baseMetadata,
11
+ ...options.metadata
12
+ } : baseMetadata;
13
+ super(message, ErrorCodes.businessRuleViolation, {
14
+ ...options,
15
+ metadata: mergedMetadata
16
+ });
17
+ }
18
+ };
19
+ //#endregion
20
+ //#region src/core/errors/not-found-error.ts
21
+ /**
22
+ * Raised when a requested resource does not exist. Maps naturally onto an HTTP
23
+ * 404 at the edge, but stays transport-agnostic here.
24
+ *
25
+ * The `resource` name builds the message (`"<resource> not found"`) and, with
26
+ * the optional lookup `criteria`, lands in the metadata so logs show *what* was
27
+ * searched for without the caller having to restate it in the message.
28
+ */
29
+ var NotFoundError = class extends AppError {
30
+ /**
31
+ * @param resource - Human-readable name of the missing resource (e.g. `"Order"`).
32
+ * @param criteria - Optional lookup keys used in the search; recorded in
33
+ * metadata to aid debugging. Avoid putting sensitive values here.
34
+ * @param options - Optional cause, correlation ids, and extra metadata.
35
+ */
36
+ constructor(resource, criteria, options) {
37
+ const baseMetadata = criteria ? {
38
+ resource,
39
+ criteria
40
+ } : { resource };
41
+ const mergedMetadata = options?.metadata ? {
42
+ ...baseMetadata,
43
+ ...options.metadata
44
+ } : baseMetadata;
45
+ super(`${resource} not found`, ErrorCodes.notFound, {
46
+ ...options,
47
+ metadata: mergedMetadata
48
+ });
49
+ }
50
+ };
51
+ //#endregion
52
+ export { BusinessRuleViolationError as n, NotFoundError as t };
53
+
54
+ //# sourceMappingURL=not-found-error.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"not-found-error.js","names":[],"sources":["../src/core/errors/business-rule-violation-error.ts","../src/core/errors/not-found-error.ts"],"sourcesContent":["import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// BusinessRuleViolationError\n// ─────────────────────────────────────────────────────────────────────────────\n\nclass BusinessRuleViolationError extends AppError {\n constructor(\n rule: string,\n message: string,\n detail?: Record<string, unknown>,\n options?: AppErrorOptions,\n ) {\n const baseMetadata = detail ? { rule, detail } : { rule };\n const mergedMetadata = options?.metadata\n ? { ...baseMetadata, ...options.metadata }\n : baseMetadata;\n\n super(message, ErrorCodes.businessRuleViolation, {\n ...options,\n metadata: mergedMetadata,\n });\n }\n}\n\nexport { BusinessRuleViolationError };\n","import { AppError } from \"./app-error.js\";\nimport { ErrorCodes } from \"./error-codes.js\";\nimport type { AppErrorOptions } from \"./types.js\";\n\n// ─────────────────────────────────────────────────────────────────────────────\n// NotFoundError\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Raised when a requested resource does not exist. Maps naturally onto an HTTP\n * 404 at the edge, but stays transport-agnostic here.\n *\n * The `resource` name builds the message (`\"<resource> not found\"`) and, with\n * the optional lookup `criteria`, lands in the metadata so logs show *what* was\n * searched for without the caller having to restate it in the message.\n */\nclass NotFoundError extends AppError {\n /**\n * @param resource - Human-readable name of the missing resource (e.g. `\"Order\"`).\n * @param criteria - Optional lookup keys used in the search; recorded in\n * metadata to aid debugging. Avoid putting sensitive values here.\n * @param options - Optional cause, correlation ids, and extra metadata.\n */\n constructor(\n resource: string,\n criteria?: Record<string, unknown>,\n options?: AppErrorOptions,\n ) {\n const baseMetadata = criteria ? { resource, criteria } : { resource };\n const mergedMetadata = options?.metadata\n ? { ...baseMetadata, ...options.metadata }\n : baseMetadata;\n\n super(`${resource} not found`, ErrorCodes.notFound, {\n ...options,\n metadata: mergedMetadata,\n });\n }\n}\n\nexport { NotFoundError };\n"],"mappings":";;AAQA,IAAM,6BAAN,cAAyC,SAAS;CAC9C,YACI,MACA,SACA,QACA,SACF;EACE,MAAM,eAAe,SAAS;GAAE;GAAM;EAAO,IAAI,EAAE,KAAK;EACxD,MAAM,iBAAiB,SAAS,WAC1B;GAAE,GAAG;GAAc,GAAG,QAAQ;EAAS,IACvC;EAEN,MAAM,SAAS,WAAW,uBAAuB;GAC7C,GAAG;GACH,UAAU;EACd,CAAC;CACL;AACJ;;;;;;;;;;;ACTA,IAAM,gBAAN,cAA4B,SAAS;;;;;;;CAOjC,YACI,UACA,UACA,SACF;EACE,MAAM,eAAe,WAAW;GAAE;GAAU;EAAS,IAAI,EAAE,SAAS;EACpE,MAAM,iBAAiB,SAAS,WAC1B;GAAE,GAAG;GAAc,GAAG,QAAQ;EAAS,IACvC;EAEN,MAAM,GAAG,SAAS,aAAa,WAAW,UAAU;GAChD,GAAG;GACH,UAAU;EACd,CAAC;CACL;AACJ"}
@@ -0,0 +1,140 @@
1
+ //#region src/core/result/result.d.ts
2
+ /**
3
+ * Represents the outcome of an operation that may succeed or fail.
4
+ * Useful for avoiding excessive exceptions and making error flows explicit.
5
+ */
6
+ declare abstract class Result<T, E> {
7
+ protected constructor();
8
+ /**
9
+ * Creates a success result containing a value.
10
+ */
11
+ static ok<T>(value: T): Result<T, never>;
12
+ /**
13
+ * Creates an error result containing an error object.
14
+ */
15
+ static err<E>(error: E): Result<never, E>;
16
+ /**
17
+ * Returns true when this is a success result.
18
+ */
19
+ abstract isOk(): this is Ok<T>;
20
+ /**
21
+ * Returns true when this is an error result.
22
+ */
23
+ abstract isErr(): this is Err<E>;
24
+ /**
25
+ * Runs a handler based on the result state (similar to pattern matching).
26
+ */
27
+ abstract match<R>(handlers: {
28
+ ok: (value: T) => R;
29
+ err: (error: E) => R;
30
+ }): R;
31
+ /**
32
+ * Returns the value when this is success, or null when this is an error.
33
+ */
34
+ getOrNull(): T | null;
35
+ /**
36
+ * Returns the error when this is a failure, or null when this is a success.
37
+ */
38
+ errorOrNull(): E | null;
39
+ /**
40
+ * Returns the value when this is a success, or throws the error when this is a failure.
41
+ */
42
+ getOrThrow(): T;
43
+ /**
44
+ * Transforms the success value using the provided function. Keeps the error when this is a failure.
45
+ */
46
+ map<R>(transform: (value: T) => R): Result<R, E>;
47
+ /**
48
+ * Transforms the error using the provided function. Keeps the value when this is a success.
49
+ */
50
+ mapError<F>(transform: (error: E) => F): Result<T, F>;
51
+ /**
52
+ * Chains another operation that returns a Result when this result is a success.
53
+ */
54
+ flatMap<R>(transform: (value: T) => Result<R, E>): Result<R, E>;
55
+ }
56
+ /**
57
+ * Success variant of Result.
58
+ */
59
+ declare class Ok<T> extends Result<T, never> {
60
+ readonly value: T;
61
+ constructor(value: T);
62
+ isOk(): this is Ok<T>;
63
+ isErr(): this is Err<never>;
64
+ match<R>(handlers: {
65
+ ok: (value: T) => R;
66
+ err: (error: never) => R;
67
+ }): R;
68
+ }
69
+ /**
70
+ * Error variant of Result.
71
+ */
72
+ declare class Err<E> extends Result<never, E> {
73
+ readonly error: E;
74
+ constructor(error: E);
75
+ isOk(): this is Ok<never>;
76
+ isErr(): this is Err<E>;
77
+ match<R>(handlers: {
78
+ ok: (value: never) => R;
79
+ err: (error: E) => R;
80
+ }): R;
81
+ }
82
+ //#endregion
83
+ //#region src/core/result/outcome.d.ts
84
+ /**
85
+ * Outcome — Business decision abstraction.
86
+ *
87
+ * Represents the semantic result of a domain decision, policy evaluation,
88
+ * or business rule. NOT for technical success/failure — use Result for that.
89
+ *
90
+ * Mental model:
91
+ * "What was the business decision?"
92
+ * NOT "Did the operation succeed?"
93
+ *
94
+ * The status axis represents valid business outcomes (APPROVED, REJECTED,
95
+ * ALLOW, DENY, NO_OP, etc.), never technical Ok/Err.
96
+ *
97
+ * @typeParam S - Union of valid status literals for this outcome
98
+ * @typeParam D - Shape of the decision data carried by this outcome
99
+ */
100
+ declare class Outcome<S extends string, D = undefined> {
101
+ readonly status: S;
102
+ readonly data: D;
103
+ readonly reason: string | undefined;
104
+ readonly metadata: Readonly<Record<string, unknown>>;
105
+ private constructor();
106
+ static of<S extends string, D = undefined>(status: S, data: D, reason?: string, metadata?: Record<string, unknown>): Outcome<S, D>;
107
+ static approved<D = undefined>(data: D, reason?: string): Outcome<"APPROVED", D>;
108
+ static rejected<D = undefined>(data: D, reason: string): Outcome<"REJECTED", D>;
109
+ static noOp<D = undefined>(data: D, reason?: string): Outcome<"NO_OP", D>;
110
+ static deferred<D = undefined>(data: D, reason: string): Outcome<"DEFERRED", D>;
111
+ static requiresReview<D = undefined>(data: D, reason: string): Outcome<"REQUIRES_REVIEW", D>;
112
+ /**
113
+ * Narrows this Outcome to a specific status.
114
+ *
115
+ * @example
116
+ * if (outcome.is('DENY')) {
117
+ * outcome.data.violations // TS knows status is 'DENY'
118
+ * }
119
+ */
120
+ is<T extends S>(status: T): this is Outcome<T, D>;
121
+ /**
122
+ * Exhaustive pattern match over all possible statuses.
123
+ * TypeScript enforces that every status has a handler.
124
+ *
125
+ * @example
126
+ * outcome.match({
127
+ * ALLOW: (o) => handleAllow(o.data),
128
+ * DENY: (o) => handleDeny(o.data.violations),
129
+ * })
130
+ */
131
+ match<THandlers extends { [K in S]: (outcome: Outcome<K, D>) => unknown }>(handlers: THandlers): ReturnType<THandlers[S]>;
132
+ withMetadata(extra: Record<string, unknown>): Outcome<S, D>;
133
+ withReason(reason: string): Outcome<S, D>;
134
+ toString(): string;
135
+ }
136
+ /** Common business outcome statuses. Extend per domain as needed. */
137
+ type CommonOutcomeStatus = "APPROVED" | "REJECTED" | "NO_OP" | "DEFERRED" | "REQUIRES_REVIEW";
138
+ //#endregion
139
+ export { Result as a, Ok as i, Outcome as n, Err as r, CommonOutcomeStatus as t };
140
+ //# sourceMappingURL=outcome.d.ts.map
package/dist/outcome.js CHANGED
@@ -1,4 +1,4 @@
1
- import { g as InvariantViolationException } from "./gate-v1-payload.schema.js";
1
+ import { t as InvariantViolationException } from "./invariant-violation-exception.js";
2
2
  //#region src/core/result/outcome.ts
3
3
  /**
4
4
  * Outcome — Business decision abstraction.
@@ -1,58 +1,7 @@
1
- import { I as Result, c as PolicyViolation, d as GatePayloadV1, g as CoreConfig, h as Outcome, l as VersionedGateEngine, p as ConditionNode, s as PolicyContext, t as GateOutcome, u as GatePayload } from "./gate-types.js";
2
- import { z } from "zod";
1
+ import { a as Result } from "./outcome.js";
2
+ import { d as GatePayloadV1, s as PolicyContext, u as GatePayload } from "./gate-types.js";
3
+ import { a as ComputeOutcome, c as VersionedComputeEngine, i as ComputeEvaluatorRegistration, l as ComputePayload, p as ComputePayloadV1, r as ComputeEvaluator } from "./gate-engine-registry.js";
3
4
 
4
- //#region src/core/policies/engines/v1/compute/compute-payload.schema.d.ts
5
- interface ComputeParamsPayload {
6
- readonly type: "params";
7
- readonly data: Readonly<Record<string, unknown>>;
8
- }
9
- interface ComputeDecisionTableRule<R = unknown> {
10
- readonly conditions: ConditionNode;
11
- readonly result: R;
12
- }
13
- interface ComputeDecisionTablePayload<R = unknown> {
14
- readonly type: "decision-table";
15
- readonly rules: readonly ComputeDecisionTableRule<R>[];
16
- readonly default: R;
17
- }
18
- type ComputePayloadV1 = ComputeDecisionTablePayload<unknown> | ComputeParamsPayload;
19
- //#endregion
20
- //#region src/core/policies/engines/compute-payload.d.ts
21
- type ComputePayload = ComputePayloadV1;
22
- //#endregion
23
- //#region src/core/policies/engines/compute-types.d.ts
24
- type ComputeStatus = "OK" | "NOT_APPLICABLE" | "ERROR";
25
- interface ComputeOutcomeData {
26
- readonly values: unknown | null;
27
- readonly violations: readonly PolicyViolation[];
28
- }
29
- /** Semantic outcome of a COMPUTE policy evaluation. */
30
- type ComputeOutcome = Outcome<ComputeStatus, ComputeOutcomeData>;
31
- /**
32
- * Pure compute operation: receives a resolved value + context, returns a
33
- * business decision. Registration metadata (policy key/version) lives outside
34
- * this contract.
35
- *
36
- * The engine resolves the structural payload before calling the evaluator:
37
- * - `params` -> `payload.data`
38
- * - `decision-table` -> matching `rule.result` or `default`
39
- *
40
- * Result wraps technical failures (invalid value shape).
41
- * Outcome carries the semantic business decision.
42
- */
43
- interface ComputeEvaluator {
44
- evaluate(resolvedValue: unknown, context: Record<string, unknown>): Result<ComputeOutcome, string>;
45
- }
46
- interface ComputeEvaluatorRegistration {
47
- readonly policyKey: string;
48
- readonly version: number;
49
- readonly evaluator: ComputeEvaluator;
50
- }
51
- interface VersionedComputeEngine {
52
- readonly version: number;
53
- evaluate(payload: ComputePayload, context: PolicyContext, evaluator: ComputeEvaluator): Result<ComputeOutcome, string>;
54
- }
55
- //#endregion
56
5
  //#region src/core/policies/engines/compute-evaluator-registry.d.ts
57
6
  declare class ComputeEvaluatorRegistry {
58
7
  private readonly evaluators;
@@ -75,29 +24,6 @@ declare class ComputeEngineRegistry {
75
24
  }): Result<ComputeOutcome, string>;
76
25
  }
77
26
  //#endregion
78
- //#region src/core/policies/engines/compute-registry.d.ts
79
- interface ComputeRegistryOptions {
80
- readonly coreConfig?: CoreConfig;
81
- }
82
- declare class ComputeRegistry {
83
- private readonly engines;
84
- private readonly evaluators;
85
- constructor(params?: ComputeRegistryOptions);
86
- register(registration: ComputeEvaluatorRegistration): void;
87
- registerEngine(engine: VersionedComputeEngine): void;
88
- getEngine(version: number): VersionedComputeEngine | undefined;
89
- getEvaluator(policyKey: string, version: number): ComputeEvaluator | undefined;
90
- evaluate(policyKey: string, computeEngineVersion: number, payloadSchemaVersion: number, payload: unknown, context: PolicyContext): Result<ComputeOutcome, string>;
91
- }
92
- //#endregion
93
- //#region src/core/policies/engines/gate-engine-registry.d.ts
94
- declare class GateEngineRegistry {
95
- private readonly engines;
96
- register(engine: VersionedGateEngine): void;
97
- get(version: number): VersionedGateEngine | undefined;
98
- evaluate(version: number, payload: unknown, context: PolicyContext): Result<GateOutcome, string>;
99
- }
100
- //#endregion
101
27
  //#region src/core/policies/engines/parse-compute-payload.d.ts
102
28
  type ComputePayloadParser = (payload: unknown) => Result<ComputePayload, string>;
103
29
  declare class ComputePayloadParserRegistry {
@@ -132,5 +58,5 @@ declare class GatePayloadParsers {
132
58
  static parse(engineVersion: number, payload: unknown): Result<GatePayloadV1, string>;
133
59
  }
134
60
  //#endregion
135
- export { ComputePayload as _, ComputePayloadParserRegistry as a, ComputeParamsPayload as b, ComputeRegistry as c, ComputeEvaluator as d, ComputeEvaluatorRegistration as f, VersionedComputeEngine as g, ComputeStatus as h, ComputePayloadParser as i, ComputeEngineRegistry as l, ComputeOutcomeData as m, GatePayloadParserRegistry as n, ComputePayloadParsers as o, ComputeOutcome as p, GatePayloadParsers as r, GateEngineRegistry as s, GatePayloadParser as t, ComputeEvaluatorRegistry as u, ComputeDecisionTablePayload as v, ComputePayloadV1 as x, ComputeDecisionTableRule as y };
61
+ export { ComputePayloadParserRegistry as a, ComputeEvaluatorRegistry as c, ComputePayloadParser as i, GatePayloadParserRegistry as n, ComputePayloadParsers as o, GatePayloadParsers as r, ComputeEngineRegistry as s, GatePayloadParser as t };
136
62
  //# sourceMappingURL=parse-gate-payload.d.ts.map
package/dist/path.d.ts ADDED
@@ -0,0 +1,90 @@
1
+ import { a as Result } from "./outcome.js";
2
+ import { m as CoreConfig } from "./gate-types.js";
3
+ import { D as PolicyDefinition, N as PolicyCatalog, P as PolicyCatalogEntryProps, S as PolicyDefinitionRepository, T as FindCandidatesParams, m as ContextResolverRegistry, y as ContextValueResolver } from "./policy-service.js";
4
+ import { i as ComputeEvaluatorRegistration } from "./gate-engine-registry.js";
5
+
6
+ //#region src/core/config/core-config.instance.d.ts
7
+
8
+ /**
9
+ * Shared instance for the application composition root.
10
+ * Use `new CoreConfig()` for isolated runtimes, tests, or multi-tenant hosts.
11
+ *
12
+ * The default reporter is silent so the core has no runtime logging dependency.
13
+ * Hosts can swap in their own `PolicyReporter` via
14
+ * `coreConfig.configure({ observability: { reporter } })`.
15
+ */
16
+ declare const coreConfig: CoreConfig;
17
+ //#endregion
18
+ //#region src/core/policies/utils/hash.d.ts
19
+ /**
20
+ * Produces a deterministic SHA-256 hex digest of a canonical JSON representation.
21
+ * Object keys are sorted recursively so key order does not affect the hash.
22
+ * Array item order is preserved on purpose; callers that treat arrays as sets
23
+ * must normalize or sort them before hashing.
24
+ *
25
+ * Values that JSON.stringify would silently drop or coerce (undefined,
26
+ * non-finite numbers, functions, symbols, bigint) are rejected up-front to
27
+ * prevent semantically different payloads from collapsing to the same hash.
28
+ */
29
+ declare class PolicyHashing {
30
+ static sha256(input: string): string;
31
+ private static assertHashable;
32
+ static canonicalJson(value: unknown): string;
33
+ static computePayloadHash(payload: unknown, policyKey: string, policyVersion: string): string;
34
+ }
35
+ //#endregion
36
+ //#region src/core/policies/defs/in-memory-policy-definition-repo.d.ts
37
+ declare class InMemoryPolicyDefinitionRepository implements PolicyDefinitionRepository {
38
+ private readonly definitions;
39
+ private readonly definitionsByPolicyKey;
40
+ constructor(definitions: readonly PolicyDefinition[]);
41
+ findCandidates(params: FindCandidatesParams): PolicyDefinition[];
42
+ }
43
+ //#endregion
44
+ //#region src/core/policies/package/policy-package.d.ts
45
+ /**
46
+ * Protocol of contribution: a module declares what it wants to add to the
47
+ * policy system without the core knowing which module it is.
48
+ *
49
+ * - catalogEntries: static policy descriptors the catalog will register.
50
+ * - definitions: default policy definitions (rules/parameters) to seed.
51
+ * - evaluators: compute evaluator registrations keyed by policy/version.
52
+ */
53
+ interface PolicyPackage {
54
+ readonly catalogEntries: readonly PolicyCatalogEntryProps[];
55
+ readonly definitions: readonly PolicyDefinition[];
56
+ readonly evaluators: readonly ComputeEvaluatorRegistration[];
57
+ }
58
+ //#endregion
59
+ //#region src/core/policies/catalog/catalog.instance.d.ts
60
+ /**
61
+ * Aggregates catalog entries contributed by each module package into a single
62
+ * PolicyCatalog. The core knows nothing about concrete modules — callers
63
+ * are responsible for passing all relevant packages at composition time.
64
+ */
65
+ declare class PolicyCatalogFactory {
66
+ static build(packages: readonly PolicyPackage[]): PolicyCatalog;
67
+ }
68
+ //#endregion
69
+ //#region src/core/policies/context/context-registry.instance.d.ts
70
+ /**
71
+ * Official instance of the ContextResolverRegistry.
72
+ * Use `new ContextResolverRegistry()` plus `registerNamespacedContextResolversIn`
73
+ * when each runtime/composition root needs its own isolated resolver graph.
74
+ */
75
+ declare const contextResolverRegistry: ContextResolverRegistry;
76
+ declare function registerNamespacedContextResolvers(namespace: string, resolvers: readonly ContextValueResolver[]): Result<ContextResolverRegistry, string>;
77
+ //#endregion
78
+ //#region src/core/policies/context/path.d.ts
79
+ declare class PolicyContextPath {
80
+ private static readonly FORBIDDEN_SEGMENTS;
81
+ private static resolve;
82
+ private static parseSegments;
83
+ private static isPlainRecord;
84
+ static getOrAbsent(obj: Record<string, unknown>, path: string): Result<unknown, "absent">;
85
+ static has(obj: Record<string, unknown>, path: string): boolean;
86
+ static set(obj: Record<string, unknown>, path: string, value: unknown): Result<void, string>;
87
+ }
88
+ //#endregion
89
+ export { PolicyPackage as a, coreConfig as c, PolicyCatalogFactory as i, contextResolverRegistry as n, InMemoryPolicyDefinitionRepository as o, registerNamespacedContextResolvers as r, PolicyHashing as s, PolicyContextPath as t };
90
+ //# sourceMappingURL=path.d.ts.map
@@ -0,0 +1,85 @@
1
+ //#region src/core/plugins/types.d.ts
2
+ /**
3
+ * Common shape every plugin shares, regardless of the contract it implements.
4
+ * Carries the metadata the {@link PluginManager} uses to identify, order and
5
+ * toggle plugins.
6
+ */
7
+ interface BasePlugin {
8
+ /** Unique identifier, used for logs / debugging and for enable/disable. */
9
+ readonly name: string;
10
+ /** Weight; the highest priority wins (default = 0). */
11
+ readonly priority?: number;
12
+ /** Shortcut to disable a plugin without removing it. */
13
+ enabled?: boolean;
14
+ }
15
+ /**
16
+ * A plugin contract is a record whose values are the methods plugins may
17
+ * implement for a given extension point.
18
+ *
19
+ * `any` here is intentional: it is the only way to express the constraint
20
+ * "a record whose values are arbitrary functions". Using `unknown` for the
21
+ * parameters breaks assignment of concrete contracts by contravariance —
22
+ * TypeScript rejects functions with specific parameters as a subtype of
23
+ * `(...args: unknown[]) => unknown`.
24
+ */
25
+ type PluginContract = Record<string, (...args: any[]) => any>;
26
+ /**
27
+ * Reducer used in `pipeline` mode to combine the result of each plugin into a
28
+ * single accumulated value.
29
+ */
30
+ type PipelineReducer<R, P extends PluginContract> = (accumulated: R, current: R, plugin: P & BasePlugin, index: number) => R;
31
+ /** Options accepted by {@link PluginManager.invoke}. */
32
+ interface InvokeOptions<P extends PluginContract, K extends keyof P> {
33
+ /**
34
+ * `'first'` → returns the first enabled plugin with the highest priority.
35
+ * `'pipeline'` → runs every enabled plugin, combining results via `reducer`.
36
+ * default = `'first'`.
37
+ */
38
+ mode?: "first" | "pipeline";
39
+ /** Executed when no plugin is enabled for the method. */
40
+ fallback: P[K];
41
+ /** Reducer used only when `mode = "pipeline"`. */
42
+ reducer?: PipelineReducer<ReturnType<P[K]>, P>;
43
+ }
44
+ //#endregion
45
+ //#region src/core/plugins/plugin.d.ts
46
+ /**
47
+ * Registry that holds a set of plugins implementing a shared {@link PluginContract}
48
+ * and resolves which of them answer a given extension point.
49
+ *
50
+ * Plugins are kept sorted by priority (descending). For a given method,
51
+ * {@link invoke} either delegates to the highest-priority enabled plugin
52
+ * (`'first'`) or folds every enabled plugin into a single value (`'pipeline'`).
53
+ * When no plugin is enabled, the supplied `fallback` runs instead, so the host
54
+ * always has defined behaviour even with an empty registry.
55
+ *
56
+ * @typeParam P - The plugin contract this manager coordinates.
57
+ */
58
+ declare class PluginManager<P extends PluginContract> {
59
+ /** Internal list, kept sorted by priority (desc). */
60
+ private plugins;
61
+ /** Registers one or more plugins and re-sorts by priority. */
62
+ register(...plugins: (P & BasePlugin)[]): void;
63
+ /** Removes a previously registered plugin by name. */
64
+ unregister(name: string): void;
65
+ /** Enables a registered plugin by name. */
66
+ enable(name: string): void;
67
+ /** Disables a registered plugin by name (without removing it). */
68
+ disable(name: string): void;
69
+ /** Lists enabled plugins only, already in priority order. */
70
+ list(): readonly (P & BasePlugin)[];
71
+ /**
72
+ * Resolves `method` against the registered plugins.
73
+ *
74
+ * In `'first'` mode the highest-priority enabled plugin that implements
75
+ * `method` answers. In `'pipeline'` mode every enabled plugin runs and the
76
+ * results are folded with `reducer` (defaults to "keep the last result").
77
+ * When no enabled plugin implements `method`, `fallback` is called.
78
+ */
79
+ invoke<K extends keyof P>(method: K, args: Parameters<P[K]>, opts: InvokeOptions<P, K>): ReturnType<P[K]>;
80
+ /** Re-sorts the internal list by priority (desc; default priority = 0). */
81
+ private reorder;
82
+ }
83
+ //#endregion
84
+ export { PluginContract as a, PipelineReducer as i, BasePlugin as n, InvokeOptions as r, PluginManager as t };
85
+ //# sourceMappingURL=plugin.d.ts.map