@almadar/integrations 2.23.0 → 2.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,5 @@
1
1
  import { B as BaseIntegration, I as IntegrationConfig, e as IntegrationParams, f as IntegrationResult } from '../BaseIntegration-MA-b4fh8.js';
2
- import { I as IntegrationFactory } from '../factory-DTdVeyAi.js';
2
+ import { a as IntegrationFactory } from '../factory-BPVhvv5q.js';
3
3
  import '@almadar/core';
4
4
 
5
5
  /**
@@ -251,56 +251,80 @@ function getIntegration(name) {
251
251
  }
252
252
 
253
253
  // src/factory.ts
254
+ function instanceKey(name, principal) {
255
+ return principal ? `${name}\0${principal}` : name;
256
+ }
254
257
  var IntegrationFactory = class {
255
258
  constructor() {
256
259
  this.instances = /* @__PURE__ */ new Map();
257
260
  this.configs = /* @__PURE__ */ new Map();
258
261
  }
259
262
  /**
260
- * Configure an integration (doesn't instantiate yet)
263
+ * Configure an integration (doesn't instantiate yet). A `principal` scopes
264
+ * the config to that principal; the app-wide config (no principal) is the
265
+ * fallback for every principal.
261
266
  */
262
- configure(name, config) {
263
- this.configs.set(name, { name, ...config });
267
+ configure(name, config, principal) {
268
+ this.configs.set(instanceKey(name, principal), { name, ...config });
264
269
  }
265
270
  /**
266
- * Get or create an integration instance
271
+ * Get or create an integration instance. Principal-scoped lookups fall
272
+ * back to the app-wide config when no per-principal config exists.
267
273
  */
268
- get(name) {
269
- if (this.instances.has(name)) {
270
- return this.instances.get(name);
274
+ get(name, principal) {
275
+ const key = instanceKey(name, principal);
276
+ const cached = this.instances.get(key);
277
+ if (cached) {
278
+ return cached;
271
279
  }
272
280
  const Constructor = getIntegration(name);
273
281
  if (!Constructor) {
274
282
  throw new Error(`Unknown integration: ${name}. Make sure it's imported.`);
275
283
  }
276
- const config = this.configs.get(name);
284
+ const config = this.configs.get(key) ?? this.configs.get(name);
277
285
  if (!config) {
278
286
  throw new Error(
279
287
  `Integration not configured: ${name}. Call configure() first.`
280
288
  );
281
289
  }
282
290
  const instance = new Constructor(config);
283
- this.instances.set(name, instance);
291
+ this.instances.set(key, instance);
284
292
  return instance;
285
293
  }
286
294
  /**
287
295
  * Execute an action on an integration
288
296
  */
289
- async execute(integration, action, params) {
290
- const instance = this.get(integration);
297
+ async execute(integration, action, params, context) {
298
+ const instance = this.get(integration, context?.principal);
291
299
  return await instance.execute(action, params);
292
300
  }
293
301
  /**
294
302
  * Check if integration is configured
295
303
  */
296
- isConfigured(name) {
297
- return this.configs.has(name);
304
+ isConfigured(name, principal) {
305
+ return this.configs.has(instanceKey(name, principal)) || this.configs.has(name);
298
306
  }
299
307
  /**
300
308
  * Register an integration instance directly (used by mock infrastructure)
301
309
  */
302
- registerInstance(name, instance) {
303
- this.instances.set(name, instance);
310
+ registerInstance(name, instance, principal) {
311
+ this.instances.set(instanceKey(name, principal), instance);
312
+ }
313
+ /**
314
+ * Drop the cached instance(s) for a name so the next `get` rebuilds from
315
+ * the current config — how a credential change goes live without restart.
316
+ * Configs are kept; without a name, every instance is dropped.
317
+ */
318
+ invalidate(name) {
319
+ if (name === void 0) {
320
+ this.instances.clear();
321
+ return;
322
+ }
323
+ for (const key of this.instances.keys()) {
324
+ if (key === name || key.startsWith(`${name}\0`)) {
325
+ this.instances.delete(key);
326
+ }
327
+ }
304
328
  }
305
329
  /**
306
330
  * Clear all instances (useful for testing)
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/core/logger.ts","../../src/core/validation.ts","../../src/core/retry.ts","../../src/core/BaseIntegration.ts","../../src/types.ts","../../src/mocks/MockIntegration.ts","../../src/registry.ts","../../src/factory.ts","../../src/mocks/MockIntegrationFactory.ts"],"names":[],"mappings":";;;;AAeO,IAAM,gBAAN,MAAiD;AAAA,EAGtD,WAAA,CAAY,SAA8C,MAAA,EAAQ;AAEhE,IAAA,IAAA,CAAK,GAAA,GAAM,aAAa,sBAAsB,CAAA;AAAA,EAChD;AAAA,EAEA,KAAA,CAAM,SAAiB,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AA,EAKA,eAAA,CAAgB,WAAA,EAAqB,MAAA,EAAgB,IAAA,EAAqB;AACxE,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,CAAI,WAAW,CAAA;AACrC,IAAA,QAAA,CAAS,WAAA,CAAY,QAAQ,IAAI,CAAA;AAAA,EACnC;AAAA;AAAA;AAAA;AAAA,EAKA,aACE,WAAA,EACsD;AACtD,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,CAAI,WAAW,CAAA;AACrC,IAAA,OAAO,SAAS,QAAA,EAAS;AAAA,EAC3B;AAAA;AAAA;AAAA;AAAA,EAKA,eAAe,WAAA,EAA2B;AACxC,IAAA,MAAM,QAAA,GAAW,IAAA,CAAK,GAAA,CAAI,WAAW,CAAA;AACrC,IAAA,QAAA,CAAS,UAAA,EAAW;AAAA,EACtB;AACF","file":"index.js","sourcesContent":["import { createLogger, type Logger } from '@almadar/logger';\nimport type { IntegrationLogger, LogMeta } from '../types';\n\n/**\n * Console-based logger implementation.\n *\n * Routes through `@almadar/logger`'s shared gate so namespace filtering\n * (`ALMADAR_DEBUG`, `globalThis.__ALMADAR_DEBUG__`) and the production\n * level default (WARN+) apply uniformly with the rest of `@almadar/*`.\n *\n * The constructor's `level` argument is retained for backwards\n * compatibility but is now a no-op — the active level is owned by the\n * shared logger (compile-time + env). To filter integration logs at\n * runtime, set `globalThis.__ALMADAR_DEBUG__ = 'almadar:integrations:*'`.\n */\nexport class ConsoleLogger implements IntegrationLogger {\n private readonly log: Logger;\n\n constructor(_level: 'debug' | 'info' | 'warn' | 'error' = 'info') {\n void _level;\n this.log = createLogger('almadar:integrations');\n }\n\n debug(message: string, meta?: LogMeta): void {\n this.log.debug(message, meta);\n }\n info(message: string, meta?: LogMeta): void {\n this.log.info(message, meta);\n }\n warn(message: string, meta?: LogMeta): void {\n this.log.warn(message, meta);\n }\n error(message: string, meta?: LogMeta): void {\n this.log.error(message, meta);\n }\n}\n","import type { ValidationResult, ValidationError, IntegrationParams } from '../types';\n\n// Import integrators registry from the package main export (JSON is inlined in the bundle)\nimport { integratorsRegistry } from '@almadar/core/patterns';\n\ninterface ActionParam {\n name: string;\n type: string;\n required?: boolean;\n description?: string;\n}\n\ninterface ActionDef {\n name: string;\n description?: string;\n params: ActionParam[];\n}\n\ninterface IntegratorEntry {\n name: string;\n description?: string;\n category?: string;\n actions: ActionDef[];\n}\n\ntype IntegratorsRegistry = Record<string, {\n version?: string;\n exportedAt?: string;\n integrators: Record<string, IntegratorEntry>;\n}>;\n\n/**\n * Validate action params against registry schema\n */\nexport function validateParams(\n integration: string,\n action: string,\n params: IntegrationParams,\n): ValidationResult {\n const typedRegistry = integratorsRegistry as IntegratorsRegistry[string];\n const registry = typedRegistry.integrators[integration];\n\n if (!registry) {\n return {\n valid: false,\n errors: [\n {\n param: 'integration',\n message: `Unknown integration: ${integration}`,\n },\n ],\n };\n }\n\n const actionDef = registry.actions.find((a: ActionDef) => a.name === action);\n\n if (!actionDef) {\n return {\n valid: false,\n errors: [{ param: 'action', message: `Unknown action: ${action}` }],\n };\n }\n\n const errors: ValidationError[] = [];\n\n // Check required params\n for (const paramDef of actionDef.params) {\n if (paramDef.required && !(paramDef.name in params)) {\n errors.push({\n param: paramDef.name,\n message: `Missing required parameter: ${paramDef.name}`,\n });\n }\n\n // Type validation\n if (paramDef.name in params) {\n const value = params[paramDef.name];\n const expectedType = paramDef.type;\n const actualType = typeof value;\n\n if (expectedType === 'number' && actualType !== 'number') {\n errors.push({\n param: paramDef.name,\n message: `Expected ${expectedType}, got ${actualType}`,\n });\n }\n\n if (expectedType === 'string' && actualType !== 'string') {\n errors.push({\n param: paramDef.name,\n message: `Expected ${expectedType}, got ${actualType}`,\n });\n }\n\n if (expectedType === 'array' && !Array.isArray(value)) {\n errors.push({\n param: paramDef.name,\n message: `Expected array, got ${actualType}`,\n });\n }\n\n if (\n expectedType === 'object' &&\n (actualType !== 'object' || Array.isArray(value) || value === null)\n ) {\n errors.push({\n param: paramDef.name,\n message: `Expected object, got ${actualType}`,\n });\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n","import type { IntegrationError, IntegrationErrorCode } from '../types';\n\n/**\n * Retry configuration\n */\nexport interface RetryConfig {\n maxAttempts: number;\n backoffMs: number;\n maxBackoffMs?: number;\n retryableErrors?: IntegrationErrorCode[];\n}\n\n/**\n * Execute a function with retry logic\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n config: RetryConfig,\n): Promise<T> {\n const {\n maxAttempts,\n backoffMs,\n maxBackoffMs = 30000,\n retryableErrors,\n } = config;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if error is retryable\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n retryableErrors\n ) {\n const integrationError = error as IntegrationError;\n if (!retryableErrors.includes(integrationError.code)) {\n throw error;\n }\n }\n\n // Last attempt, throw\n if (attempt === maxAttempts) {\n throw error;\n }\n\n // Wait before retry (exponential backoff)\n const delay = Math.min(\n backoffMs * Math.pow(2, attempt - 1),\n maxBackoffMs,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type {\n IntegrationConfig,\n IntegrationResult,\n IntegrationLogger,\n IntegrationError,\n IntegrationParams,\n} from '../types';\nimport { ConsoleLogger } from './logger';\nimport { validateParams } from './validation';\nimport { withRetry } from './retry';\n\n/**\n * Base class for all integrations\n */\nexport abstract class BaseIntegration {\n protected config: IntegrationConfig;\n protected logger: IntegrationLogger;\n\n constructor(config: IntegrationConfig) {\n this.config = config;\n this.logger = config.logger || new ConsoleLogger();\n }\n\n /**\n * Execute an action\n */\n abstract execute(\n action: string,\n params: IntegrationParams,\n ): Promise<IntegrationResult>;\n\n /**\n * Validate action params against registry\n */\n protected validateParams(\n action: string,\n params: IntegrationParams,\n ): ReturnType<typeof validateParams> {\n return validateParams(this.config.name, action, params);\n }\n\n /**\n * Handle errors uniformly\n */\n protected handleError(action: string, error: unknown): IntegrationResult {\n this.logger.error(`Integration error in ${this.config.name}.${action}`, {\n error: error instanceof Error ? error : new Error(String(error)),\n });\n\n const integrationError =\n error instanceof Error\n ? error\n : new Error(String(error));\n\n return {\n success: false,\n error: integrationError as IntegrationError,\n metadata: this.createMetadata(action, 0, 0),\n };\n }\n\n /**\n * Create metadata for result\n */\n protected createMetadata(\n action: string,\n duration: number,\n retries: number = 0,\n ): IntegrationResult['metadata'] {\n return {\n integration: this.config.name,\n action,\n duration,\n retries,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Execute with retry logic\n */\n protected async executeWithRetry<T>(\n fn: () => Promise<T>,\n ): Promise<T> {\n if (!this.config.retry) {\n return fn();\n }\n\n return withRetry(fn, {\n maxAttempts: this.config.retry.maxAttempts,\n backoffMs: this.config.retry.backoffMs,\n maxBackoffMs: this.config.retry.maxBackoffMs,\n retryableErrors: [\n 'TIMEOUT_ERROR',\n 'NETWORK_ERROR',\n 'RATE_LIMIT_ERROR',\n ],\n });\n }\n}\n","/**\n * Core types for Almadar integrations\n */\n\n/**\n * Configuration for an integration instance\n */\nexport interface IntegrationConfig {\n /** Integration name (matches registry) */\n name: string;\n\n /** Environment variables (API keys, secrets) */\n env: Record<string, string>;\n\n /** Optional logger */\n logger?: IntegrationLogger;\n\n /** Optional rate limiting config */\n rateLimit?: {\n requestsPerSecond: number;\n burstSize: number;\n };\n\n /** Optional timeout (ms) */\n timeout?: number;\n\n /** Optional retry config */\n retry?: {\n maxAttempts: number;\n backoffMs: number;\n maxBackoffMs?: number;\n };\n}\n\n/**\n * Result of an integration action call\n */\nexport interface IntegrationResult<T = unknown> {\n /** Success flag */\n success: boolean;\n\n /** Response data (on success) */\n data?: T;\n\n /** Error (on failure) */\n error?: IntegrationError;\n\n /** Metadata (timing, retries, etc.) */\n metadata: {\n integration: string;\n action: string;\n duration: number;\n retries: number;\n timestamp: number;\n };\n}\n\n/**\n * Integration error codes\n */\nexport type IntegrationErrorCode =\n | 'VALIDATION_ERROR'\n | 'AUTH_ERROR'\n | 'RATE_LIMIT_ERROR'\n | 'TIMEOUT_ERROR'\n | 'NETWORK_ERROR'\n | 'SERVICE_ERROR'\n | 'UNKNOWN_ERROR';\n\n/**\n * Integration error\n */\nexport class IntegrationError extends Error {\n code: IntegrationErrorCode;\n integration?: string;\n action?: string;\n details?: unknown;\n\n constructor(\n message: string,\n code: IntegrationErrorCode = 'UNKNOWN_ERROR',\n details?: unknown,\n ) {\n super(message);\n this.name = 'IntegrationError';\n this.code = code;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n integration: this.integration,\n action: this.action,\n details: this.details,\n };\n }\n}\n\nimport type { LogMeta } from '@almadar/core';\n\n/** Re-export LogMeta from @almadar/core as the canonical log metadata type. */\nexport type { LogMeta };\n\n/**\n * Logger interface\n */\nexport interface IntegrationLogger {\n debug(message: string, meta?: LogMeta): void;\n info(message: string, meta?: LogMeta): void;\n warn(message: string, meta?: LogMeta): void;\n error(message: string, meta?: LogMeta): void;\n}\n\n/**\n * Integration action parameters.\n * Each integration's execute() method receives params as this type.\n * Individual methods cast to specific param shapes from their contracts.\n *\n * Per-key value union is widened to admit `@almadar/core`'s `FieldValue`\n * shape (entity / payload values flowing into call-service args): `Date`\n * for date fields, `IntegrationParams[]` for nested object arrays, and a\n * raw-value array catch-all so `string[]` / `number[]` / mixed payload\n * arrays satisfy the index signature without requiring `as unknown as`\n * casts at the call site. Adapters narrow these to their canonical input\n * types (typically JSON-string serialisation for `Date`).\n */\nexport type IntegrationParamValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | ReadonlyArray<IntegrationParamValue>\n | { readonly [key: string]: IntegrationParamValue };\n\nexport interface IntegrationParams {\n [key: string]: IntegrationParamValue;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n/**\n * Validation error\n */\nexport interface ValidationError {\n param: string;\n message: string;\n}\n","import { BaseIntegration } from '../core/BaseIntegration';\nimport type { IntegrationConfig, IntegrationResult, IntegrationParams } from '../types';\nimport { IntegrationError } from '../types';\n\n/**\n * Mock integration for testing\n */\nexport class MockIntegration extends BaseIntegration {\n private responses: Map<string, unknown> = new Map();\n private calls: Array<{ action: string; params: IntegrationParams }> =\n [];\n\n constructor(config: IntegrationConfig) {\n super(config);\n }\n\n /**\n * Set mock response for an action\n */\n setResponse(action: string, data: unknown): void {\n this.responses.set(action, data);\n }\n\n /**\n * Get all calls made to this integration\n */\n getCalls(): Array<{ action: string; params: IntegrationParams }> {\n return this.calls;\n }\n\n /**\n * Clear all calls\n */\n clearCalls(): void {\n this.calls = [];\n }\n\n async execute(\n action: string,\n params: IntegrationParams,\n ): Promise<IntegrationResult> {\n // Record the call\n this.calls.push({ action, params });\n\n const data = this.responses.get(action);\n\n if (!data) {\n return {\n success: false,\n error: new IntegrationError(\n `No mock response for action: ${action}`,\n 'UNKNOWN_ERROR',\n ),\n metadata: this.createMetadata(action, 0),\n };\n }\n\n return {\n success: true,\n data,\n metadata: this.createMetadata(action, 0),\n };\n }\n}\n","import type { IntegrationConfig } from './types';\nimport { BaseIntegration } from './core/BaseIntegration';\n\n/**\n * Integration constructor type\n */\nexport type IntegrationConstructor = new (\n config: IntegrationConfig,\n) => BaseIntegration;\n\n/**\n * Integration registry (populated as integrations are imported)\n */\nexport const INTEGRATION_REGISTRY: Record<string, IntegrationConstructor> = {};\n\n/**\n * Register an integration\n */\nexport function registerIntegration(\n name: string,\n constructor: IntegrationConstructor,\n): void {\n INTEGRATION_REGISTRY[name] = constructor;\n}\n\n/**\n * Get integration constructor by name\n */\nexport function getIntegration(\n name: string,\n): IntegrationConstructor | undefined {\n return INTEGRATION_REGISTRY[name];\n}\n\n/**\n * Check if integration is known\n */\nexport function isKnownIntegration(name: string): boolean {\n return name in INTEGRATION_REGISTRY;\n}\n\n/**\n * Get all registered integration names\n */\nexport function getRegisteredIntegrations(): string[] {\n return Object.keys(INTEGRATION_REGISTRY);\n}\n","import type { IntegrationConfig, IntegrationResult, IntegrationParams } from './types';\nimport { BaseIntegration } from './core/BaseIntegration';\nimport { getIntegration } from './registry';\n\n/**\n * Factory for creating and managing integration instances\n */\nexport class IntegrationFactory {\n private instances: Map<string, BaseIntegration> = new Map();\n private configs: Map<string, IntegrationConfig> = new Map();\n\n /**\n * Configure an integration (doesn't instantiate yet)\n */\n configure(name: string, config: Omit<IntegrationConfig, 'name'>): void {\n this.configs.set(name, { name, ...config });\n }\n\n /**\n * Get or create an integration instance\n */\n get(name: string): BaseIntegration {\n // Return existing instance\n if (this.instances.has(name)) {\n return this.instances.get(name)!;\n }\n\n // Get constructor\n const Constructor = getIntegration(name);\n if (!Constructor) {\n throw new Error(`Unknown integration: ${name}. Make sure it's imported.`);\n }\n\n // Get config\n const config = this.configs.get(name);\n if (!config) {\n throw new Error(\n `Integration not configured: ${name}. Call configure() first.`,\n );\n }\n\n // Create instance\n const instance = new Constructor(config);\n this.instances.set(name, instance);\n\n return instance;\n }\n\n /**\n * Execute an action on an integration\n */\n async execute(\n integration: string,\n action: string,\n params: IntegrationParams,\n ): Promise<IntegrationResult> {\n const instance = this.get(integration);\n return await instance.execute(action, params);\n }\n\n /**\n * Check if integration is configured\n */\n isConfigured(name: string): boolean {\n return this.configs.has(name);\n }\n\n /**\n * Register an integration instance directly (used by mock infrastructure)\n */\n registerInstance(name: string, instance: BaseIntegration): void {\n this.instances.set(name, instance);\n }\n\n /**\n * Clear all instances (useful for testing)\n */\n clear(): void {\n this.instances.clear();\n }\n\n /**\n * Clear all instances and configs\n */\n reset(): void {\n this.instances.clear();\n this.configs.clear();\n }\n}\n\nlet _factory: IntegrationFactory | null = null;\n\nexport function getIntegrationFactory(): IntegrationFactory {\n if (!_factory) {\n _factory = new IntegrationFactory();\n }\n return _factory;\n}\n\nexport function resetIntegrationFactory(): void {\n _factory?.reset();\n _factory = null;\n}\n","import { IntegrationFactory } from '../factory';\nimport { MockIntegration } from './MockIntegration';\nimport { registerIntegration } from '../registry';\nimport type { IntegrationParams } from '../types';\n\n/**\n * Mock integration factory for testing\n */\nexport class MockIntegrationFactory extends IntegrationFactory {\n constructor() {\n super();\n \n // Register mock integration for all known services\n const services = ['stripe', 'youtube', 'twilio', 'email', 'llm', 'deepagent'];\n services.forEach((service) => {\n registerIntegration(`mock-${service}`, MockIntegration);\n \n // Configure with mock config\n this.configure(service, {\n env: {},\n });\n });\n }\n\n /**\n * Set mock response for an integration action\n */\n setMockResponse(integration: string, action: string, data: unknown): void {\n const instance = this.get(integration) as MockIntegration;\n instance.setResponse(action, data);\n }\n\n /**\n * Get calls made to an integration\n */\n getMockCalls(\n integration: string,\n ): Array<{ action: string; params: IntegrationParams }> {\n const instance = this.get(integration) as MockIntegration;\n return instance.getCalls();\n }\n\n /**\n * Clear calls for an integration\n */\n clearMockCalls(integration: string): void {\n const instance = this.get(integration) as MockIntegration;\n instance.clearCalls();\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/core/logger.ts","../../src/core/validation.ts","../../src/core/retry.ts","../../src/core/BaseIntegration.ts","../../src/types.ts","../../src/mocks/MockIntegration.ts","../../src/registry.ts","../../src/factory.ts","../../src/mocks/MockIntegrationFactory.ts"],"names":[],"mappings":";;;;AAeO,IAAM,gBAAN,MAAiD;AAAA,EAGtD,WAAA,CAAY,SAA8C,MAAA,EAAQ;AAEhE,IAAA,IAAA,CAAK,GAAA,GAAM,aAAa,sBAAsB,CAAA;AAAA,EAChD;AAAA,EAEA,KAAA,CAAM,SAAiB,IAAA,EAAsB;AAC3C,IAAA,IAAA,CAAK,GAAA,CAAI,KAAA,CAAM,OAAA,EAAS,IAAI,CAAA;AAAA,EAC9B;AAAA,EACA,IAAA,CAAK,SAAiB,IAAA,EAAsB;AAC1C,IAAA,IAAA,CAAK,GAAA,CAAI,IAAA,CAAK,OAAA,EAAS,IAAI,CAAA;AAAA,EAC7B;AAAA,EACA,IAAA,CAAK,SAAiB,IAAA,EAAsB;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ogger, LogMeta } from '../types';\n\n/**\n * Console-based logger implementation.\n *\n * Routes through `@almadar/logger`'s shared gate so namespace filtering\n * (`ALMADAR_DEBUG`, `globalThis.__ALMADAR_DEBUG__`) and the production\n * level default (WARN+) apply uniformly with the rest of `@almadar/*`.\n *\n * The constructor's `level` argument is retained for backwards\n * compatibility but is now a no-op — the active level is owned by the\n * shared logger (compile-time + env). To filter integration logs at\n * runtime, set `globalThis.__ALMADAR_DEBUG__ = 'almadar:integrations:*'`.\n */\nexport class ConsoleLogger implements IntegrationLogger {\n private readonly log: Logger;\n\n constructor(_level: 'debug' | 'info' | 'warn' | 'error' = 'info') {\n void _level;\n this.log = createLogger('almadar:integrations');\n }\n\n debug(message: string, meta?: LogMeta): void {\n this.log.debug(message, meta);\n }\n info(message: string, meta?: LogMeta): void {\n this.log.info(message, meta);\n }\n warn(message: string, meta?: LogMeta): void {\n this.log.warn(message, meta);\n }\n error(message: string, meta?: LogMeta): void {\n this.log.error(message, meta);\n }\n}\n","import type { ValidationResult, ValidationError, IntegrationParams } from '../types';\n\n// Import integrators registry from the package main export (JSON is inlined in the bundle)\nimport { integratorsRegistry } from '@almadar/core/patterns';\n\ninterface ActionParam {\n name: string;\n type: string;\n required?: boolean;\n description?: string;\n}\n\ninterface ActionDef {\n name: string;\n description?: string;\n params: ActionParam[];\n}\n\ninterface IntegratorEntry {\n name: string;\n description?: string;\n category?: string;\n actions: ActionDef[];\n}\n\ntype IntegratorsRegistry = Record<string, {\n version?: string;\n exportedAt?: string;\n integrators: Record<string, IntegratorEntry>;\n}>;\n\n/**\n * Validate action params against registry schema\n */\nexport function validateParams(\n integration: string,\n action: string,\n params: IntegrationParams,\n): ValidationResult {\n const typedRegistry = integratorsRegistry as IntegratorsRegistry[string];\n const registry = typedRegistry.integrators[integration];\n\n if (!registry) {\n return {\n valid: false,\n errors: [\n {\n param: 'integration',\n message: `Unknown integration: ${integration}`,\n },\n ],\n };\n }\n\n const actionDef = registry.actions.find((a: ActionDef) => a.name === action);\n\n if (!actionDef) {\n return {\n valid: false,\n errors: [{ param: 'action', message: `Unknown action: ${action}` }],\n };\n }\n\n const errors: ValidationError[] = [];\n\n // Check required params\n for (const paramDef of actionDef.params) {\n if (paramDef.required && !(paramDef.name in params)) {\n errors.push({\n param: paramDef.name,\n message: `Missing required parameter: ${paramDef.name}`,\n });\n }\n\n // Type validation\n if (paramDef.name in params) {\n const value = params[paramDef.name];\n const expectedType = paramDef.type;\n const actualType = typeof value;\n\n if (expectedType === 'number' && actualType !== 'number') {\n errors.push({\n param: paramDef.name,\n message: `Expected ${expectedType}, got ${actualType}`,\n });\n }\n\n if (expectedType === 'string' && actualType !== 'string') {\n errors.push({\n param: paramDef.name,\n message: `Expected ${expectedType}, got ${actualType}`,\n });\n }\n\n if (expectedType === 'array' && !Array.isArray(value)) {\n errors.push({\n param: paramDef.name,\n message: `Expected array, got ${actualType}`,\n });\n }\n\n if (\n expectedType === 'object' &&\n (actualType !== 'object' || Array.isArray(value) || value === null)\n ) {\n errors.push({\n param: paramDef.name,\n message: `Expected object, got ${actualType}`,\n });\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors,\n };\n}\n","import type { IntegrationError, IntegrationErrorCode } from '../types';\n\n/**\n * Retry configuration\n */\nexport interface RetryConfig {\n maxAttempts: number;\n backoffMs: number;\n maxBackoffMs?: number;\n retryableErrors?: IntegrationErrorCode[];\n}\n\n/**\n * Execute a function with retry logic\n */\nexport async function withRetry<T>(\n fn: () => Promise<T>,\n config: RetryConfig,\n): Promise<T> {\n const {\n maxAttempts,\n backoffMs,\n maxBackoffMs = 30000,\n retryableErrors,\n } = config;\n\n let lastError: unknown;\n\n for (let attempt = 1; attempt <= maxAttempts; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error;\n\n // Check if error is retryable\n if (\n error &&\n typeof error === 'object' &&\n 'code' in error &&\n retryableErrors\n ) {\n const integrationError = error as IntegrationError;\n if (!retryableErrors.includes(integrationError.code)) {\n throw error;\n }\n }\n\n // Last attempt, throw\n if (attempt === maxAttempts) {\n throw error;\n }\n\n // Wait before retry (exponential backoff)\n const delay = Math.min(\n backoffMs * Math.pow(2, attempt - 1),\n maxBackoffMs,\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n\n throw lastError;\n}\n","import type {\n IntegrationConfig,\n IntegrationResult,\n IntegrationLogger,\n IntegrationError,\n IntegrationParams,\n} from '../types';\nimport { ConsoleLogger } from './logger';\nimport { validateParams } from './validation';\nimport { withRetry } from './retry';\n\n/**\n * Base class for all integrations\n */\nexport abstract class BaseIntegration {\n protected config: IntegrationConfig;\n protected logger: IntegrationLogger;\n\n constructor(config: IntegrationConfig) {\n this.config = config;\n this.logger = config.logger || new ConsoleLogger();\n }\n\n /**\n * Execute an action\n */\n abstract execute(\n action: string,\n params: IntegrationParams,\n ): Promise<IntegrationResult>;\n\n /**\n * Validate action params against registry\n */\n protected validateParams(\n action: string,\n params: IntegrationParams,\n ): ReturnType<typeof validateParams> {\n return validateParams(this.config.name, action, params);\n }\n\n /**\n * Handle errors uniformly\n */\n protected handleError(action: string, error: unknown): IntegrationResult {\n this.logger.error(`Integration error in ${this.config.name}.${action}`, {\n error: error instanceof Error ? error : new Error(String(error)),\n });\n\n const integrationError =\n error instanceof Error\n ? error\n : new Error(String(error));\n\n return {\n success: false,\n error: integrationError as IntegrationError,\n metadata: this.createMetadata(action, 0, 0),\n };\n }\n\n /**\n * Create metadata for result\n */\n protected createMetadata(\n action: string,\n duration: number,\n retries: number = 0,\n ): IntegrationResult['metadata'] {\n return {\n integration: this.config.name,\n action,\n duration,\n retries,\n timestamp: Date.now(),\n };\n }\n\n /**\n * Execute with retry logic\n */\n protected async executeWithRetry<T>(\n fn: () => Promise<T>,\n ): Promise<T> {\n if (!this.config.retry) {\n return fn();\n }\n\n return withRetry(fn, {\n maxAttempts: this.config.retry.maxAttempts,\n backoffMs: this.config.retry.backoffMs,\n maxBackoffMs: this.config.retry.maxBackoffMs,\n retryableErrors: [\n 'TIMEOUT_ERROR',\n 'NETWORK_ERROR',\n 'RATE_LIMIT_ERROR',\n ],\n });\n }\n}\n","/**\n * Core types for Almadar integrations\n */\n\n/**\n * Configuration for an integration instance\n */\nexport interface IntegrationConfig {\n /** Integration name (matches registry) */\n name: string;\n\n /** Environment variables (API keys, secrets) */\n env: Record<string, string>;\n\n /** Optional logger */\n logger?: IntegrationLogger;\n\n /** Optional rate limiting config */\n rateLimit?: {\n requestsPerSecond: number;\n burstSize: number;\n };\n\n /** Optional timeout (ms) */\n timeout?: number;\n\n /** Optional retry config */\n retry?: {\n maxAttempts: number;\n backoffMs: number;\n maxBackoffMs?: number;\n };\n}\n\n/**\n * Result of an integration action call\n */\nexport interface IntegrationResult<T = unknown> {\n /** Success flag */\n success: boolean;\n\n /** Response data (on success) */\n data?: T;\n\n /** Error (on failure) */\n error?: IntegrationError;\n\n /** Metadata (timing, retries, etc.) */\n metadata: {\n integration: string;\n action: string;\n duration: number;\n retries: number;\n timestamp: number;\n };\n}\n\n/**\n * Integration error codes\n */\nexport type IntegrationErrorCode =\n | 'VALIDATION_ERROR'\n | 'AUTH_ERROR'\n | 'RATE_LIMIT_ERROR'\n | 'TIMEOUT_ERROR'\n | 'NETWORK_ERROR'\n | 'SERVICE_ERROR'\n | 'UNKNOWN_ERROR';\n\n/**\n * Integration error\n */\nexport class IntegrationError extends Error {\n code: IntegrationErrorCode;\n integration?: string;\n action?: string;\n details?: unknown;\n\n constructor(\n message: string,\n code: IntegrationErrorCode = 'UNKNOWN_ERROR',\n details?: unknown,\n ) {\n super(message);\n this.name = 'IntegrationError';\n this.code = code;\n this.details = details;\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n integration: this.integration,\n action: this.action,\n details: this.details,\n };\n }\n}\n\nimport type { LogMeta } from '@almadar/core';\n\n/** Re-export LogMeta from @almadar/core as the canonical log metadata type. */\nexport type { LogMeta };\n\n/**\n * Logger interface\n */\nexport interface IntegrationLogger {\n debug(message: string, meta?: LogMeta): void;\n info(message: string, meta?: LogMeta): void;\n warn(message: string, meta?: LogMeta): void;\n error(message: string, meta?: LogMeta): void;\n}\n\n/**\n * Integration action parameters.\n * Each integration's execute() method receives params as this type.\n * Individual methods cast to specific param shapes from their contracts.\n *\n * Per-key value union is widened to admit `@almadar/core`'s `FieldValue`\n * shape (entity / payload values flowing into call-service args): `Date`\n * for date fields, `IntegrationParams[]` for nested object arrays, and a\n * raw-value array catch-all so `string[]` / `number[]` / mixed payload\n * arrays satisfy the index signature without requiring `as unknown as`\n * casts at the call site. Adapters narrow these to their canonical input\n * types (typically JSON-string serialisation for `Date`).\n */\nexport type IntegrationParamValue =\n | string\n | number\n | boolean\n | Date\n | null\n | undefined\n | ReadonlyArray<IntegrationParamValue>\n | { readonly [key: string]: IntegrationParamValue };\n\nexport interface IntegrationParams {\n [key: string]: IntegrationParamValue;\n}\n\n/**\n * Validation result\n */\nexport interface ValidationResult {\n valid: boolean;\n errors: ValidationError[];\n}\n\n/**\n * Validation error\n */\nexport interface ValidationError {\n param: string;\n message: string;\n}\n","import { BaseIntegration } from '../core/BaseIntegration';\nimport type { IntegrationConfig, IntegrationResult, IntegrationParams } from '../types';\nimport { IntegrationError } from '../types';\n\n/**\n * Mock integration for testing\n */\nexport class MockIntegration extends BaseIntegration {\n private responses: Map<string, unknown> = new Map();\n private calls: Array<{ action: string; params: IntegrationParams }> =\n [];\n\n constructor(config: IntegrationConfig) {\n super(config);\n }\n\n /**\n * Set mock response for an action\n */\n setResponse(action: string, data: unknown): void {\n this.responses.set(action, data);\n }\n\n /**\n * Get all calls made to this integration\n */\n getCalls(): Array<{ action: string; params: IntegrationParams }> {\n return this.calls;\n }\n\n /**\n * Clear all calls\n */\n clearCalls(): void {\n this.calls = [];\n }\n\n async execute(\n action: string,\n params: IntegrationParams,\n ): Promise<IntegrationResult> {\n // Record the call\n this.calls.push({ action, params });\n\n const data = this.responses.get(action);\n\n if (!data) {\n return {\n success: false,\n error: new IntegrationError(\n `No mock response for action: ${action}`,\n 'UNKNOWN_ERROR',\n ),\n metadata: this.createMetadata(action, 0),\n };\n }\n\n return {\n success: true,\n data,\n metadata: this.createMetadata(action, 0),\n };\n }\n}\n","import type { IntegrationConfig } from './types';\nimport { BaseIntegration } from './core/BaseIntegration';\n\n/**\n * Integration constructor type\n */\nexport type IntegrationConstructor = new (\n config: IntegrationConfig,\n) => BaseIntegration;\n\n/**\n * Integration registry (populated as integrations are imported)\n */\nexport const INTEGRATION_REGISTRY: Record<string, IntegrationConstructor> = {};\n\n/**\n * Register an integration\n */\nexport function registerIntegration(\n name: string,\n constructor: IntegrationConstructor,\n): void {\n INTEGRATION_REGISTRY[name] = constructor;\n}\n\n/**\n * Get integration constructor by name\n */\nexport function getIntegration(\n name: string,\n): IntegrationConstructor | undefined {\n return INTEGRATION_REGISTRY[name];\n}\n\n/**\n * Check if integration is known\n */\nexport function isKnownIntegration(name: string): boolean {\n return name in INTEGRATION_REGISTRY;\n}\n\n/**\n * Get all registered integration names\n */\nexport function getRegisteredIntegrations(): string[] {\n return Object.keys(INTEGRATION_REGISTRY);\n}\n","import type { IntegrationConfig, IntegrationResult, IntegrationParams } from './types';\nimport { BaseIntegration } from './core/BaseIntegration';\nimport { getIntegration } from './registry';\n\n/**\n * Optional per-call context for principal-scoped resolution (W4). The\n * default — absent — means the tenant/app-wide credential set; a `principal`\n * selects a per-principal configuration when one was registered. Additive:\n * every existing call site is untouched.\n */\nexport interface IntegrationCallContext {\n principal?: string;\n}\n\n/** Cache key for (name, principal?) — NUL never appears in either part. */\nfunction instanceKey(name: string, principal?: string): string {\n return principal ? `${name}\\u0000${principal}` : name;\n}\n\n/**\n * Factory for creating and managing integration instances\n */\nexport class IntegrationFactory {\n private instances: Map<string, BaseIntegration> = new Map();\n private configs: Map<string, IntegrationConfig> = new Map();\n\n /**\n * Configure an integration (doesn't instantiate yet). A `principal` scopes\n * the config to that principal; the app-wide config (no principal) is the\n * fallback for every principal.\n */\n configure(name: string, config: Omit<IntegrationConfig, 'name'>, principal?: string): void {\n this.configs.set(instanceKey(name, principal), { name, ...config });\n }\n\n /**\n * Get or create an integration instance. Principal-scoped lookups fall\n * back to the app-wide config when no per-principal config exists.\n */\n get(name: string, principal?: string): BaseIntegration {\n const key = instanceKey(name, principal);\n const cached = this.instances.get(key);\n if (cached) {\n return cached;\n }\n\n // Get constructor\n const Constructor = getIntegration(name);\n if (!Constructor) {\n throw new Error(`Unknown integration: ${name}. Make sure it's imported.`);\n }\n\n // Get config — per-principal first, app-wide fallback\n const config = this.configs.get(key) ?? this.configs.get(name);\n if (!config) {\n throw new Error(\n `Integration not configured: ${name}. Call configure() first.`,\n );\n }\n\n // Create instance\n const instance = new Constructor(config);\n this.instances.set(key, instance);\n\n return instance;\n }\n\n /**\n * Execute an action on an integration\n */\n async execute(\n integration: string,\n action: string,\n params: IntegrationParams,\n context?: IntegrationCallContext,\n ): Promise<IntegrationResult> {\n const instance = this.get(integration, context?.principal);\n return await instance.execute(action, params);\n }\n\n /**\n * Check if integration is configured\n */\n isConfigured(name: string, principal?: string): boolean {\n return this.configs.has(instanceKey(name, principal)) || this.configs.has(name);\n }\n\n /**\n * Register an integration instance directly (used by mock infrastructure)\n */\n registerInstance(name: string, instance: BaseIntegration, principal?: string): void {\n this.instances.set(instanceKey(name, principal), instance);\n }\n\n /**\n * Drop the cached instance(s) for a name so the next `get` rebuilds from\n * the current config — how a credential change goes live without restart.\n * Configs are kept; without a name, every instance is dropped.\n */\n invalidate(name?: string): void {\n if (name === undefined) {\n this.instances.clear();\n return;\n }\n for (const key of this.instances.keys()) {\n if (key === name || key.startsWith(`${name}\\u0000`)) {\n this.instances.delete(key);\n }\n }\n }\n\n /**\n * Clear all instances (useful for testing)\n */\n clear(): void {\n this.instances.clear();\n }\n\n /**\n * Clear all instances and configs\n */\n reset(): void {\n this.instances.clear();\n this.configs.clear();\n }\n}\n\nlet _factory: IntegrationFactory | null = null;\n\nexport function getIntegrationFactory(): IntegrationFactory {\n if (!_factory) {\n _factory = new IntegrationFactory();\n }\n return _factory;\n}\n\nexport function resetIntegrationFactory(): void {\n _factory?.reset();\n _factory = null;\n}\n","import { IntegrationFactory } from '../factory';\nimport { MockIntegration } from './MockIntegration';\nimport { registerIntegration } from '../registry';\nimport type { IntegrationParams } from '../types';\n\n/**\n * Mock integration factory for testing\n */\nexport class MockIntegrationFactory extends IntegrationFactory {\n constructor() {\n super();\n \n // Register mock integration for all known services\n const services = ['stripe', 'youtube', 'twilio', 'email', 'llm', 'deepagent'];\n services.forEach((service) => {\n registerIntegration(`mock-${service}`, MockIntegration);\n \n // Configure with mock config\n this.configure(service, {\n env: {},\n });\n });\n }\n\n /**\n * Set mock response for an integration action\n */\n setMockResponse(integration: string, action: string, data: unknown): void {\n const instance = this.get(integration) as MockIntegration;\n instance.setResponse(action, data);\n }\n\n /**\n * Get calls made to an integration\n */\n getMockCalls(\n integration: string,\n ): Array<{ action: string; params: IntegrationParams }> {\n const instance = this.get(integration) as MockIntegration;\n return instance.getCalls();\n }\n\n /**\n * Clear calls for an integration\n */\n clearMockCalls(integration: string): void {\n const instance = this.get(integration) as MockIntegration;\n instance.clearCalls();\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
- import { I as IntegrationFactory } from '../factory-DTdVeyAi.js';
1
+ import { I as IntegrationCallContext, a as IntegrationFactory } from '../factory-BPVhvv5q.js';
2
2
  import { e as IntegrationParams } from '../BaseIntegration-MA-b4fh8.js';
3
- import { j as IntegrationName, h as IntegrationActionName, i as IntegrationContracts } from '../contracts-CLTh6gjT.js';
3
+ import { o as IntegrationName, m as IntegrationActionName, n as IntegrationContracts, e as CredentialStore } from '../store-CW1v7Apc.js';
4
4
  import '@almadar/core';
5
5
 
6
6
  /**
@@ -21,10 +21,10 @@ import '@almadar/core';
21
21
  interface CallServiceHandler {
22
22
  <S extends IntegrationName, A extends IntegrationActionName<S>>(service: S, action: A, params: IntegrationContracts[S][A] extends {
23
23
  params: infer P;
24
- } ? P : IntegrationParams | undefined): Promise<IntegrationContracts[S][A] extends {
24
+ } ? P : IntegrationParams | undefined, context?: IntegrationCallContext): Promise<IntegrationContracts[S][A] extends {
25
25
  result: infer R;
26
26
  } ? R : unknown>;
27
- (service: string, action: string, params: IntegrationParams | undefined): Promise<unknown>;
27
+ (service: string, action: string, params: IntegrationParams | undefined, context?: IntegrationCallContext): Promise<unknown>;
28
28
  }
29
29
  /**
30
30
  * Create a callService effect handler for @almadar/runtime.
@@ -48,7 +48,20 @@ declare function createCallServiceHandler(factory: IntegrationFactory): CallServ
48
48
  */
49
49
  declare class RuntimeIntegrationManager {
50
50
  private factory;
51
+ private credentialStore;
52
+ private storeEnvBase;
51
53
  constructor();
54
+ /**
55
+ * W4: configure with the tenant credential store layered over the env —
56
+ * store → env → unconfigured. Installs the store as the process-wide
57
+ * `resolveCredentialRef` source, warms it, and re-configures whenever a
58
+ * credential changes (dropping cached instances so new keys go live
59
+ * without a restart). Mock mode short-circuits inside `configureFromEnv`
60
+ * exactly as before, so verify harnesses are unaffected.
61
+ */
62
+ configureFromStore(store: CredentialStore, envOverride?: Record<string, string | undefined>): Promise<void>;
63
+ /** Re-derive configs from base env + warmed store values; drop stale instances. */
64
+ private refreshFromStore;
52
65
  /**
53
66
  * Wrap `factory.execute` so an unknown/unconfigured service echoes its
54
67
  * params instead of throwing. This makes the manager safe to install as a
@@ -58,13 +71,19 @@ declare class RuntimeIntegrationManager {
58
71
  * events fire — only the two "not set up" errors (`Unknown integration`,
59
72
  * `Integration not configured`) are caught. Subsumes the broader wrapper
60
73
  * that previously lived inside `configureMockMode`.
74
+ *
75
+ * In production the fallback is OFF: a missing key must surface as the
76
+ * circuit's failure event and a degraded health check, never a fake success.
61
77
  */
62
78
  private installNotConfiguredFallback;
63
79
  /**
64
80
  * Configure from environment variables.
65
81
  * In mock mode (USE_MOCK_DATA=true), all services return realistic mock data.
82
+ *
83
+ * Pass an explicit env map to configure hermetically (verify harnesses,
84
+ * per-tenant resolution); defaults to `process.env`.
66
85
  */
67
- configureFromEnv(): void;
86
+ configureFromEnv(envOverride?: Record<string, string | undefined>): void;
68
87
  /**
69
88
  * Configure mock mode: register MockIntegration for all known services
70
89
  * with auto-generated responses from the services registry.