@almadar/core 2.0.0 → 2.1.1

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.
@@ -433,6 +433,148 @@ interface ValidationDocument {
433
433
  validatedAt: number;
434
434
  }
435
435
 
436
+ /**
437
+ * Service Contract Types
438
+ *
439
+ * Formalizes the two public surfaces of an Almadar service:
440
+ * 1. Call-Service Contract — what the .orb schema can invoke on the TypeScript package
441
+ * 2. Event Contract — what events enter/leave the service
442
+ *
443
+ * Plus internal-but-standardized patterns:
444
+ * 3. StoreContract — database abstraction boundary
445
+ * 4. LazyService — singleton lifecycle pattern
446
+ *
447
+ * @packageDocumentation
448
+ */
449
+ /**
450
+ * Action definition for a service contract.
451
+ * Each action has typed params and a typed result.
452
+ */
453
+ interface ServiceAction {
454
+ params: Record<string, unknown>;
455
+ result: unknown;
456
+ }
457
+ /**
458
+ * What `["call-service", "name", "action", {...}]` actually calls at runtime.
459
+ * Each service defines its action map as a Record<string, ServiceAction>.
460
+ *
461
+ * @example
462
+ * ```typescript
463
+ * type LLMActions = {
464
+ * generate: {
465
+ * params: { userPrompt: string; model: string; maxTokens: number };
466
+ * result: { content: string; tokensUsed: number; latencyMs: number };
467
+ * };
468
+ * };
469
+ *
470
+ * class LLMService implements ServiceContract<LLMActions> {
471
+ * async execute(action, params) { ... }
472
+ * }
473
+ * ```
474
+ */
475
+ interface ServiceContract<Actions extends Record<string, ServiceAction>> {
476
+ execute<A extends keyof Actions & string>(action: A, params: Actions[A]["params"]): Promise<Actions[A]["result"]>;
477
+ }
478
+ /**
479
+ * Event contract — what events the service emits/listens with typed payloads.
480
+ * Derived from the `.orb` schema's `emits` and `listens` declarations.
481
+ *
482
+ * @example
483
+ * ```typescript
484
+ * type LLMEventMap = {
485
+ * AGENT_LLM_REQUEST: { requestId: string; prompt: string };
486
+ * LLM_RESPONSE: { requestId: string; content: string; tokensUsed: number };
487
+ * LLM_ERROR: { requestId: string; error: string };
488
+ * };
489
+ *
490
+ * const events: ServiceEvents<LLMEventMap> = getEventBus();
491
+ * events.emit('LLM_RESPONSE', { requestId: '1', content: '...', tokensUsed: 42 });
492
+ * ```
493
+ */
494
+ interface ServiceEvents<EventMap extends Record<string, Record<string, unknown>>> {
495
+ emit<E extends keyof EventMap & string>(event: E, payload: EventMap[E]): void;
496
+ on<E extends keyof EventMap & string>(event: E, handler: (payload: EventMap[E]) => void): () => void;
497
+ }
498
+ /**
499
+ * Create a typed view of an untyped EventBus. Wraps the raw EventBus
500
+ * with compile-time type checking while keeping runtime behavior identical.
501
+ *
502
+ * @example
503
+ * ```typescript
504
+ * type LLMEventMap = {
505
+ * LLM_RESPONSE: { requestId: string; content: string };
506
+ * LLM_ERROR: { requestId: string; error: string };
507
+ * };
508
+ *
509
+ * const typedBus = createTypedEventBus<LLMEventMap>(getServerEventBus());
510
+ * typedBus.emit('LLM_RESPONSE', { requestId: '1', content: '...' }); // type-safe
511
+ * typedBus.on('LLM_ERROR', (payload) => { payload.error; }); // payload is typed
512
+ * ```
513
+ */
514
+ declare function createTypedEventBus<EventMap extends Record<string, Record<string, unknown>>>(bus: {
515
+ emit(event: string, payload?: unknown, meta?: Record<string, unknown>): void;
516
+ on(event: string, handler: (payload: unknown, meta?: Record<string, unknown>) => void): () => void;
517
+ }): ServiceEvents<EventMap>;
518
+ /** Filter operator for store queries. */
519
+ type StoreFilterOp = "==" | "!=" | "<" | "<=" | ">" | ">=" | "in" | "not-in" | "contains";
520
+ /** A single filter clause for store queries. */
521
+ interface StoreFilter<T> {
522
+ field: keyof T & string;
523
+ op: StoreFilterOp;
524
+ value: unknown;
525
+ }
526
+ /**
527
+ * Database abstraction boundary. Services receive `StoreContract<T>`,
528
+ * not raw database clients. Swappable per database engine.
529
+ *
530
+ * @example
531
+ * ```typescript
532
+ * interface LLMRequest { id: string; prompt: string; status: string }
533
+ *
534
+ * class FirestoreLLMRequestStore implements StoreContract<LLMRequest> {
535
+ * async getById(id) { ... }
536
+ * async create(data) { ... }
537
+ * async update(id, data) { ... }
538
+ * async delete(id) { ... }
539
+ * async query(filters) { ... }
540
+ * }
541
+ * ```
542
+ */
543
+ interface StoreContract<T extends {
544
+ id: string;
545
+ }> {
546
+ getById(id: string): Promise<T | null>;
547
+ create(data: Omit<T, "id">): Promise<T>;
548
+ update(id: string, data: Partial<T>): Promise<T>;
549
+ delete(id: string): Promise<void>;
550
+ query(filters: StoreFilter<T>[]): Promise<T[]>;
551
+ }
552
+ /**
553
+ * Standardized singleton lifecycle. Replaces ad-hoc
554
+ * `let x = null; export function getX()` patterns.
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * const llmClient = createLazyService(() => new LLMClient({ apiKey: process.env.LLM_KEY }));
559
+ *
560
+ * // In request handler:
561
+ * const client = llmClient.get(); // created on first call, cached after
562
+ *
563
+ * // In test teardown:
564
+ * llmClient.reset(); // next get() creates a fresh instance
565
+ * ```
566
+ */
567
+ interface LazyService<T> {
568
+ /** Get the singleton instance (creates on first call). */
569
+ get(): T;
570
+ /** Reset the singleton (next get() creates fresh). For test isolation. */
571
+ reset(): void;
572
+ }
573
+ /**
574
+ * Create a lazy singleton from a factory function.
575
+ */
576
+ declare function createLazyService<T>(factory: () => T): LazyService<T>;
577
+
436
578
  /**
437
579
  * Shared Intermediate Representation Types
438
580
  *
@@ -701,4 +843,4 @@ declare function createResolvedField(field: {
701
843
  }): ResolvedField;
702
844
  declare function isResolvedIR(ir: unknown): ir is ResolvedIR;
703
845
 
704
- export { type AppSummary, BINDING_CONTEXT_RULES, BINDING_DOCS, type BindingContext, BindingSchema, type CategorizedRemovals, type ChangeAuthor, type ChangeSetDocument, type ChangeSummary, type CreateFlow, DEFAULT_INTERACTION_MODELS, type DeleteFlow, type EditFlow, type GitHubLink, type HistoryMeta, type InteractionModel, type InteractionModelInput, InteractionModelSchema, type ListInteraction, type OperatorName, type PageContentReduction, PatternTypeSchema, type ResolvedEntity, type ResolvedEntityBinding, type ResolvedField, type ResolvedIR, type ResolvedNavigation, type ResolvedPage, type ResolvedPattern, type ResolvedSection, type ResolvedSectionEvent, type ResolvedTrait, type ResolvedTraitBinding, type ResolvedTraitDataEntity, type ResolvedTraitEvent, type ResolvedTraitGuard, type ResolvedTraitListener, type ResolvedTraitState, type ResolvedTraitTick, type ResolvedTraitTransition, type ResolvedTraitUIBinding, SExpr, type SaveOptions, type SaveResult, type SchemaChange, type SnapshotDocument, type StatsView, type TransitionFrom, type ValidationDocument, type ValidationIssue, type ValidationMeta, type ValidationResults, type ViewFlow, createEmptyResolvedPage, createEmptyResolvedTrait, createResolvedField, getAllOperators, getAllPatternTypes, getBindingExamples, getInteractionModelForDomain, inferTsType, isResolvedIR, validateBindingInContext };
846
+ export { type AppSummary, BINDING_CONTEXT_RULES, BINDING_DOCS, type BindingContext, BindingSchema, type CategorizedRemovals, type ChangeAuthor, type ChangeSetDocument, type ChangeSummary, type CreateFlow, DEFAULT_INTERACTION_MODELS, type DeleteFlow, type EditFlow, type GitHubLink, type HistoryMeta, type InteractionModel, type InteractionModelInput, InteractionModelSchema, type LazyService, type ListInteraction, type OperatorName, type PageContentReduction, PatternTypeSchema, type ResolvedEntity, type ResolvedEntityBinding, type ResolvedField, type ResolvedIR, type ResolvedNavigation, type ResolvedPage, type ResolvedPattern, type ResolvedSection, type ResolvedSectionEvent, type ResolvedTrait, type ResolvedTraitBinding, type ResolvedTraitDataEntity, type ResolvedTraitEvent, type ResolvedTraitGuard, type ResolvedTraitListener, type ResolvedTraitState, type ResolvedTraitTick, type ResolvedTraitTransition, type ResolvedTraitUIBinding, SExpr, type SaveOptions, type SaveResult, type SchemaChange, type ServiceAction, type ServiceContract, type ServiceEvents, type SnapshotDocument, type StatsView, type StoreContract, type StoreFilter, type StoreFilterOp, type TransitionFrom, type ValidationDocument, type ValidationIssue, type ValidationMeta, type ValidationResults, type ViewFlow, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, getAllOperators, getAllPatternTypes, getBindingExamples, getInteractionModelForDomain, inferTsType, isResolvedIR, validateBindingInContext };
@@ -1124,6 +1124,32 @@ function getAllPatternTypes() {
1124
1124
  return [...PATTERN_TYPES];
1125
1125
  }
1126
1126
 
1127
+ // src/service-types.ts
1128
+ function createTypedEventBus(bus) {
1129
+ return {
1130
+ emit(event, payload) {
1131
+ bus.emit(event, payload);
1132
+ },
1133
+ on(event, handler) {
1134
+ return bus.on(event, handler);
1135
+ }
1136
+ };
1137
+ }
1138
+ function createLazyService(factory) {
1139
+ let instance = null;
1140
+ return {
1141
+ get() {
1142
+ if (instance === null) {
1143
+ instance = factory();
1144
+ }
1145
+ return instance;
1146
+ },
1147
+ reset() {
1148
+ instance = null;
1149
+ }
1150
+ };
1151
+ }
1152
+
1127
1153
  // src/types/ir.ts
1128
1154
  function createEmptyResolvedTrait(name, source) {
1129
1155
  return {
@@ -1186,6 +1212,6 @@ function isResolvedIR(ir) {
1186
1212
  return typeof r.appName === "string" && r.traits instanceof Map && r.pages instanceof Map;
1187
1213
  }
1188
1214
 
1189
- export { AGENT_DOMAIN_CATEGORIES, ALLOWED_CUSTOM_COMPONENTS, AgentDomainCategorySchema, AnimationDefSchema, AssetMapSchema, AssetMappingSchema, BINDING_CONTEXT_RULES, BINDING_DOCS, BindingSchema, CORE_BINDINGS, ComputedEventContractSchema, ComputedEventListenerSchema, CustomPatternDefinitionSchema, CustomPatternMapSchema, DEFAULT_INTERACTION_MODELS, DesignPreferencesSchema, DesignTokensSchema, DomainCategorySchema, DomainContextSchema, DomainVocabularySchema, ENTITY_ROLES, EffectSchema, EntityFieldSchema, EntityPersistenceSchema, EntityRefSchema, EntityRefStringSchema, EntityRoleSchema, EntitySchema, EntitySemanticRoleSchema, EventListenerSchema, EventPayloadFieldSchema, EventSchema, EventScopeSchema, EventSemanticRoleSchema, EventSourceSchema, ExpressionSchema, FieldFormatSchema, FieldSchema, FieldTypeSchema, GAME_TYPES, GameSubCategorySchema, GameTypeSchema, GuardSchema, InteractionModelSchema, McpServiceDefSchema, NodeClassificationSchema, OrbitalConfigSchema, OrbitalDefinitionSchema, OrbitalEntitySchema, OrbitalPageSchema, OrbitalPageStrictSchema, OrbitalSchemaSchema, OrbitalTraitRefSchema, OrbitalUnitSchema, OrbitalSchema as OrbitalZodSchema, PageRefObjectSchema, PageRefSchema, PageRefStringSchema, PageSchema, PageTraitRefSchema, PatternTypeSchema, PayloadFieldSchema, RelatedLinkSchema, RelationConfigSchema, RequiredFieldSchema, ResolvedAssetSchema, RestAuthConfigSchema, RestServiceDefSchema, SERVICE_TYPES, SExprAtomSchema, SExprSchema, SemanticAssetRefSchema, ServiceDefinitionSchema, ServiceRefSchema, ServiceRefStringSchema, ServiceTypeSchema, SocketEventsSchema, SocketServiceDefSchema, StateMachineSchema, StateSchema, StateSemanticRoleSchema, SuggestedGuardSchema, ThemeDefinitionSchema, ThemeRefSchema, ThemeRefStringSchema, ThemeTokensSchema, ThemeVariantSchema, TraitCategorySchema, TraitDataEntitySchema, TraitEntityFieldSchema, TraitEventContractSchema, TraitEventListenerSchema, TraitRefSchema, TraitReferenceSchema, TraitSchema, TraitTickSchema, TransitionSchema, UISlotSchema, UI_SLOTS, UXHintsSchema, UseDeclarationSchema, UserPersonaSchema, VISUAL_STYLES, ViewTypeSchema, VisualStyleSchema, callService, collectBindings, createAssetKey, createEmptyResolvedPage, createEmptyResolvedTrait, createResolvedField, deriveCollection, despawn, doEffects, emit, findService, getAllOperators, getAllPatternTypes, getArgs, getBindingExamples, getDefaultAnimationsForRole, getInteractionModelForDomain, getOperator, getServiceNames, getTraitConfig, getTraitName, hasService, inferTsType, isBinding, isCircuitEvent, isEffect, isEntityReference, isImportedTraitRef, isInlineTrait, isMcpService, isOrbitalDefinition, isPageReference, isPageReferenceObject, isPageReferenceString, isResolvedIR, isRestService, isRuntimeEntity, isSExpr, isSExprAtom, isSExprCall, isSExprEffect, isServiceReference, isSingletonEntity, isSocketService, isThemeReference, isValidBinding, navigate, normalizeTraitRef, notify, parseAssetKey, parseBinding, parseEntityRef, parseImportedTraitRef, parseOrbitalSchema, parsePageRef, parseServiceRef, persist, renderUI, safeParseOrbitalSchema, set, sexpr, spawn, validateAssetAnimations, validateBindingInContext, walkSExpr };
1215
+ export { AGENT_DOMAIN_CATEGORIES, ALLOWED_CUSTOM_COMPONENTS, AgentDomainCategorySchema, AnimationDefSchema, AssetMapSchema, AssetMappingSchema, BINDING_CONTEXT_RULES, BINDING_DOCS, BindingSchema, CORE_BINDINGS, ComputedEventContractSchema, ComputedEventListenerSchema, CustomPatternDefinitionSchema, CustomPatternMapSchema, DEFAULT_INTERACTION_MODELS, DesignPreferencesSchema, DesignTokensSchema, DomainCategorySchema, DomainContextSchema, DomainVocabularySchema, ENTITY_ROLES, EffectSchema, EntityFieldSchema, EntityPersistenceSchema, EntityRefSchema, EntityRefStringSchema, EntityRoleSchema, EntitySchema, EntitySemanticRoleSchema, EventListenerSchema, EventPayloadFieldSchema, EventSchema, EventScopeSchema, EventSemanticRoleSchema, EventSourceSchema, ExpressionSchema, FieldFormatSchema, FieldSchema, FieldTypeSchema, GAME_TYPES, GameSubCategorySchema, GameTypeSchema, GuardSchema, InteractionModelSchema, McpServiceDefSchema, NodeClassificationSchema, OrbitalConfigSchema, OrbitalDefinitionSchema, OrbitalEntitySchema, OrbitalPageSchema, OrbitalPageStrictSchema, OrbitalSchemaSchema, OrbitalTraitRefSchema, OrbitalUnitSchema, OrbitalSchema as OrbitalZodSchema, PageRefObjectSchema, PageRefSchema, PageRefStringSchema, PageSchema, PageTraitRefSchema, PatternTypeSchema, PayloadFieldSchema, RelatedLinkSchema, RelationConfigSchema, RequiredFieldSchema, ResolvedAssetSchema, RestAuthConfigSchema, RestServiceDefSchema, SERVICE_TYPES, SExprAtomSchema, SExprSchema, SemanticAssetRefSchema, ServiceDefinitionSchema, ServiceRefSchema, ServiceRefStringSchema, ServiceTypeSchema, SocketEventsSchema, SocketServiceDefSchema, StateMachineSchema, StateSchema, StateSemanticRoleSchema, SuggestedGuardSchema, ThemeDefinitionSchema, ThemeRefSchema, ThemeRefStringSchema, ThemeTokensSchema, ThemeVariantSchema, TraitCategorySchema, TraitDataEntitySchema, TraitEntityFieldSchema, TraitEventContractSchema, TraitEventListenerSchema, TraitRefSchema, TraitReferenceSchema, TraitSchema, TraitTickSchema, TransitionSchema, UISlotSchema, UI_SLOTS, UXHintsSchema, UseDeclarationSchema, UserPersonaSchema, VISUAL_STYLES, ViewTypeSchema, VisualStyleSchema, callService, collectBindings, createAssetKey, createEmptyResolvedPage, createEmptyResolvedTrait, createLazyService, createResolvedField, createTypedEventBus, deriveCollection, despawn, doEffects, emit, findService, getAllOperators, getAllPatternTypes, getArgs, getBindingExamples, getDefaultAnimationsForRole, getInteractionModelForDomain, getOperator, getServiceNames, getTraitConfig, getTraitName, hasService, inferTsType, isBinding, isCircuitEvent, isEffect, isEntityReference, isImportedTraitRef, isInlineTrait, isMcpService, isOrbitalDefinition, isPageReference, isPageReferenceObject, isPageReferenceString, isResolvedIR, isRestService, isRuntimeEntity, isSExpr, isSExprAtom, isSExprCall, isSExprEffect, isServiceReference, isSingletonEntity, isSocketService, isThemeReference, isValidBinding, navigate, normalizeTraitRef, notify, parseAssetKey, parseBinding, parseEntityRef, parseImportedTraitRef, parseOrbitalSchema, parsePageRef, parseServiceRef, persist, renderUI, safeParseOrbitalSchema, set, sexpr, spawn, validateAssetAnimations, validateBindingInContext, walkSExpr };
1190
1216
  //# sourceMappingURL=index.js.map
1191
1217
  //# sourceMappingURL=index.js.map