core family
Entities, keys, events and pipelines, attributes and state machines, effects, definitions and prefabs, conditions, actions and interactions, assets, 2D spatial types, gauges and weighted picks.
Every symbol on this page is exported from the package root: import { Name } from "gamekit";
80 symbols.
| Symbol | Summary |
|---|---|
Action | class. Executes validation, transactional mutations, rollback, and post-commit notifications in fixed order. |
ActionContext | class. Per-execution request view and staging area shared by action validation and commit callbacks. |
ActionMutation | class. Named reversible unit of commit work with explicit applied state. |
ActionRequest | class. Immutable-by-convention invocation data for a named Action. |
ActionResult | class. Terminal action status with output, diagnostics, and mutation history available for compensation. |
ActionSequence | class. Executes action/request pairs in order and can compensate earlier commits after a later failure. |
ActionSequenceResult | class. Terminal status and per-step results from an ActionSequence execution. |
ActionSequenceStep | class. Binds one Action to the request used when its sequence reaches that step. |
ActionStatus | enum. Defines the closed action status value set. |
AssetCancellationToken | class. Cooperative cancellation flag observed between entries of an AssetLoadPlan. |
AssetFailure | class. Captures one failed or dependency-blocked asset-plan entry. |
AssetHandle | class. Retains one loaded asset until its owner releases the handle. |
AssetKey | class. Identifies one typed asset independently of its diagnostic label. |
AssetLoadPlan | class. Mutable dependency graph of asset keys with per-entry loader, weight, and retry policy. |
AssetLoadProgress | class. Mutable progress snapshot passed to an AssetManager plan callback after each outcome. |
AssetManager | class. Selects loaders, coalesces in-flight work, caches values, and unloads them after the final handle releases. |
AssetPlanEntry | class. One asset-plan node with dependency identities and load policy. |
AssetPlanResult | class. Aggregate handles, failures, counts, and cancellation state from one plan run. |
AssetScope | class. Groups asset handles so a scene, screen, or other owner can release them together. |
Attribute | class. Lazily computes a value from a base or dependency set, then applies ordered modifiers and a final clamp. |
AttributeInspection | class. Point-in-time diagnostic snapshot of an Attribute after refresh. |
AttributeModifier | class. Named pure transformation applied to an Attribute at an explicit priority. |
AttributeSubscription | class. Idempotent lifetime handle for one Attribute change observer. |
cloneValue | function. Deep-copies arrays, maps, and object properties while preserving primitive values. |
ComponentKey | class. Identifies one component capability or ECS store independently of its label. |
Condition | class. Normalizes boolean, string, or ConditionResult evaluators into composable diagnostic outcomes. |
ConditionResult | class. Normalized condition outcome with a primary explanation and optional aggregate reasons. |
ContextKey | class. Identifies a typed hierarchical context value without relying on string lookup. |
CyclicDefinition | class. Reports an inheritance cycle discovered while resolving definitions. |
CyclicDependency | class. Reports a directed dependency cycle, such as an asset load-plan loop. |
Definition | class. Immutable source definition with copied data and ordered parent ids. |
DefinitionError | class. Adds definition identity and provenance to a registry resolution failure. |
DefinitionRegistry | class. Resolves named definitions through ordered multiple inheritance and validator callbacks. |
DuplicateRegistration | class. Reports a second registration for an identity that must be unique. |
EffectApplication | class. Incoming typed effect payload and policy options passed through the application pipeline. |
EffectCollection | class. Owns effect handles, applies admission and stacking policy, and mirrors owner lifecycle callbacks. |
EffectHandle | class. Stable handle controlling one effect's lifecycle, timer, and source cleanup. |
EffectKey | class. Identifies an effect kind and its typed payload across an entity's collection. |
EffectOptions | class. Optional collision, source-lifetime, and timed-expiration policy for an effect. |
EffectRemovalReason | enum. Defines the closed effect removal reason value set. |
EffectStacking | class. Factory for common collision policies consumed by EffectCollection. |
EffectStackingContext | class. Collision-policy view of the incoming application and matching handles in insertion order. |
EffectStackingResolution | class. Policy decision naming accept, reject, replace, or refresh plus an optional retained handle. |
EffectState | enum. Defines the closed effect state value set. |
Entity | class. Owns a game object's hierarchy, local facts, components, and effects. |
EntityAllocator | class. Issues compact generational entity ids and recycles released slots without reviving stale handles. |
EntityId | class. Names one lifetime of an allocator slot using an index-and-generation pair. |
EntityState | enum. Defines the closed entity state value set. |
EntityTeardownQueue | class. Deduplicates deferred Entity disposal until an explicit FIFO flush boundary. |
EventKey | class. Identifies an event channel and statically carries the emitted payload type. |
EventScope | class. Owns typed local event listeners and delivers snapshot notifications in subscription order. |
EventSubscription | class. Idempotent handle controlling one listener's lifetime in an EventScope. |
FakeAssetLoader | class. Deterministic in-memory loader with configurable failures, delays, and call-order inspection. |
GameKitError | class. Base error type for GameKit style guide and lifecycle violations. |
Gauge | class. Neutral rate-filled value for cooldowns, charge bars and any meter that fills with time. |
InteractionContext | class. Typed actor, target, and environment tuple shared across interaction discovery. |
InteractionDefinition | class. Builds one executable offer from context, optional availability logic, and metadata. |
InteractionOffer | class. Point-in-time executable interaction choice produced during discovery. |
InteractionProvider | class. Named discovery callback that produces zero or more offers for one context. |
InteractionRegistry | class. Aggregates providers in registration order without imposing ranking or deduplication. |
InvalidArgument | class. Reports a public API argument that violates an immediate precondition. |
InvalidDefinition | class. Reports definition data that cannot be validated or resolved. |
ISpatialIndex | interface. Defines deterministic identity-based insertion and broad-phase 2D spatial queries. |
KeyedRegistry | class. Associates heterogeneous values with exact typed-key identities in registration order. |
LinearSpatialIndex | class. Simple insertion-ordered spatial index that linearly scans copied bounds. |
mergeData | function. Recursively overlays plain objects and maps, while other values replace the base. |
MissingRegistration | class. Reports a required typed-key, component, or definition registration that is absent. |
MutablePipeline | class. Runs mutable processing stages over one shared context snapshot in insertion order. |
PipelineContext | class. Mutable per-run input, cancellation flag, and optional output shared by pipeline stages. |
PipelineResult | class. Immutable-by-convention snapshot of a completed pipeline's cancellation and output state. |
PipelineSubscription | class. Idempotent lifetime handle for one stage in a MutablePipeline. |
Prefab | class. Reusable factory binding for one definition id in a specific registry. |
ResolvedDefinition | class. Fully merged definition data plus the ordered ids that contributed to it. |
StaleHandle | class. Reports mutation through an entity or effect handle whose lifetime has ended. |
StateMachine | class. Runs explicit named-state callbacks with guarded, FIFO transitions and optional clock scheduling. |
StateMachineInspection | class. Point-in-time diagnostic counters and lifecycle flags for a StateMachine. |
StateMachineState | class. Named state with optional owner callbacks for entry, exit, and fixed updates. |
Transform2D | class. Mutable 2D position, rotation, and scale value with no scene-graph ownership. |
TypedKey | class. Provides a process-unique, type-carrying identity for registries; labels are diagnostic only. |
WeightedPick | class. Weighted choice over an injected Random, the only source of chance, so a seed gives a fixed sequence. |
Action
ts
import { Action } from "gamekit";
class Action<TPayload, TData>Executes validation, transactional mutations, rollback, and post-commit notifications in fixed order. Validation denial never mutates; commit failure rolls back applied mutations in reverse order.
Members
ts
id: stringStable identifier for this Action.
ts
description: stringHuman-readable explanation of this item.
ts
constructor(id: string, description: string = "")Creates a named action with no conditions, validation stages, or commit callback.
ts
addCondition(condition: Condition<any>): Action<TPayload, TData>Appends a precondition and returns this action for fluent configuration.
ts
precondition(condition: Condition<any>): Action<TPayload, TData>Fluent alias for appending a condition.
ts
guard(condition: Condition<any>): Action<TPayload, TData>Fluent alias for appending a condition.
ts
validate(stage: Function): Action<TPayload, TData>Appends a validation callback that may deny through context or throw failure.
ts
onCommit(commitFn: Function): Action<TPayload, TData>Replaces the callback that stages or applies commit work after validation.
ts
execute(request: ActionRequest<TPayload>, targetScope: EventScope | null = null): ActionResult<TData>Runs conditions and validators, commits staged mutations, then emits notifications. Notification failures are isolated after a successful commit.
ActionContext
ts
import { ActionContext } from "gamekit";
class ActionContext<TPayload>Per-execution request view and staging area shared by action validation and commit callbacks.
Members
ts
request: ActionRequest<TPayload>Original request that owns this execution.
ts
actor: anyActor reference copied from the request for callback convenience.
ts
target: anyTarget reference copied from the request for callback convenience.
ts
payload: TPayloadTyped payload copied from the request.
ts
metadata: anyAuxiliary request metadata reference.
ts
constructor(request: ActionRequest<TPayload>)Copies request fields and starts with no denial, output, mutations, or notifications.
ts
deny(reason: string): voidMarks validation denied and records the explanation returned to the caller.
ts
get isDenied(): booleanWhether any validation callback has denied execution.
ts
get denialReason(): stringLatest explanation supplied to deny.
ts
produce(data: any): voidReplaces the successful result payload.
ts
get resultData(): anyLatest produced payload, or null when none was produced.
ts
stageMutation(id: string, apply: Function, rollback: Function | null = null): ActionMutationCreates and appends an unapplied mutation for commit-order execution.
ts
addMutation(mutation: ActionMutation): voidAppends a prebuilt mutation to the commit sequence.
ts
get stagedMutations(): ActionMutation[]Ordered mutation list consumed by Action after the commit callback.
ts
emitOnCommit(scope: EventScope, key: EventKey<any>, event: any): voidQueues an event fact for best-effort emission only after all mutations commit.
ts
get stagedNotifications(): ActionNotificationEntry[]Ordered post-commit notification list consumed by Action.
ActionMutation
ts
import { ActionMutation } from "gamekit";
class ActionMutationNamed reversible unit of commit work with explicit applied state.
Members
ts
id: stringStable identifier for this ActionMutation.
ts
apply: FunctionCallback invoked once during forward commit.
ts
rollback: Function | nullOptional compensation callback invoked in reverse order.
ts
applied: boolean = falseWhether forward work remains eligible for rollback.
ts
constructor(id: string, apply: Function, rollback: Function | null = null)Captures a non-empty diagnostic id and forward/optional compensation callbacks.
ActionRequest
ts
import { ActionRequest } from "gamekit";
class ActionRequest<TPayload>Immutable-by-convention invocation data for a named Action.
Members
ts
actionId: stringNon-empty action identity expected by dispatching game code.
ts
actor: anyGame object initiating the action, or null.
ts
target: anyGame object receiving the action, or null.
ts
payload: TPayloadTyped action-specific input.
ts
metadata: anyOptional auxiliary data not interpreted by GameKit.
ts
constructor(actionId: string, actor: any = null, target: any = null, payload: TPayload = null, metadata: any = null)Captures a non-empty action id and game-owned invocation values.
ActionResult
ts
import { ActionResult } from "gamekit";
class ActionResult<TData>Terminal action status with output, diagnostics, and mutation history available for compensation.
Members
ts
status: ActionStatusCommitted, denied-before-commit, or failed-during-validation/commit.
ts
request: ActionRequest<any>Original request associated with the execution.
ts
data: TData | nullProduced success payload, or null for denial/failure or no output.
ts
reason: string | nullHuman-readable denial or failure explanation, when applicable.
ts
error: Error | nullCaught validation or commit exception, never notification errors.
ts
appliedMutations: ActionMutation[]Forward mutations attempted before terminal completion.
ts
constructor( status: ActionStatus, request: ActionRequest<any>, data: TData | null = null, reason: string | null = null, error: Error | null = null, appliedMutations: ActionMutation[] = [] )Captures terminal execution state without copying request or mutation references.
ts
get ok(): booleantrue only for a fully committed action.
ts
get isCommitted(): booleanWhether validation and every mutation completed successfully.
ts
get isDenied(): booleanWhether validation rejected execution before commit.
ts
get isFailed(): booleanWhether a validator or commit callback threw.
ts
rollback(): voidBest-effort compensates still-applied mutations in reverse order; compensation errors are isolated.
ActionSequence
ts
import { ActionSequence } from "gamekit";
class ActionSequenceExecutes action/request pairs in order and can compensate earlier commits after a later failure.
Members
ts
constructor(rollbackOnFailure: boolean = true)Configures whether a denied or failed step rolls back earlier committed steps.
ts
add(action: Action<any, any>, request: ActionRequest<any>): ActionSequenceAppends an action and its request and returns this sequence for chaining.
ts
execute(targetScope: EventScope | null = null): ActionSequenceResultStops on the first non-commit and optionally rolls back prior results in reverse order.
ActionSequenceResult
ts
import { ActionSequenceResult } from "gamekit";
class ActionSequenceResultTerminal status and per-step results from an ActionSequence execution.
Members
ts
status: ActionStatusOverall status, inherited from the first unsuccessful step when present.
ts
executedCount: intNumber of steps attempted, including the unsuccessful step.
ts
results: ActionResult<any>[]Ordered results for every attempted step.
ts
rolledBack: booleanWhether compensation of prior committed steps was requested.
ts
failureReason: string | nullFirst denial or failure explanation, or null on complete commit.
ts
constructor( status: ActionStatus, executedCount: int, results: ActionResult<any>[], rolledBack: boolean, failureReason: string | null = null )Captures sequence outcome and ordered step history.
ts
get ok(): booleantrue only when every step committed.
ActionSequenceStep
ts
import { ActionSequenceStep } from "gamekit";
class ActionSequenceStepBinds one Action to the request used when its sequence reaches that step.
Members
ts
action: Action<any, any>Executable action reference.
ts
request: ActionRequest<any>Invocation passed to the action.
ts
constructor(action: Action<any, any>, request: ActionRequest<any>)Captures the action/request pair without executing it.
ActionStatus
ts
import { ActionStatus } from "gamekit";
enum ActionStatusDefines the closed action status value set. Store and compare these values directly rather than introducing string aliases;
| Member | Meaning |
|---|---|
COMMITTED = "committed" | The requested mutations completed. |
DENIED = "denied" | Validation or a rule denied the request. |
FAILED = "failed" | Execution started but did not complete successfully. |
AssetCancellationToken
ts
import { AssetCancellationToken } from "gamekit";
class AssetCancellationTokenCooperative cancellation flag observed between entries of an AssetLoadPlan.
Members
ts
isCancelled: boolean = falseWhether cancellation has been requested.
ts
reason: string = ""Latest game-supplied cancellation explanation.
ts
cancel(reason: string = "cancelled"): voidPermanently marks the token cancelled and records the reason.
AssetFailure
ts
import { AssetFailure } from "gamekit";
class AssetFailureCaptures one failed or dependency-blocked asset-plan entry.
Members
ts
key: AssetKey<any>Asset whose load did not complete.
ts
message: stringFinal human-readable failure explanation.
ts
error: anyLast thrown loader value, or null for dependency blocking.
ts
attempts: intLoader invocations made; zero means a dependency blocked loading.
ts
trace: string[]Per-attempt diagnostic lines in execution order.
ts
constructor(key: AssetKey<any>, message: string, error: any = null, attempts: int = 1, trace: string[] = [])Captures the terminal failure details for plan inspection.
AssetHandle
ts
import { AssetHandle } from "gamekit";
class AssetHandle<T>Retains one loaded asset until its owner releases the handle.
Members
ts
key: AssetKey<T>Key of the asset retained by this handle.
ts
isReleased: boolean = falseWhether this handle has already dropped its manager reference.
ts
constructor(key: AssetKey<T>, manager: IAssetHandleManager<T>, scope: IAssetHandleScope | null = null)Creates a handle managed by AssetManager; consumers normally receive one from load or acquire.
ts
get scope(): IAssetHandleScope | nullScope that will release this handle, or null for an independently managed handle.
ts
get(): TReads the retained asset value while the handle remains live.
- Throws: StaleHandle When this handle has been released.
ts
release(): voidReleases this handle's reference and detaches it from its scope. Repeated calls do nothing; the asset unloads when this is its final handle.
AssetKey
ts
import { AssetKey } from "gamekit";
class AssetKey<T> extends TypedKey<T>Identifies one typed asset independently of its diagnostic label.
Members
ts
constructor(label: string)Allocates a fresh asset identity with the label shown in diagnostics.
AssetLoadPlan
ts
import { AssetLoadPlan } from "gamekit";
class AssetLoadPlanMutable dependency graph of asset keys with per-entry loader, weight, and retry policy.
Members
ts
entries: Array<AssetPlanEntry> = []Registration-ordered entries; adding an existing key replaces it in place.
ts
add<T>( key: AssetKey<T>, dependencies: Array<AssetKey<any>> = [], options: any = null ): AssetLoadPlanAdds or replaces an entry, normalizing weight and retry values in AssetPlanEntry.
ts
has(key: AssetKey<any>): booleanTests membership by exact AssetKey identity.
ts
getEntry(key: AssetKey<any>): AssetPlanEntry | nullReturns the entry for exact key identity, or null when absent.
ts
validate(): voidResolves dependency waves to detect cycles before any loader work begins.
ts
getTopologicalWaves(): Array<Array<AssetPlanEntry>>Groups entries into dependency-ready waves while preserving registration order within each wave. Dependencies outside the plan are assumed already satisfied.
AssetLoadProgress
ts
import { AssetLoadProgress } from "gamekit";
class AssetLoadProgressMutable progress snapshot passed to an AssetManager plan callback after each outcome.
Members
ts
loadedCount: int = 0Entries that acquired a handle successfully.
ts
totalCount: int = 0Total entries declared by the plan.
ts
loadedWeight: int = 0Sum of successful entry weights.
ts
totalWeight: int = 0Sum of all normalized entry weights.
ts
ratio: float = 0.0Successful weight divided by total weight, from zero through one.
ts
lastKey: AssetKey<any> | null = nullMost recently loaded key, or null before the first success.
ts
failedCount: int = 0Entries failed or blocked by failed dependencies.
AssetManager
ts
import { AssetManager } from "gamekit";
class AssetManager implements IAssetHandleManager<any>, IAssetScopeManagerSelects loaders, coalesces in-flight work, caches values, and unloads them after the final handle releases. Create one manager for the asset domain that owns its loaders, then shut it down only after every scope has stopped requesting assets.
Members
ts
isShutdown: boolean = falseWhether this manager has stopped accepting new work.
ts
constructor(defaultLoader: any = null)Starts an empty asset domain with an optional fallback loader.
ts
registerLoader<T>(key: AssetKey<T>, loader: any): voidAssociates a loader with exact key identity, replacing any earlier association.
ts
setDefaultLoader(loader: any): voidReplaces the fallback selected when a key has no loader override.
ts
createScope(name: string = ""): AssetScopeCreates a scope that can release every handle it acquires together.
- Throws: GameKitError When the manager has been shut down.
ts
unregisterScope(scope: IAssetHandleScope): voidStops retaining a disposed scope; removing an unknown scope is harmless.
ts
isLoaded(key: AssetKey<any>): booleanTests whether a key has a completed cached record.
ts
getRefCount(key: AssetKey<any>): intReturns live handles retaining the key, or zero when unloaded.
ts
getAssetValue<T>(key: AssetKey<T>): TReturns a loaded asset without acquiring another handle.
- Throws: MissingRegistration When the key has no loaded record.
ts
acquireHandle<T>(key: AssetKey<T>, scope: IAssetHandleScope | null = null): AssetHandle<T>Acquires a retaining handle for an already loaded asset. The returned handle increments the reference count and is released directly or by its scope.
- Throws: GameKitError When the manager is shut down.
- Throws: MissingRegistration When the asset is not loaded.
ts
releaseHandle(key: AssetKey<any>, handle: any): voidDrops one known handle reference and unloads the record when its count reaches zero.
ts
replaceAsset<T>(key: AssetKey<T>, newAsset: T): voidSwaps a loaded value without invalidating handles, then best-effort unloads the old value.
ts
async acquireOrLoad<T>(key: AssetKey<T>, scope: IAssetHandleScope | null = null, customLoader: any = null): Promise<AssetHandle<T>>Returns a retaining handle, loading the key when no cached record exists. Concurrent requests for the same key await one shared load and each receive its own handle.
- Throws: GameKitError When the manager is shut down.
- Throws: MissingRegistration When no loader can be selected.
ts
async load<T>(key: AssetKey<T>, options: any = null): Promise<AssetHandle<T>>Acquires or loads one key using optional {scope, loader} overrides.
ts
async loadPlan(plan: AssetLoadPlan, options: any = null): Promise<AssetPlanResult>Loads a validated dependency plan wave by wave and records all outcomes. A failed dependency blocks dependants; continueOnError controls later independent work.
ts
shutdown(): voidStops new asset work, disposes active scopes, and unloads every cached record. In-flight promises are forgotten; do not use the manager after shutdown.
AssetPlanEntry
ts
import { AssetPlanEntry } from "gamekit";
class AssetPlanEntryOne asset-plan node with dependency identities and load policy.
Members
ts
key: AssetKey<any>Asset identity loaded by this node.
ts
dependencies: Array<AssetKey<any>>Keys that must succeed first when also present in the plan.
ts
loader: anyOptional loader override; null uses key-specific or manager default selection.
ts
weight: intRelative contribution to aggregate progress.
ts
retries: intAdditional attempts after the initial load, clamped to zero or greater.
ts
constructor( key: AssetKey<any>, dependencies: Array<AssetKey<any>> = [], loader: any = null, weight: int = 1, retries: int = 0 )Captures policy, coercing non-positive weight to one and negative retries to zero.
AssetPlanResult
ts
import { AssetPlanResult } from "gamekit";
class AssetPlanResultAggregate handles, failures, counts, and cancellation state from one plan run.
Members
ts
isOk: boolean = trueRemains true only when no entry failed and cancellation did not occur.
ts
isCancelled: boolean = falseWhether cooperative cancellation stopped traversal between entries.
ts
loadedCount: int = 0Number of handles acquired successfully.
ts
failedCount: int = 0Number of loader failures plus dependency-blocked entries.
ts
handles: Array<AssetHandle<any>> = []Successful handles in plan execution order.
ts
failures: Array<AssetFailure> = []Terminal failures in plan execution order.
ts
hasHandle(key: AssetKey<any>): booleanTests successful handle presence by exact key identity.
ts
getHandle<T>(key: AssetKey<T>): AssetHandle<T> | nullReturns the successful handle for a key, or null.
ts
getFailure(key: AssetKey<any>): AssetFailure | nullReturns the terminal failure for a key, or null.
ts
getFailureTrace(key: AssetKey<any>): string | nullJoins per-attempt trace lines, or returns null when the key did not fail.
AssetScope
ts
import { AssetScope } from "gamekit";
class AssetScope implements IAssetHandleScopeGroups asset handles so a scene, screen, or other owner can release them together.
Members
ts
name: stringOptional label used in diagnostics.
ts
isDisposed: boolean = falseWhether this resource has released its owned references.
ts
constructor(manager: IAssetScopeManager, name: string = "")Creates a scope registered with an asset manager.
ts
async load<T>(key: AssetKey<T>): Promise<AssetHandle<T>>Loads an asset and attaches the resulting handle to this scope. If disposal wins the asynchronous race, the returned handle is already released.
ts
acquire<T>(key: AssetKey<T>): AssetHandle<T>Acquires an already loaded asset and records the handle in this scope.
- Throws: GameKitError When the scope has been disposed.
ts
has(key: AssetKey<any>): booleanReports whether this live scope retains a handle for the key.
ts
get<T>(key: AssetKey<T>): T | nullFinds the retained value for a key without changing its reference count.
ts
getRequired<T>(key: AssetKey<T>): TFinds a retained value and treats absence as a configuration error.
- Throws: MissingRegistration When the scope has no live handle for the key.
ts
getHandle<T>(key: AssetKey<T>): AssetHandle<T> | nullFinds this scope's live handle for a key.
ts
release(key: AssetKey<any>): voidDisposes this scope and releases a snapshot of all of its handles. It unregisters itself after release; repeated calls are harmless.
ts
releaseAll(): voidAlias for releaseAll for owners that use disposable lifecycle terminology.
ts
dispose(): voidDisposable-lifecycle alias for releaseAll.
Attribute
ts
import { Attribute } from "gamekit";
class Attribute<T>Lazily computes a value from a base or dependency set, then applies ordered modifiers and a final clamp. Changes notify a listener snapshot only after a successful recalculation.
Members
ts
constructor(baseValue: T, clamp: Function | null = null)Starts dirty with a base value and optional final-value clamp.
ts
get value(): TRecalculates when dirty and returns the cached effective value.
ts
get baseValue(): TUnmodified source value; derived attributes retain it but do not read it.
ts
get dirty(): booleanWhether the effective value requires recalculation.
ts
get recalculations(): intNumber of successful effective-value calculations.
ts
setBase(value: T): voidReplaces a non-derived base, recalculates immediately, and notifies on change.
ts
addModifier(modifier: AttributeModifier<T>): voidAdds a unique modifier, ordered by priority then insertion order, and recalculates.
ts
removeModifier(id: string): booleanRemoves a modifier by id and reports whether recalculation occurred.
ts
derive(dependencies: Attribute<any>[], calculate: Function): voidReplaces base calculation with a dependency snapshot callback and subscribes to dependency changes. Direct and transitive cycles are rejected before existing derivation state changes.
ts
clearDerived(): voidDrops dependency subscriptions and resumes calculation from the retained base value.
ts
subscribe(listener: Function): AttributeSubscription<T>Appends a (next, previous) observer and returns its idempotent lifetime handle.
ts
inspect(): AttributeInspection<T>Forces refresh and captures counts plus current base/effective values.
ts
removeSubscription(subscription: AttributeSubscription<T>): voidDeactivates an observer handle and removes it from future snapshots.
AttributeInspection
ts
import { AttributeInspection } from "gamekit";
class AttributeInspection<T>Point-in-time diagnostic snapshot of an Attribute after refresh.
Members
ts
baseValue: TRetained source value, even when derivation currently replaces it.
ts
value: TEffective derived, modified, and clamped value.
ts
modifierCount: intNumber of transformations currently attached.
ts
dependencyCount: intNumber of attributes feeding a derived calculation.
ts
listenerCount: intNumber of active change observers.
ts
recalculations: intSuccessful calculations since construction.
ts
dirty: booleanWhether another read would need recalculation at capture time.
ts
constructor(baseValue: T, value: T, modifierCount: int, dependencyCount: int, listenerCount: int, recalculations: int, dirty: boolean)Captures values and counters without retaining a reference to the Attribute.
AttributeModifier
ts
import { AttributeModifier } from "gamekit";
class AttributeModifier<T>Named pure transformation applied to an Attribute at an explicit priority.
Members
ts
id: stringStable identifier for this AttributeModifier.
ts
order: intAscending priority; equal priorities retain insertion order.
ts
apply: FunctionCallback receiving the preceding effective value and returning the next value.
ts
constructor(id: string, order: int, apply: Function)Captures a non-empty unique id, priority, and transformation callback.
AttributeSubscription
ts
import { AttributeSubscription } from "gamekit";
class AttributeSubscription<T>Idempotent lifetime handle for one Attribute change observer.
Members
ts
active: boolean = trueWhether this AttributeSubscription still accepts work.
ts
constructor(owner: Attribute<T>, entry: AttributeListenerEntry<T>)Binds the handle to its owner and private listener entry.
ts
dispose(): voidRemoves the listener from future notifications; repeated calls do nothing.
ts
matches(entry: AttributeListenerEntry<T>): booleanTests private listener-entry identity during owner cleanup.
ts
deactivate(): voidMarks the handle inactive and drops its owner reference without re-entry.
cloneValue
ts
import { cloneValue } from "gamekit";
function cloneValue(val: any): anyDeep-copies arrays, maps, and object properties while preserving primitive values.
ComponentKey
ts
import { ComponentKey } from "gamekit";
class ComponentKey<T> extends TypedKey<T>Identifies one component capability or ECS store independently of its label.
Members
ts
constructor(label: string)Allocates a fresh component identity with the label shown in diagnostics.
Condition
ts
import { Condition } from "gamekit";
class Condition<TContext>Normalizes boolean, string, or ConditionResult evaluators into composable diagnostic outcomes.
Members
ts
id: stringStable identifier for this Condition.
ts
description: stringHuman-readable explanation of this item.
ts
constructor(id: string, description: string, evaluator: Function)Binds a non-empty diagnostic id and description to a context evaluator.
ts
evaluate(context: TContext): ConditionResultConverts true or empty string to pass, false or non-empty string to failure, and preserves explicit results.
ts
and(other: Condition<TContext>, shortCircuit: boolean = true): Condition<TContext>Builds a two-condition conjunction using a derived composite id.
ts
or(other: Condition<TContext>, shortCircuit: boolean = true): Condition<TContext>Builds a two-condition disjunction using a derived composite id.
ts
not(failureReason: string = ""): Condition<TContext>Builds an inverse condition with an optional reason for an unexpected pass.
ts
static all<T>(conditions: Condition<T>[], shortCircuit: boolean = true, id: string = "all"): Condition<T>Builds a conjunction that either stops at the first failure or aggregates failure reasons.
ts
static any<T>(conditions: Condition<T>[], shortCircuit: boolean = true, id: string = "any"): Condition<T>Builds a disjunction that can stop at the first pass and reports every failure when none pass.
ts
static not<T>(condition: Condition<T>, failureReason: string = "", id: string = "not"): Condition<T>Builds a condition that passes only when the wrapped condition fails.
ConditionResult
ts
import { ConditionResult } from "gamekit";
class ConditionResultNormalized condition outcome with a primary explanation and optional aggregate reasons.
Members
ts
passed: booleantrue when evaluation permits the guarded operation.
ts
conditionId: stringIdentity of the decisive condition or composite.
ts
reason: stringPrimary human-readable outcome explanation.
ts
reasons: string[]Aggregate failure explanations; defaults to the primary reason when non-empty.
ts
constructor(passed: boolean, conditionId: string = "", reason: string = "", reasons: string[] = [])Captures an outcome and normalizes its reason list.
ts
get ok(): booleanAlias for passed used by result-oriented call sites.
ts
static pass(conditionId: string = "", reason: string = ""): ConditionResultCreates a successful outcome with optional identity and explanation.
ts
static fail(conditionId: string, reason: string, reasons: string[] = []): ConditionResultCreates a failed outcome, defaulting the aggregate list to the primary reason.
ContextKey
ts
import { ContextKey } from "gamekit";
class ContextKey<T> extends TypedKey<T>Identifies a typed hierarchical context value without relying on string lookup.
Members
ts
constructor(label: string)Allocates a fresh context identity with the label shown in diagnostics.
CyclicDefinition
ts
import { CyclicDefinition } from "gamekit";
class CyclicDefinition extends DefinitionErrorReports an inheritance cycle discovered while resolving definitions.
Members
ts
cycle: string[]Ordered ids that form the detected cycle.
ts
constructor(message: string, cycle: string[] = [])Uses the first cycle id as the inherited definition id when available.
CyclicDependency
ts
import { CyclicDependency } from "gamekit";
class CyclicDependency extends GameKitErrorReports a directed dependency cycle, such as an asset load-plan loop.
Members
ts
cycle: string[]Ordered labels participating in the detected loop.
ts
constructor(message: string, cycle: string[] = [])Retains the cycle alongside the human-readable message.
Definition
ts
import { Definition } from "gamekit";
class DefinitionImmutable source definition with copied data and ordered parent ids.
Members
ts
readonly id: stringStable identifier for this Definition.
ts
readonly inherits: string[]Parent ids merged left to right before this definition's data.
ts
readonly data: anyDeep copy of the registered source data.
ts
constructor(id: string, data: any, inherits: string[] = [])Validates non-empty ids and copies data plus the inheritance list.
DefinitionError
ts
import { DefinitionError } from "gamekit";
class DefinitionError extends GameKitErrorAdds definition identity and provenance to a registry resolution failure.
Members
ts
definitionId: stringDefinition id being resolved, or an empty string when no single id applies.
ts
provenance: string[]Resolution path from the requested definition to the failure point.
ts
constructor(message: string, definitionId: string = "", provenance: string[] = [])Captures a diagnostic message with optional definition and resolution path context.
DefinitionRegistry
ts
import { DefinitionRegistry } from "gamekit";
class DefinitionRegistryResolves named definitions through ordered multiple inheritance and validator callbacks. Every public resolution returns detached data and reports cycles or missing parents with provenance.
Members
ts
define(id: string, data: any, inherits: string[] = []): DefinitionConstructs and registers a copied source definition.
ts
register(def: Definition): DefinitionRegisters one unique Definition by id and returns the same source object.
ts
has(id: string): booleanTests exact string-id registration without resolving parents.
ts
addValidator(validator: Function): voidAppends a validator run against each fully merged candidate.
ts
resolve(id: string): ResolvedDefinitionResolves parents left to right, overlays child data, validates, and returns detached data.
ts
get(id: string): ResolvedDefinition | nullReturns a resolved snapshot, or null only when the requested root id is absent.
ts
getRequired(id: string): ResolvedDefinitionReturns a resolved snapshot and throws MissingRegistration when the root id is absent.
ts
instantiate(id: string, factory: Function, context: any = null): anyResolves fresh data and invokes factory(resolvedDefinition, context).
ts
createPrefab(id: string, factory: Function): PrefabCreates a reusable factory binding after verifying that the root id exists.
DuplicateRegistration
ts
import { DuplicateRegistration } from "gamekit";
class DuplicateRegistration extends GameKitErrorReports a second registration for an identity that must be unique.
Members
ts
definitionId: stringConflicting definition or registration id, when one is available.
ts
provenance: string[]Resolution or registration path that exposed the conflict.
ts
constructor(message: string, definitionId: string = "", provenance: string[] = [])Captures optional identity and provenance context for diagnostics.
EffectApplication
ts
import { EffectApplication } from "gamekit";
class EffectApplication<T>Incoming typed effect payload and policy options passed through the application pipeline.
Members
ts
key: EffectKey<T>Effect identity used for collision and lookup.
ts
payload: TGame-owned behavior or data being attached.
ts
options: EffectOptions<T>Source, duration, scheduler, and stacking policy for this attempt.
ts
constructor(key: EffectKey<T>, payload: T, options: EffectOptions<T>)Captures one pre-attachment request for pipeline inspection.
EffectCollection
ts
import { EffectCollection } from "gamekit";
class EffectCollectionOwns effect handles, applies admission and stacking policy, and mirrors owner lifecycle callbacks. Handles remain insertion ordered and terminal removal cleans timers plus source observation exactly once.
Members
ts
owner: IEffectOwnerEntity or game object passed to effect lifecycle callbacks.
ts
pipeline: MutablePipeline<EffectApplication<any>, any> = ...Pre-admission pipeline that may cancel an application before collision policy.
ts
constructor(owner: IEffectOwner)Starts an empty collection bound to one lifecycle owner.
ts
add<T>(key: EffectKey<T>, value: T, options: EffectOptions<T> | null = null): EffectHandle<T> | nullRuns admission, resolves same-key collisions, and enters the accepted effect into current owner lifecycle. Returns null for pipeline cancellation or policy rejection.
ts
get<T>(key: EffectKey<T>): EffectHandle<T>[]Returns a new insertion-ordered array of live handles matching exact key identity.
ts
lifecycleEntries(): EffectHandle<any>[]Returns a detached snapshot used to interleave effects with other owner capabilities.
ts
contains(effect: EffectHandle<any>): booleanTests exact handle identity, not key equivalence.
ts
activate(effect: EffectHandle<any>): voidActivates a currently retained handle; foreign or terminal handles are ignored.
ts
suspend(effect: EffectHandle<any>): voidSuspends a currently retained active handle; foreign handles are ignored.
ts
remove(effect: EffectHandle<any>, reason: EffectRemovalReason = EffectRemovalReason.REMOVED): voidTerminally removes a retained handle and emits lifecycle callbacks for the stated reason.
ts
expire(effect: EffectHandle<any>): voidApplies the special expiration boundary without a preceding suspend callback.
ts
refresh(effect: EffectHandle<any>, duration: float | null): voidReplaces a retained effect's non-negative duration and restarts its scheduler timer.
ts
removeAll(reason: EffectRemovalReason): voidRemoves a reverse-order snapshot so teardown mirrors capability unwinding.
EffectHandle
ts
import { EffectHandle } from "gamekit";
class EffectHandle<T>Stable handle controlling one effect's lifecycle, timer, and source cleanup.
Members
ts
id: intStable identifier for this EffectHandle.
ts
key: EffectKey<T>Typed effect identity shared by colliding applications.
ts
value: TAttached game-owned effect behavior or data.
ts
source: any | nullOptional lifetime owner whose disposal removes this effect.
ts
duration: float | nullCurrent expiration delay, or null for no timer.
ts
state: EffectState = EffectState.SUSPENDEDSuspended, active, removed, or expired lifecycle state.
ts
order: intMonotonic capability order shared with the owning Entity.
ts
attached: boolean = falseWhether onAttach has run at least once.
ts
constructor(collection: any, id: int, order: int, key: EffectKey<T>, value: T, options: EffectOptions<T>)Captures collection ownership and options; attachment occurs separately.
ts
get active(): booleanWhether the effect currently participates in active owner behavior.
ts
get removed(): booleanWhether the effect reached either terminal removed or expired state.
ts
suspend(): voidRequests idempotent suspension through the owning collection.
ts
activate(): voidRequests attachment if needed, then idempotent activation through the collection.
ts
remove(): voidRequests terminal manual removal through the owning collection.
ts
refresh(duration: float | null = this.duration): voidRestarts timed expiration, defaulting to the current duration.
EffectKey
ts
import { EffectKey } from "gamekit";
class EffectKey<T> extends TypedKey<T>Identifies an effect kind and its typed payload across an entity's collection.
Members
ts
constructor(label: string)Allocates a fresh effect identity with the label shown in diagnostics.
EffectOptions
ts
import { EffectOptions } from "gamekit";
class EffectOptions<T>Optional collision, source-lifetime, and timed-expiration policy for an effect.
Members
ts
policy: Function | nullStacking callback required when the key already has live effects.
ts
source: any | nullOptional object whose disposal removes this effect.
ts
duration: float | nullNon-negative lifetime in seconds of the scheduler's time, or null for no timer.
ts
scheduler: any | nullExplicit core Ticker (App.ticker, node.ticker) required whenever duration is present; headless tests may pass a ClockScheduler.
ts
constructor(policy: Function | null = null, source: any | null = null, duration: float | null = null, scheduler: any | null = null)Validates that timed effects have a non-negative duration and scheduler.
EffectRemovalReason
ts
import { EffectRemovalReason } from "gamekit";
enum EffectRemovalReasonDefines the closed effect removal reason value set. Store and compare these values directly rather than introducing string aliases;
| Member | Meaning |
|---|---|
REMOVED = "removed" | The owner explicitly removed the effect. |
REPLACED = "replaced" | A replacement displaced the effect. |
REJECTED = "rejected" | Stacking rules rejected the effect. |
EXPIRED = "expired" | The effect reached its expiration condition. |
SOURCE_DISPOSED = "source-disposed" | The effect's source owner was disposed. |
TARGET_DISPOSED = "target-disposed" | The effect's target owner was disposed. |
EffectStacking
ts
import { EffectStacking } from "gamekit";
class EffectStackingFactory for common collision policies consumed by EffectCollection.
Members
ts
static accumulate(): FunctionAccepts every incoming effect alongside existing matches.
ts
static replace(): FunctionRemoves all existing matches before accepting the incoming effect.
ts
static strongest(compare: Function): FunctionRejects incoming payloads not strictly stronger than every existing value; otherwise replaces them.
ts
static refreshDuration(): FunctionKeeps the most recently added match and restarts its timer using incoming duration.
EffectStackingContext
ts
import { EffectStackingContext } from "gamekit";
class EffectStackingContext<T>Collision-policy view of the incoming application and matching handles in insertion order.
Members
ts
incoming: EffectApplication<T>Application currently seeking admission.
ts
existing: EffectHandle<T>[]Live handles with the same key, oldest first.
ts
constructor(incoming: EffectApplication<T>, existing: EffectHandle<T>[])Captures the collision inputs for one synchronous policy decision.
ts
accept(): EffectStackingResolution<T>Chooses to retain matches and add the incoming effect.
ts
reject(): EffectStackingResolution<T>Chooses to reject incoming payload with a removal callback.
ts
replace(): EffectStackingResolution<T>Chooses to remove every match and add the incoming effect.
ts
refresh(effect: EffectHandle<T>): EffectStackingResolution<T>Chooses one existing handle to retain and retime instead of adding.
EffectStackingResolution
ts
import { EffectStackingResolution } from "gamekit";
class EffectStackingResolution<T>Policy decision naming accept, reject, replace, or refresh plus an optional retained handle.
Members
ts
action: stringDecision string interpreted and validated by EffectCollection.
ts
retained: EffectHandle<T> | nullExisting handle required only for refresh.
ts
constructor(action: string, retained: EffectHandle<T> | null = null)Captures a policy decision; collection application validates action semantics.
EffectState
ts
import { EffectState } from "gamekit";
enum EffectStateDefines the closed effect state value set. Store and compare these values directly rather than introducing string aliases;
| Member | Meaning |
|---|---|
ACTIVE = "active" | The effect currently applies. |
SUSPENDED = "suspended" | The effect is retained but not currently applied. |
EXPIRED = "expired" | The effect ended because its duration elapsed. |
REMOVED = "removed" | The effect is no longer retained by its collection. |
Entity
ts
import { Entity } from "gamekit";
class Entity implements IEffectOwnerOwns a game object's hierarchy, local facts, components, and effects. An Entity is detached until attached to an active root; its identity and owned state survive reparenting but not dispose.
Members
ts
parent: Entity | null = nullCurrent hierarchy owner, or null for a root or detached entity.
ts
state: EntityState = EntityState.DETACHEDDetached, attached, active, or terminal disposed lifecycle state.
ts
events: EventScopeLocal non-bubbling event scope closed before disposal callbacks.
ts
effects: EffectCollectionEffect collection whose lifecycle follows this entity.
ts
constructor(eventErrorSink: Function | null = null)Creates a detached entity with local events and effects; the optional sink observes listener errors.
ts
onAttach(): voidOverride hook called parent-before-child when entering a hierarchy.
ts
onActivate(): voidOverride hook called parent-before-child when entering active state.
ts
onDeactivate(): voidOverride hook called child-before-parent when leaving active state.
ts
onDetach(): voidOverride hook called child-before-parent before hierarchy unlinking.
ts
onDispose(): voidTerminal override hook called child-before-parent during recursive disposal.
ts
onContextChanged(key: ContextKey<any>): voidOverride invalidation hook delivered parent-before-child for a changed context key.
ts
children(): Entity[]Returns a detached snapshot of non-disposed direct children in attachment order.
ts
ancestors(): Entity[]Returns live ancestors nearest-first up to the hierarchy root.
ts
descendants(): Entity[]Returns live descendants in parent-before-child preorder.
ts
addComponent<T>(key: ComponentKey<T>, value: T): voidAttaches one game-defined capability under its explicit identity key. The component becomes visible immediately and receives the Entity's current lifecycle; mutation from a component callback throws.
- Throws: Error when the key is already present or lifecycle mutation is re-entrant.
ts
replaceComponent<T>(key: ComponentKey<T>, value: T): T | nullRemoves the prior keyed component through lifecycle callbacks, then attaches its replacement. Returns the former value, or null when the key was absent.
ts
removeComponent<T>(key: ComponentKey<T>): T | nullDeactivates and detaches a keyed component before returning its value, or null when absent.
ts
getComponent<T>(key: ComponentKey<T>): T | nullLooks up a component without turning absence into a programming error. This reads only this Entity's explicit component table and returns null after disposal.
ts
getAncestorComponent<T>(key: ComponentKey<T>): T | nullFinds the nearest ancestor value for a key, deliberately excluding local membership.
ts
getDescendantComponents<T>(key: ComponentKey<T>): T[]Collects matching descendant values in hierarchy preorder, excluding this entity.
ts
inspectComponents(): any[]Captures key labels, attachment order, and game-owned value references for tooling.
ts
addEffect<T>(key: EffectKey<T>, value: T, options: EffectOptions<T> | null = null): EffectHandle<T> | nullApplies an effect through admission/stacking and current entity lifecycle.
ts
getEffects<T>(key: EffectKey<T>): EffectHandle<T>[]Returns a detached insertion-ordered array of live handles matching exact key identity.
ts
attach(parent: Entity): voidLinks a detached subtree under a live parent and activates it when that parent is active.
ts
activate(): voidActivates a root or child of an active parent in parent-before-child order.
ts
deactivate(): voidDeactivates an active root subtree in child-before-parent order.
ts
detach(): voidDeactivates and detaches the subtree child-before-parent while preserving all owned state.
ts
reparent(newParent: Entity): voidTransfers synchronously through detach and attach, then activates under an active new parent.
ts
dispose(): voidIdempotently closes events and disposes descendants, capabilities, and this entity child-first.
ts
disposeDeferred(queue: any): voidEnqueues terminal disposal while leaving the entity live until queue flush.
ts
setContext<T>(key: ContextKey<T>, value: T): voidAdds or replaces a local context value, then invalidates this subtree parent-first.
ts
removeContext<T>(key: ContextKey<T>): booleanRemoves a local context value and invalidates descendants only when membership changed.
ts
getContext<T>(key: ContextKey<T>): T | nullResolves the nearest local-or-ancestor context value, or null at an absent boundary.
EntityAllocator
ts
import { EntityAllocator } from "gamekit";
class EntityAllocatorIssues compact generational entity ids and recycles released slots without reviving stale handles.
Members
ts
create(): EntityIdAllocates a live id, preferring the most recently released reusable slot.
ts
seedGeneration(index: int, generation: int): voidSets a slot generation for boundary tests and persisted-id hardening; inactive seeded slots become reusable.
ts
isAlive(id: EntityId): booleanReturns true only when the index exists, is live, and has the exact generation.
ts
resolve(id: EntityId): EntityId | nullReturns the supplied id when live, or null for unknown and stale identities.
ts
requireAlive(id: EntityId): voidEnforces liveness at mutation boundaries.
ts
destroy(id: EntityId): booleanInvalidates a live id and increments its generation before recycling the slot. A slot at EntityId.MAX_GENERATION is retired permanently.
EntityId
ts
import { EntityId } from "gamekit";
class EntityIdNames one lifetime of an allocator slot using an index-and-generation pair.
Members
ts
static const MAX_GENERATION: int = 2147483647Highest generation value before allocator slots retire instead of wrapping.
ts
index: intReusable allocator slot index; it is not unique without generation.
ts
generation: intSlot generation that prevents a stale id from resolving after reuse.
ts
constructor(index: int, generation: int)Captures an allocator-issued slot and generation without validating liveness.
ts
equals(other: EntityId): booleanRequires both slot and generation to match.
ts
toString(): stringFormats the identity as entity index:generation for diagnostics.
EntityState
ts
import { EntityState } from "gamekit";
enum EntityStateDefines the closed entity state value set. Store and compare these values directly rather than introducing string aliases;
| Member | Meaning |
|---|---|
DETACHED = "Detached" | The entity has no parent owner. |
ATTACHED = "Attached" | The entity belongs to a parent but is inactive. |
ACTIVE = "Active" | The entity is attached and receiving active lifecycle work. |
DISPOSED = "Disposed" | The entity has completed teardown. |
EntityTeardownQueue
ts
import { EntityTeardownQueue } from "gamekit";
class EntityTeardownQueueDeduplicates deferred Entity disposal until an explicit FIFO flush boundary.
Members
ts
defer(entity: Entity): voidEnqueues a live entity once by object identity; disposed entities are ignored.
ts
flush(): voidDisposes the current snapshot in issue order; callback additions wait for the next flush.
EventKey
ts
import { EventKey } from "gamekit";
class EventKey<T> extends TypedKey<T>Identifies an event channel and statically carries the emitted payload type.
Members
ts
constructor(label: string)Allocates a fresh event identity with the label shown in diagnostics.
EventScope
ts
import { EventScope } from "gamekit";
class EventScopeOwns typed local event listeners and delivers snapshot notifications in subscription order. Listener failures are isolated and optionally reported without aborting later listeners.
Members
ts
constructor(errorSink: Function | null = null)Starts an open local scope with an optional (error, eventKey) reporting sink.
ts
get subscriptionCount(): intNumber of active listener handles owned by this scope.
ts
subscribe<T>(key: EventKey<T>, listener: Function): EventSubscriptionAppends a listener for exact key identity and returns its idempotent cancellation handle. Subscribing after close returns an already inactive handle.
ts
emit<T>(key: EventKey<T>, event: T): voidDelivers a listener snapshot in subscription order; changes affect only later emissions. Closing during delivery stops remaining callbacks, while listener errors go to the sink.
ts
forward<T>(target: EventScope, key: EventKey<T>, event: T): voidExplicitly emits on another scope without introducing hierarchy or bubbling.
ts
close(): voidIdempotently prevents future delivery and deactivates every owned subscription.
ts
get isClosed(): booleanWhether the scope has permanently stopped accepting listeners and events.
ts
removeSubscription(subscription: EventSubscription): voidDeactivates and removes an owned handle; repeated or foreign removal is harmless.
EventSubscription
ts
import { EventSubscription } from "gamekit";
class EventSubscriptionIdempotent handle controlling one listener's lifetime in an EventScope.
Members
ts
active: boolean = trueWhether this EventSubscription still accepts work.
ts
constructor(scope: EventScope, entry: ListenerEntry)Binds the handle to its owning scope and private listener entry.
ts
dispose(): voidStops future delivery and detaches from the scope; repeated calls do nothing.
ts
matches(entry: ListenerEntry): booleanTests the private listener-entry identity during owner cleanup.
ts
deactivate(): voidMarks the handle inactive and drops its owner reference without re-entering the owner.
FakeAssetLoader
ts
import { FakeAssetLoader } from "gamekit";
class FakeAssetLoaderDeterministic in-memory loader with configurable failures, delays, and call-order inspection.
Members
ts
loadOrder: Array<AssetKey<any>> = []Asset keys requested in chronological order, including failed attempts.
ts
loadOrderLabels: Array<string> = []Labels captured at each request for concise assertions.
ts
unloadOrder: Array<AssetKey<any>> = []Keys unloaded in chronological order.
ts
set<T>(key: AssetKey<T>, value: T): voidAssociates a value with exact key identity for future successful loads.
ts
setFailures(key: AssetKey<any>, errors: string[]): voidReplaces the queue of error messages thrown by successive loads.
ts
setFailure(key: AssetKey<any>, error: string): voidConfigures one failing attempt for a key.
ts
setDelay(key: AssetKey<any>, delayMs: int): voidSets an asynchronous delay in milliseconds before outcome selection.
ts
getLoadCount(key: AssetKey<any>): intReturns attempted loads for exact key identity.
ts
getUnloadCount(key: AssetKey<any>): intReturns unload calls for exact key identity.
ts
async load(key: AssetKey<any>): Promise<any>Records the attempt, waits its delay, consumes one queued failure, then returns configured or default mock data.
ts
unload(key: AssetKey<any>, asset: any): voidRecords unload and invokes dispose on the asset.
ts
reset(): voidClears configured data, failures, delays, counters, and order traces.
GameKitError
ts
import { GameKitError } from "gamekit";
class GameKitError extends ErrorBase error type for GameKit style guide and lifecycle violations.
Members
ts
constructor(message: string)Preserves a consumer-facing explanation through the standard Error surface.
Gauge
ts
import { Gauge } from "gamekit";
class GaugeNeutral rate-filled value for cooldowns, charge bars and any meter that fills with time. Time arrives through advance, never read from a clock, so a crossing lands on the same tick every run.
Members
ts
value: floatCurrent fill, always within 0 and capacity.
ts
capacity: floatFill at which the gauge is full.
ts
rate: floatFill added per unit of time given to advance.
ts
paused: boolean = falseWhile true, advance leaves the value unchanged.
ts
constructor(capacity: float, rate: float, start: float = 0.0)Starts at start (clamped into range, default empty).
- Throws: InvalidArgument when capacity is not above zero or rate is negative.
ts
advance(dt: float): booleanAdds rate * dt, clamped to capacity. Does nothing while paused.
dt: Time passed, not negative.- Returns: true only on the call that takes the gauge from below capacity to full.
- Throws: InvalidArgument when dt is negative.
ts
consume(amount: float): voidRemoves amount, flooring at zero.
- Throws: InvalidArgument when amount is negative.
ts
fill(): voidSets the value to capacity without reporting a crossing.
InteractionContext
ts
import { InteractionContext } from "gamekit";
class InteractionContext<TActor, TTarget, TEnv>Typed actor, target, and environment tuple shared across interaction discovery.
Members
ts
actor: TActorGame object attempting the interaction.
ts
target: TTargetGame object being inspected or acted upon.
ts
environment: TEnvOptional world or presentation context interpreted by providers.
ts
constructor(actor: TActor, target: TTarget, environment: TEnv = null)Captures game-owned references without copying them.
InteractionDefinition
ts
import { InteractionDefinition } from "gamekit";
class InteractionDefinition<TMetadata>Builds one executable offer from context, optional availability logic, and metadata.
Members
ts
id: stringStable identifier for this InteractionDefinition.
ts
action: Action<any, any>Action executed if the resulting offer is enabled.
ts
requestFactory: FunctionCallback converting discovery context into an ActionRequest.
ts
condition: Condition<any> | nullOptional availability test evaluated during offer creation.
ts
metadataFactory: Function | nullOptional (context, enabled, conditionResult) presentation-data callback.
ts
constructor( id: string, action: Action<any, any>, requestFactory: Function, condition: Condition<any> | null = null, metadataFactory: Function | null = null )Captures a non-empty offer id and its request, action, condition, and metadata factories.
ts
createOffer(context: InteractionContext<any, any, any>): InteractionOffer<TMetadata>Evaluates availability once and captures the request plus metadata in a new offer.
InteractionOffer
ts
import { InteractionOffer } from "gamekit";
class InteractionOffer<TMetadata>Point-in-time executable interaction choice produced during discovery.
Members
ts
id: stringStable identifier for this InteractionOffer.
ts
action: Action<any, any>Action invoked when this offer executes while enabled.
ts
request: ActionRequest<any>Prebuilt invocation captured during discovery.
ts
enabled: booleanWhether this behavior is currently enabled.
ts
conditionResult: ConditionResult | nullAvailability explanation, or null when no condition was configured.
ts
metadata: TMetadataGame-defined display or ranking data captured during discovery.
ts
constructor( id: string, action: Action<any, any>, request: ActionRequest<any>, enabled: boolean = true, conditionResult: ConditionResult | null = null, metadata: TMetadata = null )Captures a non-empty id and the discovery-time execution state.
ts
execute(targetScope: EventScope | null = null): ActionResult<any>Returns denial without invoking the action when disabled; otherwise executes the captured request.
InteractionProvider
ts
import { InteractionProvider } from "gamekit";
class InteractionProvider<TActor, TTarget, TEnv>Named discovery callback that produces zero or more offers for one context.
Members
ts
id: stringStable identifier for this InteractionProvider.
ts
constructor(id: string, discoverFn: Function)Binds a non-empty provider id to a discovery callback.
ts
discover(context: InteractionContext<TActor, TTarget, TEnv>): InteractionOffer<any>[]Normalizes a null callback result to an empty offer list.
ts
static fromDefinition(definition: InteractionDefinition<any>): InteractionProvider<any, any, any>Wraps a single definition as a provider that always returns one captured offer.
InteractionRegistry
ts
import { InteractionRegistry } from "gamekit";
class InteractionRegistryAggregates providers in registration order without imposing ranking or deduplication.
Members
ts
register(provider: InteractionProvider<any, any, any>): voidAppends a provider; duplicate ids remain independently discoverable.
ts
unregister(id: string): booleanRemoves the first provider with the id and reports whether one existed.
ts
discover(actor: any, target: any, environment: any = null): InteractionOffer<any>[]Builds one shared context and concatenates provider offers in stable order.
InvalidArgument
ts
import { InvalidArgument } from "gamekit";
class InvalidArgument extends GameKitErrorReports a public API argument that violates an immediate precondition.
Members
ts
constructor(message: string)Captures the failed precondition in the inherited error message.
InvalidDefinition
ts
import { InvalidDefinition } from "gamekit";
class InvalidDefinition extends DefinitionErrorReports definition data that cannot be validated or resolved.
Members
ts
reason: stringMachine-comparable validation reason, separate from the display message.
ts
constructor(message: string, definitionId: string = "", provenance: string[] = [], reason: string = "")Captures definition identity, provenance, and a concise validation reason.
ISpatialIndex
ts
import { ISpatialIndex } from "gamekit";
interface ISpatialIndex<T>Defines deterministic identity-based insertion and broad-phase 2D spatial queries.
Members
ts
upsert(value: T, bounds: Rect): voidInserts a value or replaces its copied bounds when the same object identity exists.
ts
remove(value: T): booleanRemoves exact object identity and reports whether membership changed.
ts
point(point: Vec2): T[]Returns values whose half-open bounds contain a point (left/top inclusive, right/bottom exclusive).
ts
area(bounds: Rect): T[]Returns values whose bounds overlap an area (touching edges do not overlap).
ts
nearest(point: Vec2, maxDistance?: float): T | nullFinds the first nearest bounds, optionally limited by a world-unit radius.
ts
swept(bounds: Rect, delta: Vec2): T[]Broad-phases against the union of starting and translated bounds.
ts
readonly size: intNumber of distinct value identities currently indexed.
KeyedRegistry
ts
import { KeyedRegistry } from "gamekit";
class KeyedRegistryAssociates heterogeneous values with exact typed-key identities in registration order.
Members
ts
register<T>(key: TypedKey<T>, value: T): voidRetains a value under a key that must not already be present.
ts
get<T>(key: TypedKey<T>): T | nullReads by key identity, returning null when no registration exists.
ts
getRequired<T>(key: TypedKey<T>): TReads by key identity and treats absence as a programming error.
LinearSpatialIndex
ts
import { LinearSpatialIndex } from "gamekit";
class LinearSpatialIndex<T> implements ISpatialIndex<T>Simple insertion-ordered spatial index that linearly scans copied bounds.
Members
ts
upsert(value: T, bounds: Rect): voidInserts by object identity or replaces that value's copied bounds in place.
ts
remove(value: T): booleanRemoves exact object identity and returns whether an entry existed.
ts
point(point: Vec2): T[]Collects containing entries in insertion order. Uses half-open bounds semantics: left/top edges are inclusive, right/bottom edges are exclusive.
ts
area(bounds: Rect): T[]Collects overlapping entries in insertion order. Touching edges do not overlap.
ts
nearest(point: Vec2, maxDistance: float = -1.0): T | nullFinds the first entry at minimum squared distance from a point to its bounds. A radius of -1 means unlimited; other negative values throw.
ts
swept(bounds: Rect, delta: Vec2): T[]Broad-phases the union of starting and translated bounds, not the exact swept shape.
ts
get size(): intNumber of distinct value identities currently indexed.
mergeData
ts
import { mergeData } from "gamekit";
function mergeData(base: any, override: any): anyRecursively overlays plain objects and maps, while other values replace the base. The returned structure does not share nested containers with either input.
MissingRegistration
ts
import { MissingRegistration } from "gamekit";
class MissingRegistration extends GameKitErrorReports a required typed-key, component, or definition registration that is absent.
Members
ts
missingId: stringMissing definition or registration identity, when known.
ts
provenance: string[]Lookup path that led to the absent registration.
ts
constructor(message: string, missingId: string = "", provenance: string[] = [])Captures optional missing-id and lookup-path context for diagnostics.
MutablePipeline
ts
import { MutablePipeline } from "gamekit";
class MutablePipeline<I, O>Runs mutable processing stages over one shared context snapshot in insertion order.
Members
ts
add(stage: Function): PipelineSubscription<I, O>Appends a stage and returns an idempotent handle that can remove it.
ts
run(input: I): PipelineResult<O>Runs the entry snapshot until exhausted or cancelled, then captures the optional output.
ts
dispose(): voidRemoves all stages and deactivates their handles; repeated calls are harmless.
ts
removeSubscription(subscription: PipelineSubscription<I, O>): voidDeactivates and removes one stage; an in-progress run keeps its entry snapshot.
PipelineContext
ts
import { PipelineContext } from "gamekit";
class PipelineContext<I, O>Mutable per-run input, cancellation flag, and optional output shared by pipeline stages.
Members
ts
input: IOriginal input reference supplied to MutablePipeline.run.
ts
cancelled: boolean = falseSet once a stage requests that later stages be skipped.
ts
constructor(input: I)Starts an uncancelled run with no produced output.
ts
cancel(): voidPrevents later stages in the current snapshot from running.
ts
produce(result: O): voidReplaces the output; the last stage to produce wins.
ts
get result(): O | nullLatest produced output, or null when no stage produced one.
PipelineResult
ts
import { PipelineResult } from "gamekit";
class PipelineResult<O>Immutable-by-convention snapshot of a completed pipeline's cancellation and output state.
Members
ts
cancelled: booleanWhether a stage stopped traversal before the snapshot ended.
ts
result: O | nullLast produced output, or null when no stage produced one.
ts
constructor(cancelled: boolean, result: O | null)Captures terminal context values after pipeline traversal.
PipelineSubscription
ts
import { PipelineSubscription } from "gamekit";
class PipelineSubscription<I, O>Idempotent lifetime handle for one stage in a MutablePipeline.
Members
ts
active: boolean = trueWhether this PipelineSubscription still accepts work.
ts
constructor(pipeline: MutablePipeline<I, O>, entry: PipelineStageEntry)Binds the handle to its owner and private stage entry.
ts
dispose(): voidRemoves the stage from future runs; repeated calls do nothing.
ts
matches(entry: PipelineStageEntry): booleanTests private stage-entry identity during owner cleanup.
ts
deactivate(): voidMarks the handle inactive and drops its owner reference without re-entry.
Prefab
ts
import { Prefab } from "gamekit";
class PrefabReusable factory binding for one definition id in a specific registry.
Members
ts
readonly definitionId: stringRegistered definition resolved for every instantiation.
ts
constructor(registry: any, definitionId: string, factory: Function)Binds a non-null registry and factory to a non-empty definition id.
ts
instantiate(context: any = null): anyResolves fresh data and calls the factory as (resolvedDefinition, context).
ResolvedDefinition
ts
import { ResolvedDefinition } from "gamekit";
class ResolvedDefinitionFully merged definition data plus the ordered ids that contributed to it.
Members
ts
readonly id: stringStable identifier for this ResolvedDefinition.
ts
readonly data: anyMerged data snapshot returned independently to each resolver caller.
ts
readonly provenance: string[]Unique parent-first contribution order ending with id.
ts
constructor(id: string, data: any, provenance: string[])Captures a completed resolution result.
StaleHandle
ts
import { StaleHandle } from "gamekit";
class StaleHandle extends GameKitErrorReports mutation through an entity or effect handle whose lifetime has ended.
Members
ts
constructor(message: string)Captures which retired identity was used in the inherited message.
StateMachine
ts
import { StateMachine } from "gamekit";
class StateMachine<TOwner>Runs explicit named-state callbacks with guarded, FIFO transitions and optional clock scheduling. Transitions requested from callbacks queue behind the current callback and obey a per-drain work cap.
Members
ts
constructor(owner: TOwner, clock: any | null = null, transitionWorkCap: int = 64)Binds an owner, optional scheduler, and positive transition-chain safety cap.
ts
get stateName(): string | nullCurrent state name, or null before start and after disposal.
ts
get processing(): booleanWhether an enter, exit, update, or transition drain is active.
ts
get disposed(): booleanWhether teardown has permanently disabled the machine.
ts
addState(state: StateMachineState<TOwner>): voidRegisters a uniquely named state before the machine starts.
ts
permit(source: string, target: string, guard: Function | null = null): voidDeclares one directed transition with an optional (owner, context) guard.
ts
start(name: string, context: any = null): voidEnters the initial state, then drains transitions queued by its callback.
ts
transition(target: string, context: any = null): booleanEvaluates the declared guard and queues a permitted transition. Returns false only when the guard rejects it; callback requests return before the queue drains.
ts
update(delta: float): voidInvokes the current state's (owner, deltaSeconds) callback and drains queued transitions.
ts
transitionAfter(delay: float, target: string, context: any = null): anySchedules a transition on the injected clock and returns its cancellable work handle.
ts
dispose(context: any = null): voidIdempotently cancels scheduled work, clears queued transitions, and exits the current state.
ts
inspect(): StateMachineInspectionCaptures current state, queue, transition, processing, disposal, and timer counts.
StateMachineInspection
ts
import { StateMachineInspection } from "gamekit";
class StateMachineInspectionPoint-in-time diagnostic counters and lifecycle flags for a StateMachine.
Members
ts
stateName: string | nullCurrent state name, or null when not started or disposed.
ts
queuedTransitions: intFIFO requests waiting behind current callback work.
ts
transitionCount: intSuccessful initial entry and state changes completed so far.
ts
processing: booleanWhether callback or transition work was active at capture time.
ts
disposed: booleanWhether the machine had permanently completed teardown.
ts
scheduledTransitions: intTimer handles retained for cancellation on dispose.
ts
constructor(stateName: string | null, queuedTransitions: int, transitionCount: int, processing: boolean, disposed: boolean, scheduledTransitions: int)Captures scalar state without retaining the inspected machine.
StateMachineState
ts
import { StateMachineState } from "gamekit";
class StateMachineState<TOwner>Named state with optional owner callbacks for entry, exit, and fixed updates.
Members
ts
name: stringOptional label used in diagnostics.
ts
enter: Function | nullOptional (owner, context) callback invoked after becoming current.
ts
exit: Function | nullOptional (owner, context) callback invoked before leaving current state.
ts
update: Function | nullOptional (owner, deltaSeconds) callback invoked by machine updates.
ts
constructor(name: string, callbacks: any = {})Captures a non-empty name and the recognized callbacks from an options object.
Transform2D
ts
import { Transform2D } from "gamekit";
class Transform2DMutable 2D position, rotation, and scale value with no scene-graph ownership.
Members
ts
position: Vec2Translation in world units.
ts
rotation: floatClockwise rotation in radians.
ts
scale: Vec2Independent x/y scale multipliers.
ts
constructor(position: Vec2 = Vec2{}, rotation: float = 0.0, scale: Vec2 = Vec2{ x: 1.0, y: 1.0 })Retains the supplied mutable vectors and rotation value.
ts
copy(): Transform2DDeep-copies position and scale so later vector edits are independent.
TypedKey
ts
import { TypedKey } from "gamekit";
class TypedKey<T>Provides a process-unique, type-carrying identity for registries; labels are diagnostic only.
Members
ts
label: stringHuman-readable name shown in errors and inspection output.
ts
constructor(kind: string, label: string)Allocates a fresh identity token for a non-empty diagnostic label.
ts
equals(other: TypedKey<any>): booleanCompares identity tokens, so separately constructed keys never alias by label.
ts
getToken(): intExposes the process-local token used for equality and deterministic diagnostics.
ts
describe(): stringFormats the key kind, label, and unique token for error messages.
WeightedPick
ts
import { WeightedPick } from "gamekit";
class WeightedPick<T>Weighted choice over an injected Random, the only source of chance, so a seed gives a fixed sequence. Entries with weight 0 are never chosen. fork(name) derives an independent stream from the original seed, so several tables stay reproducible whatever order they are created in.
Members
ts
constructor(random: Random)Uses random for every draw; the table starts empty.
ts
get count(): intNumber of entries, including zero-weight ones.
ts
add(item: T, weight: float): voidAppends an entry. Higher weight is proportionally more likely; 0 is never chosen.
- Throws: InvalidArgument when weight is negative or not a number.
ts
pick(): TDraws one entry.
- Throws: InvalidArgument when the table has no entry with a weight above zero.
ts
fork(name: string): WeightedPick<T>Copies the entries onto a table that draws from random.fork(name); later add calls on either table do not affect the other.