@semiont/make-meaning 0.2.35-build.99 → 0.2.36

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.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/service.ts","../src/jobs/reference-annotation-worker.ts","../src/detection/entity-extractor.ts","../src/jobs/generation-worker.ts","../src/generation/resource-generation.ts","../src/id-generation.ts","../src/jobs/highlight-annotation-worker.ts","../src/jobs/assessment-annotation-worker.ts","../src/jobs/comment-annotation-worker.ts","../src/jobs/tag-annotation-worker.ts","../../../node_modules/rxjs/node_modules/tslib/tslib.es6.js","../../../node_modules/rxjs/src/internal/util/isFunction.ts","../../../node_modules/rxjs/src/internal/config.ts","../../../node_modules/rxjs/src/internal/util/hostReportError.ts","../../../node_modules/rxjs/src/internal/Observer.ts","../../../node_modules/rxjs/src/internal/util/isObject.ts","../../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../../node_modules/rxjs/src/internal/Subscription.ts","../../../node_modules/rxjs/src/internal/symbol/rxSubscriber.ts","../../../node_modules/rxjs/src/internal/Subscriber.ts","../../../node_modules/rxjs/src/internal/util/canReportError.ts","../../../node_modules/rxjs/src/internal/util/toSubscriber.ts","../../../node_modules/rxjs/src/internal/util/identity.ts","../../../node_modules/rxjs/src/internal/util/pipe.ts","../../../node_modules/rxjs/src/internal/Observable.ts","../../../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts","../../../node_modules/rxjs/src/internal/SubjectSubscription.ts","../../../node_modules/rxjs/src/internal/Subject.ts","../../../node_modules/rxjs/src/internal/operators/groupBy.ts","../../../node_modules/rxjs/src/internal/util/subscribeToArray.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../../node_modules/rxjs/src/internal/operators/map.ts","../../../node_modules/rxjs/src/internal/util/subscribeToPromise.ts","../../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../../node_modules/rxjs/src/internal/util/subscribeToIterable.ts","../../../node_modules/rxjs/src/internal/util/subscribeToObservable.ts","../../../node_modules/rxjs/src/internal/util/isPromise.ts","../../../node_modules/rxjs/src/internal/util/subscribeTo.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../../node_modules/rxjs/src/internal/util/isIterable.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../../node_modules/rxjs/src/internal/observable/from.ts","../../../node_modules/rxjs/src/internal/innerSubscribe.ts","../../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../../node_modules/rxjs/src/internal/operators/concatMap.ts","../src/graph/consumer.ts","../src/bootstrap/entity-types.ts","../src/views/entity-types-reader.ts","../src/resource-operations.ts","../src/annotation-operations.ts","../src/annotation-context.ts","../src/resource-context.ts","../src/graph-context.ts","../src/llm-context.ts","../src/annotation-assistance.ts","../src/detection/motivation-prompts.ts","../src/detection/motivation-parsers.ts","../src/index.ts"],"sourcesContent":["/**\n * Make-Meaning Service\n *\n * Consolidates all meaning-making infrastructure:\n * - Job queue initialization\n * - Worker instantiation and startup\n * - Graph consumer (event-to-graph synchronization)\n *\n * Provides a clean interface similar to createEventStore():\n * const makeMeaning = await startMakeMeaning(config);\n */\n\nimport * as path from 'path';\nimport { JobQueue } from '@semiont/jobs';\nimport { createEventStore as createEventStoreCore, type EventStore } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore, type RepresentationStore } from '@semiont/content';\nimport type { EnvironmentConfig, Logger } from '@semiont/core';\nimport { EventBus } from '@semiont/core';\nimport { getInferenceClient, type InferenceClient } from '@semiont/inference';\nimport { getGraphDatabase, type GraphDatabase } from '@semiont/graph';\nimport { ReferenceAnnotationWorker } from './jobs/reference-annotation-worker';\nimport { GenerationWorker } from './jobs/generation-worker';\nimport { HighlightAnnotationWorker } from './jobs/highlight-annotation-worker';\nimport { AssessmentAnnotationWorker } from './jobs/assessment-annotation-worker';\nimport { CommentAnnotationWorker } from './jobs/comment-annotation-worker';\nimport { TagAnnotationWorker } from './jobs/tag-annotation-worker';\nimport { GraphDBConsumer } from './graph/consumer';\nimport { bootstrapEntityTypes } from './bootstrap/entity-types';\n\nexport interface MakeMeaningService {\n jobQueue: JobQueue;\n eventStore: EventStore;\n eventBus: EventBus;\n repStore: RepresentationStore;\n inferenceClient: InferenceClient;\n graphDb: GraphDatabase;\n workers: {\n detection: ReferenceAnnotationWorker;\n generation: GenerationWorker;\n highlight: HighlightAnnotationWorker;\n assessment: AssessmentAnnotationWorker;\n comment: CommentAnnotationWorker;\n tag: TagAnnotationWorker;\n };\n graphConsumer: GraphDBConsumer;\n stop: () => Promise<void>;\n}\n\nexport async function startMakeMeaning(config: EnvironmentConfig, eventBus: EventBus, logger: Logger): Promise<MakeMeaningService> {\n // 1. Validate configuration\n const configuredPath = config.services?.filesystem?.path;\n if (!configuredPath) {\n throw new Error('services.filesystem.path is required for make-meaning service');\n }\n\n const baseUrl = config.services?.backend?.publicURL;\n if (!baseUrl) {\n throw new Error('services.backend.publicURL is required for make-meaning service');\n }\n\n // Resolve basePath to absolute path\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n // 2. Initialize job queue\n const jobQueueLogger = logger.child({ component: 'job-queue' });\n const jobQueue = new JobQueue({ dataDir: basePath }, jobQueueLogger, eventBus);\n await jobQueue.initialize();\n\n // 3. Create shared event store with EventBus integration\n const eventStoreLogger = logger.child({ component: 'event-store' });\n const eventStore = createEventStoreCore(basePath, baseUrl, undefined, eventBus, eventStoreLogger);\n\n // 4. Bootstrap entity types (if projection doesn't exist)\n const bootstrapLogger = logger.child({ component: 'entity-types-bootstrap' });\n await bootstrapEntityTypes(eventStore, config, bootstrapLogger);\n\n // 5. Create shared representation store\n const repStoreLogger = logger.child({ component: 'representation-store' });\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot, repStoreLogger);\n\n // 6. Create inference client (shared across all workers)\n const inferenceLogger = logger.child({ component: 'inference-client' });\n const inferenceClient = await getInferenceClient(config, inferenceLogger);\n\n // 7. Create graph database connection\n const graphDb = await getGraphDatabase(config);\n\n // 8. Create child loggers for each component\n const detectionLogger = logger.child({ component: 'reference-detection-worker' });\n const generationLogger = logger.child({ component: 'generation-worker' });\n const highlightLogger = logger.child({ component: 'highlight-detection-worker' });\n const assessmentLogger = logger.child({ component: 'assessment-detection-worker' });\n const commentLogger = logger.child({ component: 'comment-detection-worker' });\n const tagLogger = logger.child({ component: 'tag-detection-worker' });\n const graphConsumerLogger = logger.child({ component: 'graph-consumer' });\n\n // 9. Start graph consumer\n const graphConsumer = new GraphDBConsumer(config, eventStore, graphDb, graphConsumerLogger);\n await graphConsumer.initialize();\n\n // 10. Instantiate workers with EventBus and logger\n const workers = {\n detection: new ReferenceAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, detectionLogger),\n generation: new GenerationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, generationLogger),\n highlight: new HighlightAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, highlightLogger),\n assessment: new AssessmentAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, assessmentLogger),\n comment: new CommentAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, commentLogger),\n tag: new TagAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, tagLogger),\n };\n\n // 11. Start all workers (non-blocking)\n workers.detection.start().catch((error: unknown) => {\n detectionLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.generation.start().catch((error: unknown) => {\n generationLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.highlight.start().catch((error: unknown) => {\n highlightLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.assessment.start().catch((error: unknown) => {\n assessmentLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.comment.start().catch((error: unknown) => {\n commentLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.tag.start().catch((error: unknown) => {\n tagLogger.error('Worker stopped unexpectedly', { error });\n });\n\n return {\n jobQueue,\n eventStore,\n eventBus,\n repStore,\n inferenceClient,\n graphDb,\n workers,\n graphConsumer,\n stop: async () => {\n logger.info('Stopping Make-Meaning service');\n await Promise.all([\n workers.detection.stop(),\n workers.generation.stop(),\n workers.highlight.stop(),\n workers.assessment.stop(),\n workers.comment.stop(),\n workers.tag.stop(),\n ]);\n await graphConsumer.stop();\n await graphDb.disconnect();\n logger.info('Make-Meaning service stopped');\n },\n };\n}\n","/**\n * Reference Detection Worker\n *\n * Processes detection jobs: runs AI inference to find entities in resources\n * and emits reference.created events for each detected entity.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, DetectionJob, JobQueue, RunningJob, DetectionParams, DetectionProgress, DetectionResult } from '@semiont/jobs';\nimport { ResourceContext } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus } from '@semiont/core';\nimport type { EnvironmentConfig, Logger, components } from '@semiont/core';\nimport { getPrimaryRepresentation, decodeRepresentation, validateAndCorrectOffsets } from '@semiont/api-client';\nimport { extractEntities } from '../detection/entity-extractor';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport type { InferenceClient } from '@semiont/inference';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface DetectedAnnotation {\n annotation: {\n selector: {\n start: number;\n end: number;\n exact: string;\n prefix?: string;\n suffix?: string;\n };\n entityTypes: string[];\n };\n}\n\nexport class ReferenceAnnotationWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'ReferenceAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'reference-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<DetectionResult> {\n if (job.metadata.type !== 'reference-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n return await this.processDetectionJob(job as RunningJob<DetectionParams, DetectionProgress>);\n }\n\n /**\n * Detect entity references in resource using AI\n * Self-contained implementation for reference detection\n *\n * Public for testing charset handling - see entity-detection-charset.test.ts\n */\n public async detectReferences(\n resource: ResourceDescriptor,\n entityTypes: string[],\n includeDescriptiveReferences: boolean = false\n ): Promise<DetectedAnnotation[]> {\n this.logger?.debug('Detecting entities', {\n resourceId: resource.id,\n entityTypes,\n includeDescriptiveReferences\n });\n\n const detectedAnnotations: DetectedAnnotation[] = [];\n\n // Get primary representation\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return detectedAnnotations;\n\n // Only process text content (check base media type, ignoring charset parameters)\n const mediaType = primaryRep.mediaType;\n const baseMediaType = mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType === 'text/plain' || baseMediaType === 'text/markdown') {\n // Load content from representation store using content-addressed lookup\n if (!primaryRep.checksum || !primaryRep.mediaType) return detectedAnnotations;\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const content = decodeRepresentation(contentBuffer, primaryRep.mediaType);\n\n // Use AI to extract entities (with optional anaphoric/cataphoric references)\n const extractedEntities = await extractEntities(content, entityTypes, this.inferenceClient, includeDescriptiveReferences, this.logger);\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n for (const entity of extractedEntities) {\n try {\n const validated = validateAndCorrectOffsets(\n content,\n entity.startOffset,\n entity.endOffset,\n entity.exact\n );\n\n const annotation: DetectedAnnotation = {\n annotation: {\n selector: {\n start: validated.start,\n end: validated.end,\n exact: validated.exact,\n prefix: validated.prefix,\n suffix: validated.suffix,\n },\n entityTypes: [entity.entityType],\n },\n };\n detectedAnnotations.push(annotation);\n } catch (error) {\n this.logger?.warn('Skipping invalid entity', { exact: entity.exact, error });\n // Skip this entity - AI hallucinated text that doesn't exist\n }\n }\n }\n\n return detectedAnnotations;\n }\n\n private async processDetectionJob(job: RunningJob<DetectionParams, DetectionProgress>): Promise<DetectionResult> {\n this.logger?.info('Processing detection job', { resourceId: job.params.resourceId, jobId: job.metadata.id });\n this.logger?.debug('Entity types to detect', { entityTypes: job.params.entityTypes });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n let totalFound = 0;\n let totalEmitted = 0;\n let totalErrors = 0;\n\n // Create updated job with initial progress\n let updatedJob: RunningJob<DetectionParams, DetectionProgress> = {\n ...job,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: 0,\n entitiesFound: 0,\n entitiesEmitted: 0\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each entity type\n for (let i = 0; i < job.params.entityTypes.length; i++) {\n const entityType = job.params.entityTypes[i];\n\n if (!entityType) continue;\n\n this.logger?.info('Detecting entity type', {\n entityType,\n progress: `${i + 1}/${job.params.entityTypes.length}`\n });\n\n // Emit progress BEFORE inference call for immediate user feedback\n updatedJob = {\n ...updatedJob,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: i,\n currentEntityType: entityType,\n entitiesFound: totalFound,\n entitiesEmitted: totalEmitted\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Detect entities using AI (loads content from filesystem internally)\n // This is where the latency is - user now has feedback that work started\n const detectedAnnotations = await this.detectReferences(resource, [entityType], job.params.includeDescriptiveReferences);\n\n totalFound += detectedAnnotations.length;\n this.logger?.info('Found entities', { entityType, count: detectedAnnotations.length });\n\n // Emit events for each detected entity\n // This happens INDEPENDENT of any HTTP client!\n for (let idx = 0; idx < detectedAnnotations.length; idx++) {\n const detected = detectedAnnotations[idx];\n\n if (!detected) {\n this.logger?.warn('Skipping undefined entity', { index: idx });\n continue;\n }\n\n let referenceId: string;\n try {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n referenceId = generateAnnotationId(backendUrl);\n } catch (error) {\n this.logger?.error('Failed to generate annotation ID', { error });\n throw new Error('Configuration error: Backend publicURL not set');\n }\n\n try {\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotation: {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n id: referenceId,\n motivation: 'linking' as const,\n target: {\n source: resourceIdToURI(job.params.resourceId, this.config.services.backend!.publicURL), // Convert to full URI\n selector: [\n {\n type: 'TextPositionSelector',\n start: detected.annotation.selector.start,\n end: detected.annotation.selector.end,\n },\n {\n type: 'TextQuoteSelector',\n exact: detected.annotation.selector.exact,\n ...(detected.annotation.selector.prefix && { prefix: detected.annotation.selector.prefix }),\n ...(detected.annotation.selector.suffix && { suffix: detected.annotation.selector.suffix }),\n },\n ],\n },\n body: (detected.annotation.entityTypes || []).map(et => ({\n type: 'TextualBody' as const,\n value: et,\n purpose: 'tagging' as const,\n })),\n modified: new Date().toISOString(),\n },\n },\n });\n\n totalEmitted++;\n\n if ((idx + 1) % 10 === 0 || idx === detectedAnnotations.length - 1) {\n this.logger?.debug('Emitted events for entity type', {\n entityType,\n emitted: idx + 1,\n total: detectedAnnotations.length\n });\n }\n\n } catch (error) {\n totalErrors++;\n this.logger?.error('Failed to emit event', { referenceId, error });\n // Continue processing other entities even if one fails\n }\n }\n\n this.logger?.info('Completed entity type processing', {\n entityType,\n found: detectedAnnotations.length,\n emitted: detectedAnnotations.length - (totalErrors - (totalFound - totalEmitted))\n });\n\n // Update progress after processing this entity type\n updatedJob = {\n ...updatedJob,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: i + 1,\n currentEntityType: entityType,\n entitiesFound: totalFound,\n entitiesEmitted: totalEmitted\n }\n };\n await this.updateJobProgress(updatedJob);\n }\n\n this.logger?.info('Detection complete', { totalFound, totalEmitted, totalErrors });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n totalFound,\n totalEmitted,\n errors: totalErrors\n };\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event (domain + progress)\n */\n protected override async emitCompletionEvent(\n job: RunningJob<DetectionParams, DetectionProgress>,\n result: DetectionResult\n ): Promise<void> {\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'reference-annotation',\n result,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(job.params.resourceId);\n this.logger?.debug('[EventBus] Emitting job:completed to resource-scoped bus', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n resourceBus.get('job:completed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.completed' }>);\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'reference-annotation') {\n // Type narrowing: job is FailedJob<DetectionParams>\n const detJob = job as DetectionJob;\n\n const errorMessage = 'Entity detection failed. Please try again later.';\n\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n error: errorMessage,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(detJob.params.resourceId);\n this.logger?.debug('[EventBus] Emitting job:failed to resource-scoped bus', {\n resourceId: detJob.params.resourceId,\n jobId: detJob.metadata.id\n });\n resourceBus.get('job:failed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.failed' }>);\n }\n }\n\n /**\n * Update job progress and emit events to Event Store and EventBus\n * Overrides base class to emit both domain events and progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for detection jobs\n if (job.metadata.type !== 'reference-annotation') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const detJob = job as RunningJob<DetectionParams, DetectionProgress>;\n\n const baseEvent = {\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n };\n\n // Determine update type based on progress state\n const isFirstUpdate = detJob.progress.processedEntityTypes === 0 && !detJob.progress.currentEntityType;\n\n // \"Before processing\" updates are emitted when we're about to START an entity type\n // They have processedEntityTypes < totalEntityTypes (not done yet) and currentEntityType set\n // The key distinction: if the currentEntityType matches the NEXT entity to process (not yet in processed count),\n // then this is a \"before\" update that should only emit ephemeral progress, not a domain event\n const currentIndex = detJob.progress.currentEntityType\n ? detJob.params.entityTypes.findIndex(et => et === detJob.progress.currentEntityType)\n : -1;\n const isBeforeProcessing = currentIndex !== -1 && detJob.progress.processedEntityTypes === currentIndex;\n\n // Get resource-scoped EventBus for progress events\n const resourceBus = this.eventBus.scope(detJob.params.resourceId);\n this.logger?.debug('[EventBus] Scoping to resourceId', { resourceId: detJob.params.resourceId });\n\n if (isFirstUpdate) {\n // First progress update - emit job.started (domain event)\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n totalSteps: detJob.params.entityTypes.length,\n },\n });\n\n // ALSO emit initial annotate:progress for immediate frontend feedback\n this.logger?.debug('[EventBus] Emitting initial annotate:progress', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType\n });\n resourceBus.get('annotate:progress').next({\n status: 'started',\n message: detJob.progress.currentEntityType\n ? `Starting ${detJob.progress.currentEntityType}...`\n : 'Starting detection...',\n currentEntityType: detJob.progress.currentEntityType,\n percentage: 0,\n });\n } else if (isBeforeProcessing) {\n // Before processing an entity type - only emit ephemeral annotate:progress (no domain event)\n // This provides immediate UX feedback that we're starting work on this entity type\n const percentage = 0; // Starting this entity type\n this.logger?.debug('[EventBus] Emitting annotate:progress (before processing)', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType\n });\n resourceBus.get('annotate:progress').next({\n status: 'scanning',\n message: `Starting ${detJob.progress.currentEntityType}...`,\n currentEntityType: detJob.progress.currentEntityType,\n percentage,\n });\n } else {\n // After processing an entity type - emit job.progress (domain event)\n const percentage = Math.round((detJob.progress.processedEntityTypes / detJob.progress.totalEntityTypes) * 100);\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n percentage,\n currentStep: detJob.progress.currentEntityType,\n processedSteps: detJob.progress.processedEntityTypes,\n totalSteps: detJob.progress.totalEntityTypes,\n foundCount: detJob.progress.entitiesFound,\n },\n });\n\n // PROGRESS EVENT: Emit annotate:progress directly to EventBus (ephemeral)\n this.logger?.debug('[EventBus] Emitting annotate:progress', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType,\n percentage\n });\n resourceBus.get('annotate:progress').next({\n status: 'scanning',\n message: `Processing ${detJob.progress.currentEntityType}`,\n currentEntityType: detJob.progress.currentEntityType,\n percentage,\n });\n }\n }\n}\n","import type { InferenceClient } from '@semiont/inference';\nimport type { Logger } from '@semiont/core';\n\n/**\n * Entity reference extracted from text\n */\nexport interface ExtractedEntity {\n exact: string; // The actual text span\n entityType: string; // The detected entity type\n startOffset: number; // Character offset where entity starts\n endOffset: number; // Character offset where entity ends\n prefix?: string; // Text immediately before entity (for disambiguation)\n suffix?: string; // Text immediately after entity (for disambiguation)\n}\n\n/**\n * Extract entity references from text using AI\n *\n * @param text - The text to analyze\n * @param entityTypes - Array of entity types to detect (optionally with examples)\n * @param client - Inference client for AI operations\n * @param includeDescriptiveReferences - Include anaphoric/cataphoric references (default: false)\n * @param logger - Optional logger for debugging entity extraction\n * @returns Array of extracted entities with their character offsets\n */\nexport async function extractEntities(\n exact: string,\n entityTypes: string[] | { type: string; examples?: string[] }[],\n client: InferenceClient,\n includeDescriptiveReferences: boolean = false,\n logger?: Logger\n): Promise<ExtractedEntity[]> {\n\n // Format entity types for the prompt\n const entityTypesDescription = entityTypes.map(et => {\n if (typeof et === 'string') {\n return et;\n }\n return et.examples && et.examples.length > 0\n ? `${et.type} (examples: ${et.examples.slice(0, 3).join(', ')})`\n : et.type;\n }).join(', ');\n\n // Build prompt with optional support for anaphoric/cataphoric references\n // Anaphora: references that point backward (e.g., \"John arrived. He was tired.\")\n // Cataphora: references that point forward (e.g., \"When she arrived, Mary was surprised.\")\n // When enabled, include substantive descriptive references beyond simple pronouns\n const descriptiveReferenceGuidance = includeDescriptiveReferences\n ? `\nInclude both:\n- Direct mentions (names, proper nouns)\n- Descriptive references (substantive phrases that refer to entities)\n\nFor descriptive references, include:\n- Definite descriptions: \"the Nobel laureate\", \"the tech giant\", \"the former president\"\n- Role-based references: \"the CEO\", \"the physicist\", \"the author\", \"the owner\", \"the contractor\"\n- Epithets with context: \"the Cupertino-based company\", \"the iPhone maker\"\n- References to entities even when identity is unknown or unspecified\n\nDo NOT include:\n- Simple pronouns alone: he, she, it, they, him, her, them\n- Generic determiners alone: this, that, these, those\n- Possessives without substance: his, her, their, its\n\nExamples:\n- For \"Marie Curie\", include \"the Nobel laureate\" and \"the physicist\" but NOT \"she\"\n- For an unknown person, include \"the owner\" or \"the contractor\" (role-based references count even when identity is unspecified)\n`\n : `\nFind direct mentions only (names, proper nouns). Do not include pronouns or descriptive references.\n`;\n\n const prompt = `Identify entity references in the following text. Look for mentions of: ${entityTypesDescription}.\n${descriptiveReferenceGuidance}\nText to analyze:\n\"\"\"\n${exact}\n\"\"\"\n\nReturn ONLY a JSON array of entities found. Each entity should have:\n- exact: the exact text span from the input\n- entityType: one of the provided entity types\n- startOffset: character position where the entity starts (0-indexed)\n- endOffset: character position where the entity ends\n- prefix: up to 32 characters of text immediately before the entity (helps identify correct occurrence)\n- suffix: up to 32 characters of text immediately after the entity (helps identify correct occurrence)\n\nReturn empty array [] if no entities found.\nDo not include markdown formatting or code fences, just the raw JSON array.\n\nExample output:\n[{\"exact\":\"Alice\",\"entityType\":\"Person\",\"startOffset\":0,\"endOffset\":5,\"prefix\":\"\",\"suffix\":\" went to\"},{\"exact\":\"Paris\",\"entityType\":\"Location\",\"startOffset\":20,\"endOffset\":25,\"prefix\":\"went to \",\"suffix\":\" yesterday\"}]`;\n\n logger?.debug('Sending entity extraction request', { entityTypes: entityTypesDescription });\n const response = await client.generateTextWithMetadata(\n prompt,\n 4000, // Increased to handle many entities without truncation\n 0.3 // Lower temperature for more consistent extraction\n );\n logger?.debug('Got entity extraction response', { responseLength: response.text.length });\n\n try {\n // Clean up response if wrapped in markdown\n let jsonStr = response.text.trim();\n if (jsonStr.startsWith('```')) {\n jsonStr = jsonStr.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const entities = JSON.parse(jsonStr);\n logger?.debug('Parsed entities from AI response', { count: entities.length });\n\n // Check if response was truncated - this is an ERROR condition\n if (response.stopReason === 'max_tokens') {\n const errorMsg = `AI response truncated: Found ${entities.length} entities but response hit max_tokens limit. Increase max_tokens or reduce resource size.`;\n logger?.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n // Validate and fix offsets\n return entities.map((entity: any, idx: number) => {\n let startOffset = entity.startOffset;\n let endOffset = entity.endOffset;\n\n logger?.debug('Processing entity', {\n index: idx + 1,\n total: entities.length,\n type: entity.entityType,\n text: entity.exact,\n offsetsFromAI: `[${startOffset}:${endOffset}]`\n });\n\n // Verify the offsets are correct by checking if the text matches\n const extractedText = exact.substring(startOffset, endOffset);\n\n // If the extracted text doesn't match, find the correct position using context\n if (extractedText !== entity.exact) {\n logger?.warn('Offset mismatch detected', {\n expected: entity.exact,\n foundAtOffsets: `[${startOffset}:${endOffset}]`,\n foundText: extractedText\n });\n\n // Show context around the AI-provided offset\n const contextStart = Math.max(0, startOffset - 50);\n const contextEnd = Math.min(exact.length, endOffset + 50);\n const contextBefore = exact.substring(contextStart, startOffset);\n const contextAfter = exact.substring(endOffset, contextEnd);\n logger?.debug('Context around AI offset', {\n before: contextBefore,\n extracted: extractedText,\n after: contextAfter\n });\n\n logger?.debug('Searching for exact match in resource');\n\n // Try to find using prefix/suffix context if provided\n let found = false;\n if (entity.prefix || entity.suffix) {\n logger?.debug('Using LLM-provided context for disambiguation', {\n prefix: entity.prefix,\n suffix: entity.suffix\n });\n\n // Search for all occurrences and find the one with matching context\n let searchPos = 0;\n while ((searchPos = exact.indexOf(entity.exact, searchPos)) !== -1) {\n const candidatePrefix = exact.substring(Math.max(0, searchPos - 32), searchPos);\n const candidateSuffix = exact.substring(\n searchPos + entity.exact.length,\n Math.min(exact.length, searchPos + entity.exact.length + 32)\n );\n\n // Check if context matches (allowing for partial matches at boundaries)\n const prefixMatch = !entity.prefix || candidatePrefix.endsWith(entity.prefix);\n const suffixMatch = !entity.suffix || candidateSuffix.startsWith(entity.suffix);\n\n if (prefixMatch && suffixMatch) {\n logger?.debug('Found match using context', {\n offset: searchPos,\n offsetDiff: searchPos - startOffset,\n candidatePrefix,\n candidateSuffix\n });\n startOffset = searchPos;\n endOffset = searchPos + entity.exact.length;\n found = true;\n break;\n }\n\n searchPos++;\n }\n\n if (!found) {\n logger?.warn('No occurrence found with matching context', { text: entity.exact });\n }\n }\n\n // Fallback to first occurrence if context didn't help\n if (!found) {\n const index = exact.indexOf(entity.exact);\n if (index !== -1) {\n logger?.warn('Using first occurrence', {\n text: entity.exact,\n offset: index,\n offsetDiff: index - startOffset\n });\n startOffset = index;\n endOffset = index + entity.exact.length;\n } else {\n logger?.error('Cannot find entity anywhere in resource', {\n text: entity.exact,\n resourceStart: exact.substring(0, 200)\n });\n // If we still can't find it, skip this entity\n return null;\n }\n }\n } else {\n logger?.debug('Offsets correct', { text: entity.exact });\n }\n\n return {\n exact: entity.exact,\n entityType: entity.entityType,\n startOffset: startOffset,\n endOffset: endOffset,\n prefix: entity.prefix,\n suffix: entity.suffix\n };\n }).filter((entity: ExtractedEntity | null): entity is ExtractedEntity => {\n // Filter out nulls and ensure we have valid offsets\n if (entity === null) {\n logger?.debug('Filtered entity: null');\n return false;\n }\n if (entity.startOffset === undefined || entity.endOffset === undefined) {\n logger?.warn('Filtered entity: missing offsets', { text: entity.exact });\n return false;\n }\n if (entity.startOffset < 0) {\n logger?.warn('Filtered entity: negative startOffset', {\n text: entity.exact,\n startOffset: entity.startOffset\n });\n return false;\n }\n if (entity.endOffset > exact.length) {\n logger?.warn('Filtered entity: endOffset exceeds text length', {\n text: entity.exact,\n endOffset: entity.endOffset,\n textLength: exact.length\n });\n return false;\n }\n\n // Verify the text at the offsets matches\n const extractedText = exact.substring(entity.startOffset, entity.endOffset);\n if (extractedText !== entity.exact) {\n logger?.warn('Filtered entity: offset mismatch', {\n expected: entity.exact,\n got: extractedText,\n offsets: `[${entity.startOffset}:${entity.endOffset}]`\n });\n return false;\n }\n\n logger?.debug('Accepted entity', {\n text: entity.exact,\n offsets: `[${entity.startOffset}:${entity.endOffset}]`\n });\n return true;\n });\n } catch (error) {\n logger?.error('Failed to parse entity extraction response', {\n error: error instanceof Error ? error.message : String(error)\n });\n return [];\n }\n}","/**\n * Generation Worker\n *\n * Processes generation jobs: runs AI inference to generate new resources\n * and emits resource.created and annotation.body.updated events.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, JobQueue, RunningJob, GenerationParams, GenerationProgress, GenerationResult, GenerationJob } from '@semiont/jobs';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { ResourceContext } from '..';\nimport { generateResourceFromTopic } from '../generation/resource-generation';\nimport { resourceUri, annotationUri, EventBus, type Logger } from '@semiont/core';\nimport { getTargetSelector, getExactText } from '@semiont/api-client';\nimport { getEntityTypes } from '@semiont/ontology';\nimport {\n CREATION_METHODS,\n type BodyOperation,\n resourceId,\n annotationId,\n} from '@semiont/core';\nimport { generateUuid } from '../id-generation';\nimport { EventStore } from '@semiont/event-sourcing';\nimport type { EnvironmentConfig } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class GenerationWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'GenerationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'generation';\n }\n\n protected async executeJob(job: AnyJob): Promise<GenerationResult> {\n if (job.metadata.type !== 'generation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n return await this.processGenerationJob(job as RunningJob<GenerationParams, GenerationProgress>);\n }\n\n private async processGenerationJob(job: RunningJob<GenerationParams, GenerationProgress>): Promise<GenerationResult> {\n this.logger?.info('Processing generation job', {\n referenceId: job.params.referenceId,\n jobId: job.metadata.id\n });\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Update progress: fetching\n let updatedJob: RunningJob<GenerationParams, GenerationProgress> = {\n ...job,\n progress: {\n stage: 'fetching',\n percentage: 20,\n message: 'Fetching source resource...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Fetch annotation from view storage\n // TODO: Once AnnotationContext is consolidated, use it here\n const { FilesystemViewStorage } = await import('@semiont/event-sourcing');\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(job.params.sourceResourceId);\n if (!view) {\n throw new Error(`Resource ${job.params.sourceResourceId} not found`);\n }\n const projection = view.annotations;\n\n // Construct full annotation URI for comparison\n const expectedAnnotationUri = `${this.config.services.backend!.publicURL}/annotations/${job.params.referenceId}`;\n const annotation = projection.annotations.find((a: any) =>\n a.id === expectedAnnotationUri && a.motivation === 'linking'\n );\n\n if (!annotation) {\n throw new Error(`Annotation ${job.params.referenceId} not found in resource ${job.params.sourceResourceId}`);\n }\n\n const sourceResource = await ResourceContext.getResourceMetadata(job.params.sourceResourceId, this.config);\n if (!sourceResource) {\n throw new Error(`Source resource ${job.params.sourceResourceId} not found`);\n }\n\n // Determine resource name\n const targetSelector = getTargetSelector(annotation.target);\n const resourceName = job.params.title || (targetSelector ? getExactText(targetSelector) : '') || 'New Resource';\n this.logger?.info('Generating resource', { resourceName });\n\n // Verify context is provided (required for generation)\n if (!job.params.context) {\n throw new Error('Generation context is required but was not provided in job');\n }\n this.logger?.debug('Using pre-fetched context', {\n beforeLength: job.params.context.sourceContext?.before?.length || 0,\n selectedLength: job.params.context.sourceContext?.selected?.length || 0,\n afterLength: job.params.context.sourceContext?.after?.length || 0\n });\n\n // Update progress: generating (skip fetching context since it's already in job)\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 40,\n message: 'Creating content with AI...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Generate content using AI with context from job\n const prompt = job.params.prompt || `Create a comprehensive resource about \"${resourceName}\"`;\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes({ body: annotation.body });\n\n const generatedContent = await generateResourceFromTopic(\n resourceName,\n job.params.entityTypes || annotationEntityTypes,\n this.inferenceClient,\n prompt,\n job.params.language,\n job.params.context, // NEW - context from job (passed from modal)\n job.params.temperature, // NEW - from job\n job.params.maxTokens // NEW - from job\n );\n\n this.logger?.info('Content generated', { contentLength: generatedContent.content.length });\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 70,\n message: 'Content ready, creating resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Generate resource ID\n const rId = resourceId(generateUuid());\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 85,\n message: 'Saving resource...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Save content to RepresentationStore\n const storedRep = await repStore.store(Buffer.from(generatedContent.content), {\n mediaType: 'text/markdown',\n rel: 'original',\n });\n this.logger?.info('Saved resource representation', { resourceId: rId });\n\n // Emit resource.created event\n await this.eventStore.appendEvent({\n type: 'resource.created',\n resourceId: rId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n name: resourceName,\n format: 'text/markdown',\n contentChecksum: storedRep.checksum,\n creationMethod: CREATION_METHODS.GENERATED,\n entityTypes: job.params.entityTypes || annotationEntityTypes,\n language: job.params.language,\n isDraft: true,\n generatedFrom: job.params.referenceId,\n generationPrompt: undefined, // Could be added if we track the prompt\n },\n });\n this.logger?.info('Emitted resource.created event', { resourceId: rId });\n\n // Update progress: linking\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 95,\n message: 'Linking reference...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Emit annotation.body.updated event to link the annotation to the new resource\n // Build full resource URI for the annotation body\n const newResourceUri = resourceUri(`${this.config.services.backend!.publicURL}/resources/${rId}`);\n\n const operations: BodyOperation[] = [{\n op: 'add',\n item: {\n type: 'SpecificResource',\n source: newResourceUri,\n purpose: 'linking',\n },\n }];\n\n // Extract annotation ID from full URI (format: http://host/annotations/{id})\n const annotationIdSegment = job.params.referenceId.split('/').pop()!;\n\n await this.eventStore.appendEvent({\n type: 'annotation.body.updated',\n resourceId: job.params.sourceResourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotationId: annotationId(annotationIdSegment),\n operations,\n },\n });\n this.logger?.info('Emitted annotation.body.updated event', {\n referenceId: job.params.referenceId,\n targetResourceId: rId\n });\n\n // Final progress update\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 100,\n message: 'Complete!'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n this.logger?.info('Generation complete', { createdResourceId: rId });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n resourceId: rId,\n resourceName: resourceName\n };\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event with resultResourceId\n */\n protected override async emitCompletionEvent(\n job: RunningJob<GenerationParams, GenerationProgress>,\n result: GenerationResult\n ): Promise<void> {\n // DOMAIN EVENT: Write to EventStore (auto-publishes to global EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.sourceResourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'generation',\n resultResourceId: result.resourceId,\n annotationUri: annotationUri(`${this.config.services.backend!.publicURL}/annotations/${job.params.referenceId}`),\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(job.params.sourceResourceId);\n this.logger?.debug('[EventBus] Emitting job:completed to resource-scoped bus', {\n resourceId: job.params.sourceResourceId,\n jobId: job.metadata.id\n });\n resourceBus.get('job:completed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.completed' }>);\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'generation') {\n // Type narrowing: job is FailedJob<GenerationParams>\n const genJob = job as GenerationJob;\n\n const errorMessage = 'Resource generation failed. Please try again later.';\n\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: genJob.params.sourceResourceId,\n userId: genJob.metadata.userId,\n version: 1,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n error: errorMessage,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(genJob.params.sourceResourceId);\n this.logger?.debug('[EventBus] Emitting job:failed to resource-scoped bus', {\n resourceId: genJob.params.sourceResourceId,\n jobId: genJob.metadata.id\n });\n resourceBus.get('job:failed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.failed' }>);\n }\n }\n\n /**\n * Update job progress and emit events to Event Store\n * Overrides base class to also emit job progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for generation jobs\n if (job.metadata.type !== 'generation') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const genJob = job as RunningJob<GenerationParams, GenerationProgress>;\n\n const baseEvent = {\n resourceId: genJob.params.sourceResourceId,\n userId: genJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(genJob.params.sourceResourceId);\n\n // Emit appropriate event based on progress stage\n if (genJob.progress.stage === 'fetching' && genJob.progress.percentage === 20) {\n // First progress update - emit job.started\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n totalSteps: 5, // fetching, generating, creating, linking, complete\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n currentStep: genJob.progress.stage,\n percentage: genJob.progress.percentage,\n message: genJob.progress.message,\n },\n });\n resourceBus.get('generate:progress').next({\n status: genJob.progress.stage as 'fetching' | 'generating' | 'creating',\n referenceId: genJob.params.referenceId,\n sourceResourceId: genJob.params.sourceResourceId,\n percentage: genJob.progress.percentage,\n message: genJob.progress.message\n });\n }\n }\n}\n","/**\n * Resource Generation Functions\n *\n * Application-specific resource generation logic including:\n * - Markdown resource generation from topics\n * - Resource summary generation\n * - Reference suggestion generation\n * - Language handling and template processing\n *\n */\n\nimport { getLocaleEnglishName } from '@semiont/api-client';\nimport type { GenerationContext, Logger } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\n\n\nfunction getLanguageName(locale: string): string {\n return getLocaleEnglishName(locale) || locale;\n}\n\n/**\n * Generate resource content using inference\n */\nexport async function generateResourceFromTopic(\n topic: string,\n entityTypes: string[],\n client: InferenceClient,\n userPrompt?: string,\n locale?: string,\n context?: GenerationContext,\n temperature?: number,\n maxTokens?: number,\n logger?: Logger\n): Promise<{ title: string; content: string }> {\n logger?.debug('Generating resource from topic', {\n topicPreview: topic.substring(0, 100),\n entityTypes,\n hasUserPrompt: !!userPrompt,\n locale,\n hasContext: !!context,\n temperature,\n maxTokens\n });\n\n // Use provided values or defaults\n const finalTemperature = temperature ?? 0.7;\n const finalMaxTokens = maxTokens ?? 500;\n\n // Determine language instruction\n const languageInstruction = locale && locale !== 'en'\n ? `\\n\\nIMPORTANT: Write the entire resource in ${getLanguageName(locale)}.`\n : '';\n\n // Build context section if available\n let contextSection = '';\n if (context?.sourceContext) {\n const { before, selected, after } = context.sourceContext;\n contextSection = `\\n\\nSource document context:\n---\n${before ? `...${before}` : ''}\n**[${selected}]**\n${after ? `${after}...` : ''}\n---\n`;\n }\n\n // Simple, direct prompt - just ask for markdown content\n const prompt = `Generate a concise, informative resource about \"${topic}\".\n${entityTypes.length > 0 ? `Focus on these entity types: ${entityTypes.join(', ')}.` : ''}\n${userPrompt ? `Additional context: ${userPrompt}` : ''}${contextSection}${languageInstruction}\n\nRequirements:\n- Start with a clear heading (# Title)\n- Write 2-3 paragraphs of substantive content\n- Be factual and informative\n- Use markdown formatting\n- Return ONLY the markdown content, no JSON, no code fences, no additional wrapper`;\n\n // Simple parser - just use the response directly as markdown\n const parseResponse = (response: string): { title: string; content: string } => {\n // Clean up any markdown code fences if present\n let content = response.trim();\n if (content.startsWith('```markdown') || content.startsWith('```md')) {\n content = content.slice(content.indexOf('\\n') + 1);\n const endIndex = content.lastIndexOf('```');\n if (endIndex !== -1) {\n content = content.slice(0, endIndex);\n }\n } else if (content.startsWith('```')) {\n content = content.slice(3);\n const endIndex = content.lastIndexOf('```');\n if (endIndex !== -1) {\n content = content.slice(0, endIndex);\n }\n }\n\n content = content.trim();\n\n // Title is provided by the caller (topic), not extracted from generated content\n // This matches how it's actually used in generation-worker.ts line 87\n return {\n title: topic,\n content: content\n };\n };\n\n logger?.debug('Sending prompt to inference', {\n promptLength: prompt.length,\n temperature: finalTemperature,\n maxTokens: finalMaxTokens\n });\n const response = await client.generateText(prompt, finalMaxTokens, finalTemperature);\n logger?.debug('Got response from inference', { responseLength: response.length });\n\n const result = parseResponse(response);\n logger?.debug('Parsed response', {\n hasTitle: !!result.title,\n titleLength: result.title?.length,\n hasContent: !!result.content,\n contentLength: result.content?.length\n });\n\n return result;\n}\n\n/**\n * Generate an intelligent summary for a resource\n */\nexport async function generateResourceSummary(\n resourceName: string,\n content: string,\n entityTypes: string[],\n client: InferenceClient\n): Promise<string> {\n // Truncate content if too long\n const truncatedContent = content.length > 2000\n ? content.substring(0, 2000) + '...'\n : content;\n\n const prompt = `Create a brief, intelligent summary of this resource titled \"${resourceName}\".\n${entityTypes.length > 0 ? `Key entity types: ${entityTypes.join(', ')}` : ''}\n\nResource content:\n${truncatedContent}\n\nWrite a 2-3 sentence summary that captures the key points and would help someone understand what this resource contains.`;\n\n return await client.generateText(prompt, 150, 0.5);\n}\n\n/**\n * Generate smart suggestions for a reference\n */\nexport async function generateReferenceSuggestions(\n referenceTitle: string,\n client: InferenceClient,\n entityType?: string,\n currentContent?: string\n): Promise<string[] | null> {\n const prompt = `For a reference titled \"${referenceTitle}\"${entityType ? ` (type: ${entityType})` : ''}${currentContent ? ` with current stub: \"${currentContent}\"` : ''}, suggest 3 specific, actionable next steps or related topics to explore.\n\nFormat as a simple list, one suggestion per line.`;\n\n const response = await client.generateText(prompt, 200, 0.8);\n if (!response) {\n return null;\n }\n\n // Parse into array of suggestions\n return response\n .split('\\n')\n .map(line => line.replace(/^[-*•]\\s*/, '').trim())\n .filter(line => line.length > 0)\n .slice(0, 3);\n}\n","/**\n * ID generation utilities\n */\n\nimport { randomBytes } from 'crypto';\n\n/**\n * Generate a UUID v4-like ID (without dashes)\n */\nexport function generateUuid(): string {\n return randomBytes(16).toString('hex');\n}\n","/**\n * Highlight Detection Worker\n *\n * Processes highlight-detection jobs: runs AI inference to find passages\n * that should be highlighted and creates highlight annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, HighlightDetectionJob, JobQueue, RunningJob, HighlightDetectionParams, HighlightDetectionProgress, HighlightDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { HighlightMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class HighlightAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'HighlightAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'highlight-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<HighlightDetectionResult> {\n if (job.metadata.type !== 'highlight-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processHighlightDetectionJob(job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<HighlightDetectionParams, HighlightDetectionProgress>,\n result: HighlightDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'highlight-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'highlight-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const hlJob = job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>;\n\n const baseEvent = {\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(hlJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n progress: hlJob.progress,\n },\n });\n resourceBus.get('annotate:progress').next({\n status: hlJob.progress.stage,\n message: hlJob.progress.message,\n percentage: hlJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'highlight-annotation') {\n const hlJob = job as HighlightDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n error: 'Highlight detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processHighlightDetectionJob(job: RunningJob<HighlightDetectionParams, HighlightDetectionProgress>): Promise<HighlightDetectionResult> {\n this.logger?.info('Processing highlight detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<HighlightDetectionParams, HighlightDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect highlights\n const highlights = await AnnotationDetection.detectHighlights(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.density\n );\n\n this.logger?.info('Found highlights to create', { count: highlights.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${highlights.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each highlight\n let created = 0;\n for (const highlight of highlights) {\n try {\n await this.createHighlightAnnotation(job.params.resourceId, job.metadata.userId, highlight);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create highlight', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} highlights`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Highlight detection complete', { created, total: highlights.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n highlightsFound: highlights.length,\n highlightsCreated: created\n };\n }\n\n private async createHighlightAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n highlight: HighlightMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: highlighting\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'highlighting' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: highlight.start,\n end: highlight.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: highlight.exact,\n ...(highlight.prefix && { prefix: highlight.prefix }),\n ...(highlight.suffix && { suffix: highlight.suffix }),\n },\n ]\n },\n 'body': [] // Empty body for highlights\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Assessment Detection Worker\n *\n * Processes assessment-detection jobs: runs AI inference to assess/evaluate\n * passages in the text and creates assessment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, AssessmentDetectionJob, JobQueue, RunningJob, AssessmentDetectionParams, AssessmentDetectionProgress, AssessmentDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { AssessmentMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class AssessmentAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'AssessmentAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'assessment-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<AssessmentDetectionResult> {\n if (job.metadata.type !== 'assessment-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processAssessmentDetectionJob(job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>,\n result: AssessmentDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'assessment-annotation',\n result,\n },\n });\n\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'assessment-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const assJob = job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>;\n\n const baseEvent = {\n resourceId: assJob.params.resourceId,\n userId: assJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(assJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n progress: assJob.progress,\n },\n });\n resourceBus.get('annotate:progress').next({\n status: assJob.progress.stage,\n message: assJob.progress.message,\n percentage: assJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'assessment-annotation') {\n const aJob = job as AssessmentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: aJob.params.resourceId,\n userId: aJob.metadata.userId,\n version: 1,\n payload: {\n jobId: aJob.metadata.id,\n jobType: aJob.metadata.type,\n error: 'Assessment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processAssessmentDetectionJob(job: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>): Promise<AssessmentDetectionResult> {\n this.logger?.info('Processing assessment detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect assessments\n const assessments = await AnnotationDetection.detectAssessments(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n this.logger?.info('Found assessments to create', { count: assessments.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${assessments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each assessment\n let created = 0;\n for (const assessment of assessments) {\n try {\n await this.createAssessmentAnnotation(job.params.resourceId, job.metadata.userId, assessment);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create assessment', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} assessments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Assessment detection complete', { created, total: assessments.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n assessmentsFound: assessments.length,\n assessmentsCreated: created\n };\n }\n\n private async createAssessmentAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n assessment: AssessmentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: assessing\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'assessing' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: assessment.start,\n end: assessment.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: assessment.exact,\n ...(assessment.prefix && { prefix: assessment.prefix }),\n ...(assessment.suffix && { suffix: assessment.suffix }),\n },\n ]\n },\n 'body': {\n type: 'TextualBody' as const,\n value: assessment.assessment,\n format: 'text/plain'\n }\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Comment Detection Worker\n *\n * Processes comment-detection jobs: runs AI inference to identify passages\n * that would benefit from explanatory comments and creates comment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, CommentDetectionJob, JobQueue, RunningJob, CommentDetectionParams, CommentDetectionProgress, CommentDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { CommentMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class CommentAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'CommentAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'comment-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<CommentDetectionResult> {\n if (job.metadata.type !== 'comment-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processCommentDetectionJob(job as RunningJob<CommentDetectionParams, CommentDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<CommentDetectionParams, CommentDetectionProgress>,\n result: CommentDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'comment-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'comment-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const cdJob = job as RunningJob<CommentDetectionParams, CommentDetectionProgress>;\n\n const baseEvent = {\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(cdJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n progress: cdJob.progress,\n },\n });\n resourceBus.get('annotate:progress').next({\n status: cdJob.progress.stage,\n message: cdJob.progress.message,\n percentage: cdJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'comment-annotation') {\n const cdJob = job as CommentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n error: 'Comment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processCommentDetectionJob(job: RunningJob<CommentDetectionParams, CommentDetectionProgress>): Promise<CommentDetectionResult> {\n this.logger?.info('Processing comment detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<CommentDetectionParams, CommentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text and generating comments...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect passages needing comments\n const comments = await AnnotationDetection.detectComments(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n this.logger?.info('Found comments to create', { count: comments.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${comments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each comment\n let created = 0;\n for (const comment of comments) {\n try {\n await this.createCommentAnnotation(job.params.resourceId, job.metadata.userId, comment);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create comment', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} comments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Comment detection complete', { created, total: comments.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n commentsFound: comments.length,\n commentsCreated: created\n };\n }\n\n private async createCommentAnnotation(\n resourceId: ResourceId,\n userId_: string,\n comment: CommentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with motivation: \"commenting\"\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'commenting' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: comment.start,\n end: comment.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: comment.exact,\n prefix: comment.prefix || '',\n suffix: comment.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: comment.comment,\n purpose: 'commenting' as const,\n format: 'text/plain',\n language: 'en'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n this.logger?.debug('Created comment annotation', {\n annotationId,\n exactPreview: comment.exact.substring(0, 50)\n });\n }\n}\n","/**\n * Tag Detection Worker\n *\n * Processes tag-detection jobs: runs AI inference to identify passages\n * serving specific structural roles (IRAC, IMRAD, Toulmin, etc.) and\n * creates tag annotations with dual-body structure.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, TagDetectionJob, JobQueue, RunningJob, TagDetectionParams, TagDetectionProgress, TagDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport { getTagSchema } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { TagMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class TagAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'TagAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'tag-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<TagDetectionResult> {\n if (job.metadata.type !== 'tag-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processTagDetectionJob(job as RunningJob<TagDetectionParams, TagDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<TagDetectionParams, TagDetectionProgress>,\n result: TagDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'tag-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'tag-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const tdJob = job as RunningJob<TagDetectionParams, TagDetectionProgress>;\n\n const baseEvent = {\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(tdJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n progress: tdJob.progress,\n },\n });\n resourceBus.get('annotate:progress').next({\n status: tdJob.progress.stage,\n message: tdJob.progress.message,\n percentage: tdJob.progress.percentage,\n currentCategory: tdJob.progress.currentCategory,\n processedCategories: tdJob.progress.processedCategories,\n totalCategories: tdJob.progress.totalCategories\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'tag-annotation') {\n const tdJob = job as TagDetectionJob;\n\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n error: 'Tag detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processTagDetectionJob(job: RunningJob<TagDetectionParams, TagDetectionProgress>): Promise<TagDetectionResult> {\n this.logger?.info('Processing tag detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Validate schema\n const schema = getTagSchema(job.params.schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${job.params.schemaId}`);\n }\n\n // Validate categories\n for (const category of job.params.categories) {\n if (!schema.tags.some(t => t.name === category)) {\n throw new Error(`Invalid category \"${category}\" for schema ${job.params.schemaId}`);\n }\n }\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started\n let updatedJob: RunningJob<TagDetectionParams, TagDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n processedCategories: 0,\n totalCategories: job.params.categories.length,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each category separately\n const allTags: TagMatch[] = [];\n const byCategory: Record<string, number> = {};\n\n for (let i = 0; i < job.params.categories.length; i++) {\n const category = job.params.categories[i]!; // Safe: i < length check guarantees element exists\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 10 + Math.floor((i / job.params.categories.length) * 50),\n currentCategory: category,\n processedCategories: i + 1,\n totalCategories: job.params.categories.length,\n message: `Analyzing ${category}...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Detect tags for this category\n const tags = await AnnotationDetection.detectTags(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.schemaId,\n category\n );\n this.logger?.info('Found tags for category', { category, count: tags.length });\n\n allTags.push(...tags);\n byCategory[category] = tags.length;\n }\n\n // Create annotations\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Creating ${allTags.length} tag annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n let created = 0;\n for (const tag of allTags) {\n try {\n await this.createTagAnnotation(job.params.resourceId, job.metadata.userId, job.params.schemaId, tag);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create tag', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Complete! Created ${created} tags`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Tag detection complete', {\n created,\n total: allTags.length,\n categoryCount: job.params.categories.length\n });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n tagsFound: allTags.length,\n tagsCreated: created,\n byCategory\n };\n }\n\n private async createTagAnnotation(\n resourceId: ResourceId,\n userId_: string,\n schemaId: string,\n tag: TagMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with dual-body structure:\n // 1. purpose: \"tagging\" with category value\n // 2. purpose: \"classifying\" with schema ID\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'tagging' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: tag.start,\n end: tag.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: tag.exact,\n prefix: tag.prefix || '',\n suffix: tag.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: tag.category,\n purpose: 'tagging' as const,\n format: 'text/plain',\n language: 'en'\n },\n {\n type: 'TextualBody' as const,\n value: schemaId,\n purpose: 'classifying' as const,\n format: 'text/plain'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n this.logger?.debug('Created tag annotation', {\n annotationId,\n category: tag.category,\n exactPreview: tag.exact.substring(0, 50)\n });\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","export function isFunction(x: any): x is Function {\n return typeof x === 'function';\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like what Promise contructor should used to create Promises\n */\nexport const config = {\n /**\n * The promise constructor used by default for methods such as\n * {@link toPromise} and {@link forEach}\n */\n Promise: undefined as PromiseConstructorLike,\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME\n * FOR MIGRATION REASONS.\n */\n set useDeprecatedSynchronousErrorHandling(value: boolean) {\n if (value) {\n const error = new Error();\n console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n","/**\n * Throws an error on another job so that it's picked up by the runtime's\n * uncaught error handling mechanism.\n * @param err the error to throw\n */\nexport function hostReportError(err: any) {\n setTimeout(() => { throw err; }, 0);\n}","import { Observer } from './types';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\nexport const empty: Observer<any> = {\n closed: true,\n next(value: any): void { /* noop */},\n error(err: any): void {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n },\n complete(): void { /*noop*/ }\n};\n","export function isObject(x: any): x is Object {\n return x !== null && typeof x === 'object';\n}\n","export interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n new(errors: any[]): UnsubscriptionError;\n}\n\nconst UnsubscriptionErrorImpl = (() => {\n function UnsubscriptionErrorImpl(this: any, errors: any[]) {\n Error.call(this);\n this.message = errors ?\n `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}` : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n\n UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n\n return UnsubscriptionErrorImpl;\n})();\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = UnsubscriptionErrorImpl as any;","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic } from './types';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY: Subscription = (function(empty: any) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n * @type {boolean}\n */\n public closed: boolean = false;\n\n /** @internal */\n protected _parentOrParents: Subscription | Subscription[] = null;\n /** @internal */\n private _subscriptions: SubscriptionLike[] = null;\n\n /**\n * @param {function(): void} [unsubscribe] A function describing how to\n * perform the disposal of resources when the `unsubscribe` method is called.\n */\n constructor(unsubscribe?: () => void) {\n if (unsubscribe) {\n (this as any)._ctorUnsubscribe = true;\n (this as any)._unsubscribe = unsubscribe;\n }\n }\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[];\n\n if (this.closed) {\n return;\n }\n\n let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);\n\n this.closed = true;\n this._parentOrParents = null;\n // null out _subscriptions first so any child subscriptions that attempt\n // to remove themselves from this subscription will noop\n this._subscriptions = null;\n\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n } else if (_parentOrParents !== null) {\n for (let index = 0; index < _parentOrParents.length; ++index) {\n const parent = _parentOrParents[index];\n parent.remove(this);\n }\n }\n\n if (isFunction(_unsubscribe)) {\n // It's only possible to null _unsubscribe - to release the reference to\n // any teardown function passed in the constructor - if the property was\n // actually assigned in the constructor, as there are some classes that\n // are derived from Subscriber (which derives from Subscription) that\n // implement an _unsubscribe method as a mechanism for obtaining\n // unsubscription notifications and some of those subscribers are\n // recycled. Also, in some of those subscribers, _unsubscribe switches\n // from a prototype method to an instance property - see notifyNext in\n // RetryWhenSubscriber.\n if (_ctorUnsubscribe) {\n (this as any)._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n\n if (isArray(_subscriptions)) {\n let index = -1;\n let len = _subscriptions.length;\n\n while (++index < len) {\n const sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n } catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n } else {\n errors.push(e);\n }\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n\n /**\n * Adds a tear down to be called during the unsubscribe() of this\n * Subscription. Can also be used to add a child subscription.\n *\n * If the tear down being added is a subscription that is already\n * unsubscribed, is the same reference `add` is being called on, or is\n * `Subscription.EMPTY`, it will not be added.\n *\n * If this subscription is already in an `closed` state, the passed\n * tear down logic will be executed immediately.\n *\n * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.\n *\n * @param {TeardownLogic} teardown The additional logic to execute on\n * teardown.\n * @return {Subscription} Returns the Subscription used or created to be\n * added to the inner subscriptions list. This Subscription can be used with\n * `remove()` to remove the passed teardown logic from the inner subscriptions\n * list.\n */\n add(teardown: TeardownLogic): Subscription {\n let subscription = (<Subscription>teardown);\n\n if (!teardown) {\n return Subscription.EMPTY;\n }\n\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(<(() => void)>teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.\n return subscription;\n } else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n } else if (!(subscription instanceof Subscription)) {\n const tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n\n // Add `this` as parent of `subscription` if that's not already the case.\n let { _parentOrParents } = subscription;\n if (_parentOrParents === null) {\n // If we don't have a parent, then set `subscription._parents` to\n // the `this`, which is the common case that we optimize for.\n subscription._parentOrParents = this;\n } else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n // If there's already one parent, but not multiple, allocate an\n // Array to store the rest of the parent Subscriptions.\n subscription._parentOrParents = [_parentOrParents, this];\n } else if (_parentOrParents.indexOf(this) === -1) {\n // Only add `this` to the _parentOrParents list if it's not already there.\n _parentOrParents.push(this);\n } else {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n\n // Optimize for the common case when adding the first subscription.\n const subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n } else {\n subscriptions.push(subscription);\n }\n\n return subscription;\n }\n\n /**\n * Removes a Subscription from the internal list of subscriptions that will\n * unsubscribe during the unsubscribe process of this Subscription.\n * @param {Subscription} subscription The subscription to remove.\n * @return {void}\n */\n remove(subscription: Subscription): void {\n const subscriptions = this._subscriptions;\n if (subscriptions) {\n const subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n }\n}\n\nfunction flattenUnsubscriptionErrors(errors: any[]) {\n return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);\n}\n","/** @deprecated do not use, this is no longer checked by RxJS internals */\nexport const rxSubscriber = (() =>\n typeof Symbol === 'function'\n ? Symbol('rxSubscriber')\n : '@@rxSubscriber_' + Math.random())();\n\n/**\n * @deprecated use rxSubscriber instead\n */\nexport const $$rxSubscriber = rxSubscriber;\n","import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Observer, PartialObserver, TeardownLogic } from './types';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n\n [rxSubscriberSymbol]() { return this; }\n\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param {function(x: ?T): void} [next] The `next` callback of an Observer.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n */\n static create<T>(next?: (x?: T) => void,\n error?: (e?: any) => void,\n complete?: () => void): Subscriber<T> {\n const subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n }\n\n /** @internal */ syncErrorValue: any = null;\n /** @internal */ syncErrorThrown: boolean = false;\n /** @internal */ syncErrorThrowable: boolean = false;\n\n protected isStopped: boolean = false;\n protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @param {Observer|function(value: T): void} [destinationOrNext] A partially\n * defined Observer or a `next` callback function.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n */\n constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n switch (arguments.length) {\n case 0:\n this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n this.destination = destinationOrNext;\n destinationOrNext.add(this);\n } else {\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);\n }\n break;\n }\n default:\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);\n break;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (!this.isStopped) {\n this._next(value);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n super.unsubscribe();\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.destination.complete();\n this.unsubscribe();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribeAndRecycle(): Subscriber<T> {\n const { _parentOrParents } = this;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SafeSubscriber<T> extends Subscriber<T> {\n\n private _context: any;\n\n constructor(private _parentSubscriber: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n let next: ((value: T) => void);\n let context: any = this;\n\n if (isFunction(observerOrNext)) {\n next = (<((value: T) => void)> observerOrNext);\n } else if (observerOrNext) {\n next = (<PartialObserver<T>> observerOrNext).next;\n error = (<PartialObserver<T>> observerOrNext).error;\n complete = (<PartialObserver<T>> observerOrNext).complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n this.add(<() => void> context.unsubscribe.bind(context));\n }\n context.unsubscribe = this.unsubscribe.bind(this);\n }\n }\n\n this._context = context;\n this._next = next;\n this._error = error;\n this._complete = complete;\n }\n\n next(value?: T): void {\n if (!this.isStopped && this._next) {\n const { _parentSubscriber } = this;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n }\n\n error(err?: any): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n const { useDeprecatedSynchronousErrorHandling } = config;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n } else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n } else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n } else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n }\n\n complete(): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n if (this._complete) {\n const wrappedComplete = () => this._complete.call(this._context);\n\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n } else {\n this.unsubscribe();\n }\n }\n }\n\n private __tryOrUnsub(fn: Function, value?: any): void {\n try {\n fn.call(this._context, value);\n } catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n }\n }\n\n private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n } else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _unsubscribe(): void {\n const { _parentSubscriber } = this;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subject } from '../Subject';\n\n/**\n * Determines whether the ErrorObserver is closed or stopped or has a\n * destination that is closed or stopped - in which case errors will\n * need to be reported via a different mechanism.\n * @param observer the observer\n */\nexport function canReportError(observer: Subscriber<any> | Subject<any>): boolean {\n while (observer) {\n const { closed, destination, isStopped } = observer as any;\n if (closed || isStopped) {\n return false;\n } else if (destination && destination instanceof Subscriber) {\n observer = destination;\n } else {\n observer = null;\n }\n }\n return true;\n}\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nimport { PartialObserver } from '../types';\n\nexport function toSubscriber<T>(\n nextOrObserver?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscriber<T> {\n\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return (<Subscriber<T>> nextOrObserver);\n }\n\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n\n return new Subscriber(nextOrObserver, error, complete);\n}\n","export function identity<T>(x: T): T {\n return x;\n}\n","import { noop } from './noop';\nimport { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pipe<T>(): UnaryFunction<T, T>;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>, ...fns: UnaryFunction<any, any>[]): UnaryFunction<T, {}>;\n/* tslint:enable:max-line-length */\n\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n","import { Operator } from './Operator';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { iif } from './observable/iif';\nimport { throwError } from './observable/throwError';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n\n /** Internal implementation detail, do not use directly. */\n public _isScalar: boolean = false;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n source: Observable<any>;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n operator: Operator<any, T>;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new cold Observable by calling the Observable constructor\n * @static true\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new cold observable\n * @nocollapse\n * @deprecated use new Observable() instead\n */\n static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n }\n\n /**\n * Creates a new Observable, with this Observable as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param {Operator} operator the operator defining the operation to take on the observable\n * @return {Observable} a new observable with the Operator applied\n */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observer?: PartialObserver<T>): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;\n /** @deprecated Use an observer instead of an error callback */\n subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;\n subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will\n * be left uncaught.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,\n * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * ## Example\n * ### Subscribe with an Observer\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Subscribe with functions\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Cancel a subscription\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe(\n * num => console.log(num),\n * undefined,\n * () => {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * );\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // \"unsubscribed!\" after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {ISubscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscription {\n\n const { operator } = this;\n const sink = toSubscriber(observerOrNext, error, complete);\n\n if (operator) {\n sink.add(operator.call(sink, this.source));\n } else {\n sink.add(\n this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink)\n );\n }\n\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n\n return sink;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n\n /**\n * @method forEach\n * @param {Function} next a handler for each value emitted by the observable\n * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise\n * @return {Promise} a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n // Must be declared in a separate statement to avoid a ReferenceError when\n // accessing subscription below in the closure due to Temporal Dead Zone.\n let subscription: Subscription;\n subscription = this.subscribe((value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n }) as Promise<void>;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n const { source } = this;\n return source && source.subscribe(subscriber);\n }\n\n // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in\n // favor of iif and throwError functions.\n /**\n * @nocollapse\n * @deprecated In favor of iif creation function: import { iif } from 'rxjs';\n */\n static if: typeof iif;\n /**\n * @nocollapse\n * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';\n */\n static throw: typeof throwError;\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;\n pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;\n pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;\n pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ### Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { map, filter, scan } from 'rxjs/operators';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x))\n * ```\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n if (operations.length === 0) {\n return this as any;\n }\n\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n toPromise<T>(this: Observable<T>): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;\n /* tslint:enable:max-line-length */\n\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: any;\n this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));\n }) as Promise<T>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n\n return promiseCtor;\n}\n","export interface ObjectUnsubscribedError extends Error {\n}\n\nexport interface ObjectUnsubscribedErrorCtor {\n new(): ObjectUnsubscribedError;\n}\n\nconst ObjectUnsubscribedErrorImpl = (() => {\n function ObjectUnsubscribedErrorImpl(this: any) {\n Error.call(this);\n this.message = 'object unsubscribed';\n this.name = 'ObjectUnsubscribedError';\n return this;\n }\n\n ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);\n\n return ObjectUnsubscribedErrorImpl;\n})();\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = ObjectUnsubscribedErrorImpl as any;","import { Subject } from './Subject';\nimport { Observer } from './types';\nimport { Subscription } from './Subscription';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SubjectSubscription<T> extends Subscription {\n closed: boolean = false;\n\n constructor(public subject: Subject<T>, public subscriber: Observer<T>) {\n super();\n }\n\n unsubscribe() {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n\n const subject = this.subject;\n const observers = subject.observers;\n\n this.subject = null;\n\n if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n return;\n }\n\n const subscriberIndex = observers.indexOf(this.subscriber);\n\n if (subscriberIndex !== -1) {\n observers.splice(subscriberIndex, 1);\n }\n }\n}\n","import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\n\n/**\n * @class SubjectSubscriber<T>\n */\nexport class SubjectSubscriber<T> extends Subscriber<T> {\n constructor(protected destination: Subject<T>) {\n super(destination);\n }\n}\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n *\n * @class Subject<T>\n */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n\n [rxSubscriberSymbol]() {\n return new SubjectSubscriber(this);\n }\n\n observers: Observer<T>[] = [];\n\n closed = false;\n\n isStopped = false;\n\n hasError = false;\n\n thrownError: any = null;\n\n constructor() {\n super();\n }\n\n /**@nocollapse\n * @deprecated use new Subject() instead\n */\n static create: Function = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n return new AnonymousSubject<T>(destination, source);\n }\n\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const subject = new AnonymousSubject(this, this);\n subject.operator = <any>operator;\n return <any>subject;\n }\n\n next(value?: T) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n if (!this.isStopped) {\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].next(value);\n }\n }\n }\n\n error(err: any) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.hasError = true;\n this.thrownError = err;\n this.isStopped = true;\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].error(err);\n }\n this.observers.length = 0;\n }\n\n complete() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.isStopped = true;\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].complete();\n }\n this.observers.length = 0;\n }\n\n unsubscribe() {\n this.isStopped = true;\n this.closed = true;\n this.observers = null;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else {\n return super._trySubscribe(subscriber);\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>): Subscription {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else if (this.hasError) {\n subscriber.error(this.thrownError);\n return Subscription.EMPTY;\n } else if (this.isStopped) {\n subscriber.complete();\n return Subscription.EMPTY;\n } else {\n this.observers.push(subscriber);\n return new SubjectSubscription(this, subscriber);\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create customize Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return {Observable} Observable that the Subject casts to\n */\n asObservable(): Observable<T> {\n const observable = new Observable<T>();\n (<any>observable).source = this;\n return observable;\n }\n}\n\n/**\n * @class AnonymousSubject<T>\n */\nexport class AnonymousSubject<T> extends Subject<T> {\n constructor(protected destination?: Observer<T>, source?: Observable<T>) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n const { destination } = this;\n if (destination && destination.next) {\n destination.next(value);\n }\n }\n\n error(err: any) {\n const { destination } = this;\n if (destination && destination.error) {\n this.destination.error(err);\n }\n }\n\n complete() {\n const { destination } = this;\n if (destination && destination.complete) {\n this.destination.complete();\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>): Subscription {\n const { source } = this;\n if (source) {\n return this.source.subscribe(subscriber);\n } else {\n return Subscription.EMPTY;\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function groupBy<T, K>(keySelector: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K>(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable<K, T>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, R>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>, subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Groups the items emitted by an Observable according to a specified criterion,\n * and emits these grouped items as `GroupedObservables`, one\n * {@link GroupedObservable} per group.\n *\n * ![](groupBy.png)\n *\n * When the Observable emits an item, a key is computed for this item with the keySelector function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Elsewhere, a new\n * {@link GroupedObservable} for this key is created and emits.\n *\n * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common\n * key is available as the key field of a {@link GroupedObservable} instance.\n *\n * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements\n * returned by the elementSelector function.\n *\n * ## Examples\n *\n * ### Group objects by id and return as array\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { mergeMap, groupBy, reduce } from 'rxjs/operators';\n *\n * of(\n * {id: 1, name: 'JavaScript'},\n * {id: 2, name: 'Parcel'},\n * {id: 2, name: 'webpack'},\n * {id: 1, name: 'TypeScript'},\n * {id: 3, name: 'TSLint'}\n * ).pipe(\n * groupBy(p => p.id),\n * mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // [ { id: 1, name: 'JavaScript'},\n * // { id: 1, name: 'TypeScript'} ]\n * //\n * // [ { id: 2, name: 'Parcel'},\n * // { id: 2, name: 'webpack'} ]\n * //\n * // [ { id: 3, name: 'TSLint'} ]\n * ```\n *\n * ### Pivot data on the id field\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';\n *\n * of(\n * { id: 1, name: 'JavaScript' },\n * { id: 2, name: 'Parcel' },\n * { id: 2, name: 'webpack' },\n * { id: 1, name: 'TypeScript' },\n * { id: 3, name: 'TSLint' }\n * )\n * .pipe(\n * groupBy(p => p.id, p => p.name),\n * mergeMap(group$ =>\n * group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))\n * ),\n * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }\n * // { id: 2, values: [ 'Parcel', 'webpack' ] }\n * // { id: 3, values: [ 'TSLint' ] }\n * ```\n *\n * @param {function(value: T): K} keySelector A function that extracts the key\n * for each item.\n * @param {function(value: T): R} [elementSelector] A function that extracts the\n * return element for each item.\n * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @return {Observable<GroupedObservable<K,R>>} An Observable that emits\n * GroupedObservables, each of which corresponds to a unique key value and each\n * of which emits those items from the source Observable that share that key\n * value.\n * @method groupBy\n * @owner Observable\n */\nexport function groupBy<T, K, R>(keySelector: (value: T) => K,\n elementSelector?: ((value: T) => R) | void,\n durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>> {\n return (source: Observable<T>) =>\n source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));\n}\n\nexport interface RefCountSubscription {\n count: number;\n unsubscribe: () => void;\n closed: boolean;\n attemptedToUnsubscribe: boolean;\n}\n\nclass GroupByOperator<T, K, R> implements Operator<T, GroupedObservable<K, R>> {\n constructor(private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n private subjectSelector?: () => Subject<R>) {\n }\n\n call(subscriber: Subscriber<GroupedObservable<K, R>>, source: any): any {\n return source.subscribe(new GroupBySubscriber(\n subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupBySubscriber<T, K, R> extends Subscriber<T> implements RefCountSubscription {\n private groups: Map<K, Subject<T | R>> = null;\n public attemptedToUnsubscribe: boolean = false;\n public count: number = 0;\n\n constructor(destination: Subscriber<GroupedObservable<K, R>>,\n private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n private subjectSelector?: () => Subject<R>) {\n super(destination);\n }\n\n protected _next(value: T): void {\n let key: K;\n try {\n key = this.keySelector(value);\n } catch (err) {\n this.error(err);\n return;\n }\n\n this._group(value, key);\n }\n\n private _group(value: T, key: K) {\n let groups = this.groups;\n\n if (!groups) {\n groups = this.groups = new Map<K, Subject<T | R>>();\n }\n\n let group = groups.get(key);\n\n let element: R;\n if (this.elementSelector) {\n try {\n element = this.elementSelector(value);\n } catch (err) {\n this.error(err);\n }\n } else {\n element = <any>value;\n }\n\n if (!group) {\n group = (this.subjectSelector ? this.subjectSelector() : new Subject<R>()) as Subject<T | R>;\n groups.set(key, group);\n const groupedObservable = new GroupedObservable(key, group, this);\n this.destination.next(groupedObservable);\n if (this.durationSelector) {\n let duration: any;\n try {\n duration = this.durationSelector(new GroupedObservable<K, R>(key, <Subject<R>>group));\n } catch (err) {\n this.error(err);\n return;\n }\n this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));\n }\n }\n\n if (!group.closed) {\n group.next(element);\n }\n }\n\n protected _error(err: any): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.error(err);\n });\n\n groups.clear();\n }\n this.destination.error(err);\n }\n\n protected _complete(): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.complete();\n });\n\n groups.clear();\n }\n this.destination.complete();\n }\n\n removeGroup(key: K): void {\n this.groups.delete(key);\n }\n\n unsubscribe() {\n if (!this.closed) {\n this.attemptedToUnsubscribe = true;\n if (this.count === 0) {\n super.unsubscribe();\n }\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupDurationSubscriber<K, T> extends Subscriber<T> {\n constructor(private key: K,\n private group: Subject<T>,\n private parent: GroupBySubscriber<any, K, T | any>) {\n super(group);\n }\n\n protected _next(value: T): void {\n this.complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { parent, key } = this;\n this.key = this.parent = null;\n if (parent) {\n parent.removeGroup(key);\n }\n }\n}\n\n/**\n * An Observable representing values belonging to the same group represented by\n * a common key. The values emitted by a GroupedObservable come from the source\n * Observable. The common key is available as the field `key` on a\n * GroupedObservable instance.\n *\n * @class GroupedObservable<K, T>\n */\nexport class GroupedObservable<K, T> extends Observable<T> {\n /** @deprecated Do not construct this type. Internal use only */\n constructor(public key: K,\n private groupSubject: Subject<T>,\n private refCountSubscription?: RefCountSubscription) {\n super();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>) {\n const subscription = new Subscription();\n const { refCountSubscription, groupSubject } = this;\n if (refCountSubscription && !refCountSubscription.closed) {\n subscription.add(new InnerRefCountSubscription(refCountSubscription));\n }\n subscription.add(groupSubject.subscribe(subscriber));\n return subscription;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass InnerRefCountSubscription extends Subscription {\n constructor(private parent: RefCountSubscription) {\n super();\n parent.count++;\n }\n\n unsubscribe() {\n const parent = this.parent;\n if (!parent.closed && !this.closed) {\n super.unsubscribe();\n parent.count -= 1;\n if (parent.count === 0 && parent.attemptedToUnsubscribe) {\n parent.unsubscribe();\n }\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable<R>} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return function mapOperation(source: Observable<T>): Observable<R> {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\n\nexport class MapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber<T, R> extends Subscriber<T> {\n count: number = 0;\n private thisArg: any;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => R,\n thisArg: any) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n // NOTE: This looks unoptimized, but it's actually purposefully NOT\n // using try/catch optimizations.\n protected _next(value: T) {\n let result: R;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {\n promise.then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = <T>(iterable: Iterable<T>) => (subscriber: Subscriber<T>) => {\n const iterator = (iterable as any)[Symbol_iterator]();\n\n do {\n let item: IteratorResult<T>;\n try {\n item = iterator.next();\n } catch (err) {\n subscriber.error(err);\n return subscriber;\n }\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n\n // Finalize the iterator if it happens to be a Generator\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n\n return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = <T>(obj: any) => (subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return !!value && typeof (<any>value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result as any);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result as Promise<any>);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result as any);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.`\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable: Subscribable<T> = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(\n value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n },\n err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n }\n )));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let iterator: Iterator<T>;\n sub.add(() => {\n // Finalize generators\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value: T;\n let done: boolean;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n * @name from\n * @owner Observable\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable<T>(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","/** @prettier */\nimport { Subscription } from './Subscription';\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\n\ninterface SimpleOuterSubscriberLike<T> {\n /**\n * A handler for inner next notifications from the inner subscription\n * @param innerValue the value nexted by the inner producer\n */\n notifyNext(innerValue: T): void;\n /**\n * A handler for inner error notifications from the inner subscription\n * @param err the error from the inner producer\n */\n notifyError(err: any): void;\n /**\n * A handler for inner complete notifications from the inner subscription.\n */\n notifyComplete(): void;\n}\n\nexport class SimpleInnerSubscriber<T> extends Subscriber<T> {\n constructor(private parent: SimpleOuterSubscriberLike<any>) {\n super();\n }\n\n protected _next(value: T): void {\n this.parent.notifyNext(value);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete();\n this.unsubscribe();\n }\n}\n\nexport class ComplexInnerSubscriber<T, R> extends Subscriber<R> {\n constructor(private parent: ComplexOuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n super();\n }\n\n protected _next(value: R): void {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n\nexport class SimpleOuterSubscriber<T, R> extends Subscriber<T> implements SimpleOuterSubscriberLike<R> {\n notifyNext(innerValue: R): void {\n this.destination.next(innerValue);\n }\n\n notifyError(err: any): void {\n this.destination.error(err);\n }\n\n notifyComplete(): void {\n this.destination.complete();\n }\n}\n\n/**\n * DO NOT USE (formerly \"OuterSubscriber\")\n * TODO: We want to refactor this and remove it. It is retaining values it shouldn't for long\n * periods of time.\n */\nexport class ComplexOuterSubscriber<T, R> extends Subscriber<T> {\n /**\n * @param _outerValue Used by: bufferToggle, delayWhen, windowToggle\n * @param innerValue Used by: subclass default, combineLatest, race, bufferToggle, windowToggle, withLatestFrom\n * @param _outerIndex Used by: combineLatest, race, withLatestFrom\n * @param _innerSub Used by: delayWhen\n */\n notifyNext(_outerValue: T, innerValue: R, _outerIndex: number, _innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.next(innerValue);\n }\n\n notifyError(error: any): void {\n this.destination.error(error);\n }\n\n /**\n * @param _innerSub Used by: race, bufferToggle, delayWhen, windowToggle, windowWhen\n */\n notifyComplete(_innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.complete();\n }\n}\n\nexport function innerSubscribe(result: any, innerSubscriber: Subscriber<any>): Subscription | undefined {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n let subscription: Subscription;\n try {\n subscription = subscribeTo(result)(innerSubscriber) as Subscription;\n } catch (error) {\n innerSubscriber.error(error);\n }\n return subscription;\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n // DEPRECATED PATH\n return (source: Observable<T>) => source.pipe(\n mergeMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n ), concurrent)\n );\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n }\n\n call(observer: Subscriber<R>, source: any): any {\n return source.subscribe(new MergeMapSubscriber(\n observer, this.project, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private hasCompleted: boolean = false;\n private buffer: T[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n\n protected _tryNext(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error!(err);\n return;\n }\n this.active++;\n this._innerSub(result);\n }\n\n private _innerSub(ish: ObservableInput<R>): void {\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n const innerSubscription = innerSubscribe(ish, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete!();\n }\n this.unsubscribe();\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n\n notifyComplete(): void {\n const buffer = this.buffer;\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift()!);\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete!();\n }\n }\n}\n\n/**\n * @deprecated renamed. Use {@link mergeMap}\n */\nexport const flatMap = mergeMap;","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.</span>\n *\n * ![](concatMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item emitted\n * by the source Observable and taking values from each projected inner\n * Observable sequentially.\n * @method concatMap\n * @owner Observable\n */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n return mergeMap(project, resultSelector, 1);\n}\n","/**\n * GraphDB Consumer\n *\n * Subscribes to resource events and updates GraphDB accordingly.\n * Makes GraphDB a projection of Event Store events (single source of truth).\n *\n * Uses an RxJS pipeline with adaptive burst buffering:\n * - First event after idle passes through immediately (zero latency)\n * - Subsequent events in a burst are batched and flushed together\n * - After idle, returns to passthrough mode\n *\n * Per-resource ordering is preserved via groupBy(resourceId) + concatMap.\n * Cross-resource parallelism is provided via mergeMap over groups.\n *\n * Burst buffer thresholds (see BATCH-GRAPH-CONSUMER-RX.md for tuning guidance):\n * BURST_WINDOW_MS = 50 — debounce window before flushing a batch\n * MAX_BATCH_SIZE = 500 — force flush to bound memory\n * IDLE_TIMEOUT_MS = 200 — silence before returning to passthrough\n */\n\nimport { Subject, Subscription, from } from 'rxjs';\nimport { groupBy, mergeMap, concatMap } from 'rxjs/operators';\nimport { EventQuery, type EventStore } from '@semiont/event-sourcing';\nimport { didToAgent, burstBuffer } from '@semiont/core';\nimport type { GraphDatabase } from '@semiont/graph';\nimport type { components } from '@semiont/core';\nimport type { ResourceEvent, StoredEvent, AnnotationAddedEvent, EnvironmentConfig, ResourceId, Logger } from '@semiont/core';\nimport { resourceId as makeResourceId, findBodyItem } from '@semiont/core';\nimport { toResourceUri, toAnnotationUri } from '@semiont/event-sourcing';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport class GraphDBConsumer {\n // Event types that produce GraphDB mutations — filter everything else\n private static readonly GRAPH_RELEVANT_EVENTS = new Set([\n 'resource.created', 'resource.archived', 'resource.unarchived',\n 'annotation.added', 'annotation.removed', 'annotation.body.updated',\n 'entitytag.added', 'entitytag.removed', 'entitytype.added',\n ]);\n\n // Burst buffer thresholds — see class doc and BATCH-GRAPH-CONSUMER-RX.md\n private static readonly BURST_WINDOW_MS = 50;\n private static readonly MAX_BATCH_SIZE = 500;\n private static readonly IDLE_TIMEOUT_MS = 200;\n\n private _globalSubscription: any = null;\n private eventSubject = new Subject<StoredEvent>();\n private pipelineSubscription: Subscription | null = null;\n private lastProcessed: Map<string, number> = new Map();\n private readonly logger: Logger;\n\n constructor(\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private graphDb: GraphDatabase,\n logger: Logger\n ) {\n this.logger = logger;\n }\n\n async initialize() {\n this.logger.info('GraphDB consumer initialized');\n await this.subscribeToGlobalEvents();\n }\n\n /**\n * Subscribe globally to ALL events, pre-filter to graph-relevant types,\n * and wire through the RxJS burst-buffered pipeline.\n */\n private async subscribeToGlobalEvents() {\n // Bridge: callback-based EventBus subscription → RxJS Subject\n this._globalSubscription = this.eventStore.bus.subscriptions.subscribeGlobal(\n (storedEvent: StoredEvent) => {\n if (!GraphDBConsumer.GRAPH_RELEVANT_EVENTS.has(storedEvent.event.type)) return;\n this.eventSubject.next(storedEvent);\n }\n );\n\n // Build the RxJS pipeline\n this.pipelineSubscription = this.eventSubject.pipe(\n // Split into one inner Observable per resource (system events grouped under '__system__')\n groupBy((se: StoredEvent) => se.event.resourceId ?? '__system__'),\n\n mergeMap((group) => {\n if (group.key === '__system__') {\n // System events (e.g., entitytype.added): process immediately, sequentially\n return group.pipe(\n concatMap((se) => from(this.safeApplyEvent(se)))\n );\n }\n\n // Resource events: apply burst buffering per resource group\n return group.pipe(\n burstBuffer<StoredEvent>({\n burstWindowMs: GraphDBConsumer.BURST_WINDOW_MS,\n maxBatchSize: GraphDBConsumer.MAX_BATCH_SIZE,\n idleTimeoutMs: GraphDBConsumer.IDLE_TIMEOUT_MS,\n }),\n concatMap((eventOrBatch: StoredEvent | StoredEvent[]) => {\n if (Array.isArray(eventOrBatch)) {\n return from(this.processBatch(eventOrBatch));\n }\n return from(this.safeApplyEvent(eventOrBatch).then(() => {\n this.lastProcessed.set(\n eventOrBatch.event.resourceId!,\n eventOrBatch.metadata.sequenceNumber\n );\n }));\n })\n );\n })\n ).subscribe({\n error: (err) => {\n this.logger.error('GraphDB consumer pipeline error', { error: err });\n }\n });\n\n this.logger.info('Subscribed to global events with burst-buffered pipeline');\n }\n\n /**\n * Wrap applyEventToGraph in try/catch so one failed event doesn't kill the pipeline.\n */\n private async safeApplyEvent(storedEvent: StoredEvent): Promise<void> {\n try {\n await this.applyEventToGraph(storedEvent);\n } catch (error) {\n this.logger.error('Failed to apply event to graph', {\n eventType: storedEvent.event.type,\n resourceId: storedEvent.event.resourceId,\n error,\n });\n }\n }\n\n private ensureInitialized(): GraphDatabase {\n return this.graphDb;\n }\n\n /**\n * Stop the consumer, flush remaining buffered events, and unsubscribe.\n */\n async stop() {\n this.logger.info('Stopping GraphDB consumer');\n\n // Unsubscribe from event source (stops feeding the Subject)\n if (this._globalSubscription && typeof this._globalSubscription.unsubscribe === 'function') {\n this._globalSubscription.unsubscribe();\n }\n this._globalSubscription = null;\n\n // Complete the Subject — this triggers burst buffer flush of remaining events\n this.eventSubject.complete();\n\n // Unsubscribe from the pipeline\n if (this.pipelineSubscription) {\n this.pipelineSubscription.unsubscribe();\n this.pipelineSubscription = null;\n }\n\n // Create a fresh Subject for potential re-initialization\n this.eventSubject = new Subject<StoredEvent>();\n\n this.logger.info('GraphDB consumer stopped');\n }\n\n /**\n * Process a batch of events for the same resource.\n * Partitions into consecutive same-type runs for batch optimization.\n */\n private async processBatch(events: StoredEvent[]): Promise<void> {\n // Partition into runs of consecutive same-type events\n const runs: StoredEvent[][] = [];\n let currentRun: StoredEvent[] = [];\n\n for (const event of events) {\n if (currentRun.length > 0 && currentRun[0].event.type !== event.event.type) {\n runs.push(currentRun);\n currentRun = [];\n }\n currentRun.push(event);\n }\n if (currentRun.length > 0) runs.push(currentRun);\n\n for (const run of runs) {\n try {\n if (run.length === 1) {\n await this.applyEventToGraph(run[0]);\n } else {\n await this.applyBatchByType(run);\n }\n } catch (error) {\n this.logger.error('Failed to process batch run', {\n eventType: run[0].event.type,\n runSize: run.length,\n error,\n });\n }\n const last = run[run.length - 1];\n if (last.event.resourceId) {\n this.lastProcessed.set(last.event.resourceId, last.metadata.sequenceNumber);\n }\n }\n\n this.logger.debug('Processed batch', {\n resourceId: events[0]?.event.resourceId,\n batchSize: events.length,\n });\n }\n\n /**\n * Batch-optimized processing for consecutive events of the same type.\n * Uses batch graph methods where available, falls back to sequential.\n */\n private async applyBatchByType(events: StoredEvent[]): Promise<void> {\n const graphDb = this.ensureInitialized();\n const type = events[0].event.type;\n\n switch (type) {\n case 'resource.created': {\n const resources = events.map(e => this.buildResourceDescriptor(e));\n await graphDb.batchCreateResources(resources);\n this.logger.info('Batch created resources in graph', { count: events.length });\n break;\n }\n case 'annotation.added': {\n const inputs = events.map(e => {\n const event = e.event as AnnotationAddedEvent;\n return {\n ...event.payload.annotation,\n creator: didToAgent(event.userId),\n };\n });\n await graphDb.createAnnotations(inputs);\n this.logger.info('Batch created annotations in graph', { count: events.length });\n break;\n }\n default:\n // For types without batch optimization, fall back to sequential\n for (const event of events) {\n await this.applyEventToGraph(event);\n }\n }\n }\n\n /**\n * Build a ResourceDescriptor from a resource.created event.\n * Extracted for reuse by both applyEventToGraph and applyBatchByType.\n */\n private buildResourceDescriptor(storedEvent: StoredEvent): ResourceDescriptor {\n const event = storedEvent.event;\n if (event.type !== 'resource.created') {\n throw new Error('Expected resource.created event');\n }\n if (!event.resourceId) {\n throw new Error('resource.created requires resourceId');\n }\n\n const resourceUri = toResourceUri(\n { baseUrl: this.config.services.backend!.publicURL },\n event.resourceId\n );\n\n return {\n '@context': 'https://schema.org/',\n '@id': resourceUri,\n name: event.payload.name,\n entityTypes: event.payload.entityTypes || [],\n representations: [{\n mediaType: event.payload.format,\n checksum: event.payload.contentChecksum,\n rel: 'original',\n }],\n archived: false,\n dateCreated: new Date().toISOString(),\n wasAttributedTo: didToAgent(event.userId),\n creationMethod: event.payload.creationMethod,\n };\n }\n\n /**\n * Apply a single event to GraphDB.\n */\n protected async applyEventToGraph(storedEvent: StoredEvent): Promise<void> {\n const graphDb = this.ensureInitialized();\n const event = storedEvent.event;\n\n this.logger.debug('Applying event to GraphDB', {\n eventType: event.type,\n sequenceNumber: storedEvent.metadata.sequenceNumber\n });\n\n switch (event.type) {\n case 'resource.created': {\n const resource = this.buildResourceDescriptor(storedEvent);\n this.logger.debug('Creating resource in graph', { resourceUri: resource['@id'] });\n await graphDb.createResource(resource);\n this.logger.info('Resource created in graph', { resourceUri: resource['@id'] });\n break;\n }\n\n case 'resource.archived':\n if (!event.resourceId) throw new Error('resource.archived requires resourceId');\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n archived: true,\n });\n break;\n\n case 'resource.unarchived':\n if (!event.resourceId) throw new Error('resource.unarchived requires resourceId');\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n archived: false,\n });\n break;\n\n case 'annotation.added':\n this.logger.debug('Processing annotation.added event', {\n annotationId: event.payload.annotation.id\n });\n await graphDb.createAnnotation({\n ...event.payload.annotation,\n creator: didToAgent(event.userId),\n });\n this.logger.info('Annotation created in graph', {\n annotationId: event.payload.annotation.id\n });\n break;\n\n case 'annotation.removed':\n await graphDb.deleteAnnotation(toAnnotationUri({ baseUrl: this.config.services.backend!.publicURL }, event.payload.annotationId));\n break;\n\n case 'annotation.body.updated':\n this.logger.debug('Processing annotation.body.updated event', {\n annotationId: event.payload.annotationId,\n payload: event.payload\n });\n try {\n const annotationUri = toAnnotationUri({ baseUrl: this.config.services.backend!.publicURL }, event.payload.annotationId);\n\n const currentAnnotation = await graphDb.getAnnotation(annotationUri);\n\n if (currentAnnotation) {\n let bodyArray = Array.isArray(currentAnnotation.body)\n ? [...currentAnnotation.body]\n : currentAnnotation.body\n ? [currentAnnotation.body]\n : [];\n\n for (const op of event.payload.operations) {\n if (op.op === 'add') {\n const exists = findBodyItem(bodyArray, op.item) !== -1;\n if (!exists) {\n bodyArray.push(op.item);\n }\n } else if (op.op === 'remove') {\n const index = findBodyItem(bodyArray, op.item);\n if (index !== -1) {\n bodyArray.splice(index, 1);\n }\n } else if (op.op === 'replace') {\n const index = findBodyItem(bodyArray, op.oldItem);\n if (index !== -1) {\n bodyArray[index] = op.newItem;\n }\n }\n }\n\n await graphDb.updateAnnotation(annotationUri, {\n body: bodyArray,\n } as Partial<Annotation>);\n\n this.logger.info('updateAnnotation completed successfully');\n } else {\n this.logger.warn('Annotation not found in graph, skipping update');\n }\n } catch (error) {\n this.logger.error('Error in annotation.body.updated handler', {\n annotationId: event.payload.annotationId,\n error,\n stack: error instanceof Error ? error.stack : undefined\n });\n }\n break;\n\n case 'entitytag.added':\n if (!event.resourceId) throw new Error('entitytag.added requires resourceId');\n {\n const doc = await graphDb.getResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId));\n if (doc) {\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n entityTypes: [...(doc.entityTypes || []), event.payload.entityType],\n });\n }\n }\n break;\n\n case 'entitytag.removed':\n if (!event.resourceId) throw new Error('entitytag.removed requires resourceId');\n {\n const doc = await graphDb.getResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId));\n if (doc) {\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n entityTypes: (doc.entityTypes || []).filter(t => t !== event.payload.entityType),\n });\n }\n }\n break;\n\n case 'entitytype.added':\n await graphDb.addEntityType(event.payload.entityType);\n break;\n\n default:\n this.logger.warn('Unknown event type', { eventType: (event as ResourceEvent).type });\n }\n }\n\n /**\n * Rebuild entire resource from events.\n * Bypasses the live pipeline — reads directly from event store.\n */\n async rebuildResource(resourceId: ResourceId): Promise<void> {\n const graphDb = this.ensureInitialized();\n this.logger.info('Rebuilding resource from events', { resourceId });\n\n try {\n await graphDb.deleteResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, makeResourceId(resourceId)));\n } catch (error) {\n this.logger.debug('No existing resource to delete', { resourceId });\n }\n\n const query = new EventQuery(this.eventStore.log.storage);\n const events = await query.getResourceEvents(resourceId);\n\n for (const storedEvent of events) {\n await this.applyEventToGraph(storedEvent);\n }\n\n this.logger.info('Resource rebuild complete', { resourceId, eventCount: events.length });\n }\n\n /**\n * Rebuild entire GraphDB from all events.\n * Uses two-pass approach to ensure all resources exist before creating REFERENCES edges.\n * Bypasses the live pipeline — reads directly from event store.\n */\n async rebuildAll(): Promise<void> {\n const graphDb = this.ensureInitialized();\n this.logger.info('Rebuilding entire GraphDB from events');\n this.logger.info('Using two-pass approach: nodes first, then edges');\n\n await graphDb.clearDatabase();\n\n const query = new EventQuery(this.eventStore.log.storage);\n const allResourceIds = await this.eventStore.log.getAllResourceIds();\n\n this.logger.info('Found resources to rebuild', { count: allResourceIds.length });\n\n // PASS 1: Create all nodes (resources and annotations)\n this.logger.info('PASS 1: Creating all nodes (resources + annotations)');\n for (const resourceId of allResourceIds) {\n const events = await query.getResourceEvents(makeResourceId(resourceId as string));\n\n for (const storedEvent of events) {\n if (storedEvent.event.type === 'annotation.body.updated') {\n continue;\n }\n await this.applyEventToGraph(storedEvent);\n }\n }\n this.logger.info('Pass 1 complete - all nodes created');\n\n // PASS 2: Create all edges (REFERENCES relationships)\n this.logger.info('PASS 2: Creating all REFERENCES edges');\n for (const resourceId of allResourceIds) {\n const events = await query.getResourceEvents(makeResourceId(resourceId as string));\n\n for (const storedEvent of events) {\n if (storedEvent.event.type === 'annotation.body.updated') {\n await this.applyEventToGraph(storedEvent);\n }\n }\n }\n this.logger.info('Pass 2 complete - all edges created');\n\n this.logger.info('Rebuild complete');\n }\n\n /**\n * Get consumer health metrics.\n */\n getHealthMetrics(): {\n subscriptions: number;\n lastProcessed: Record<string, number>;\n pipelineActive: boolean;\n } {\n return {\n subscriptions: this._globalSubscription ? 1 : 0,\n lastProcessed: Object.fromEntries(this.lastProcessed),\n pipelineActive: !!this.pipelineSubscription,\n };\n }\n\n /**\n * Shutdown consumer.\n */\n async shutdown(): Promise<void> {\n await this.stop();\n this.logger.info('GraphDB consumer shut down');\n }\n}\n","/**\n * Entity Types Bootstrap Service\n *\n * On startup, checks if the entity types projection exists.\n * If not, emits entitytype.added events for each DEFAULT_ENTITY_TYPES entry.\n * This ensures the system has entity types available immediately after first deployment.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { EventStore } from '@semiont/event-sourcing';\nimport { DEFAULT_ENTITY_TYPES } from '@semiont/ontology';\nimport { userId, type EnvironmentConfig, type Logger } from '@semiont/core';\n\n// Singleton flag to ensure bootstrap only runs once per process\nlet bootstrapCompleted = false;\n\n/**\n * Bootstrap entity types projection if it doesn't exist.\n * Uses a system user ID (00000000-0000-0000-0000-000000000000) for bootstrap events.\n */\nexport async function bootstrapEntityTypes(eventStore: EventStore, config: EnvironmentConfig, logger?: Logger): Promise<void> {\n if (bootstrapCompleted) {\n logger?.debug('Entity types bootstrap already completed, skipping');\n return;\n }\n\n // Resolve basePath against project root if relative\n const configuredPath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n const projectionPath = path.join(\n basePath,\n 'projections',\n '__system__',\n 'entitytypes.json'\n );\n\n try {\n // Check if projection exists\n await fs.access(projectionPath);\n logger?.info('Entity types projection already exists, skipping bootstrap');\n bootstrapCompleted = true;\n return;\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error;\n }\n // File doesn't exist - proceed with bootstrap\n logger?.info('Entity types projection does not exist, bootstrapping with DEFAULT_ENTITY_TYPES');\n }\n\n // System user ID for bootstrap events\n const SYSTEM_USER_ID = userId('00000000-0000-0000-0000-000000000000');\n\n // Emit one entitytype.added event for each default entity type\n for (const entityType of DEFAULT_ENTITY_TYPES) {\n logger?.debug('Emitting entitytype.added event', { entityType });\n await eventStore.appendEvent({\n type: 'entitytype.added',\n // resourceId: undefined - system-level event\n userId: SYSTEM_USER_ID,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n\n logger?.info('Entity types bootstrap completed', { count: DEFAULT_ENTITY_TYPES.length });\n bootstrapCompleted = true;\n}\n\n/**\n * Reset the bootstrap flag (used for testing)\n */\nexport function resetBootstrap(): void {\n bootstrapCompleted = false;\n}\n","/**\n * Entity Types Projection Reader\n *\n * Reads entity types from the view storage projection file.\n * This file is maintained by ViewMaterializer in response to entitytype.added events.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { EnvironmentConfig } from '@semiont/core';\n\n/**\n * Read entity types from view storage projection\n */\nexport async function readEntityTypesProjection(config: EnvironmentConfig): Promise<string[]> {\n // Resolve basePath against project root if relative\n const configuredPath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n const entityTypesPath = path.join(\n basePath,\n 'projections',\n '__system__',\n 'entitytypes.json'\n );\n\n try {\n const content = await fs.readFile(entityTypesPath, 'utf-8');\n const projection = JSON.parse(content);\n return projection.entityTypes || [];\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // File doesn't exist yet - return empty array\n return [];\n }\n throw error;\n }\n}\n","/**\n * Resource Operations\n *\n * Business logic for resource operations including:\n * - Resource creation (ID generation, content storage, event emission)\n * - Archive/unarchive operations\n * - Entity type tagging (add/remove)\n * - Computing diffs and emitting appropriate events\n */\n\nimport type { EventStore } from '@semiont/event-sourcing';\nimport type { RepresentationStore } from '@semiont/content';\nimport type { components } from '@semiont/core';\nimport {\n CREATION_METHODS,\n type CreationMethod,\n resourceId,\n type UserId,\n type ResourceId,\n type EnvironmentConfig,\n} from '@semiont/core';\nimport { generateUuid } from './id-generation';\n\ntype CreateResourceResponse = components['schemas']['CreateResourceResponse'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype ContentFormat = components['schemas']['ContentFormat'];\n\nexport interface UpdateResourceInput {\n resourceId: ResourceId;\n userId: UserId;\n currentArchived?: boolean;\n updatedArchived?: boolean;\n currentEntityTypes?: string[];\n updatedEntityTypes?: string[];\n}\n\nexport interface CreateResourceInput {\n name: string;\n content: Buffer;\n format: ContentFormat;\n language?: string;\n entityTypes?: string[];\n creationMethod?: CreationMethod;\n}\n\nexport class ResourceOperations {\n /**\n * Create a new resource\n * Orchestrates: content storage → event emission → response building\n */\n static async createResource(\n input: CreateResourceInput,\n userId: UserId,\n eventStore: EventStore,\n repStore: RepresentationStore,\n config: EnvironmentConfig\n ): Promise<CreateResourceResponse> {\n // Generate resource ID\n const rId = resourceId(generateUuid());\n\n // Store content\n const storedRep = await repStore.store(input.content, {\n mediaType: input.format,\n language: input.language || undefined,\n rel: 'original',\n });\n\n // Validate creation method\n const validCreationMethods = Object.values(CREATION_METHODS) as string[];\n const validatedCreationMethod = input.creationMethod && validCreationMethods.includes(input.creationMethod)\n ? (input.creationMethod as CreationMethod)\n : CREATION_METHODS.API;\n\n // Emit resource.created event\n await eventStore.appendEvent({\n type: 'resource.created',\n resourceId: rId,\n userId,\n version: 1,\n payload: {\n name: input.name,\n format: input.format,\n contentChecksum: storedRep.checksum,\n contentByteSize: storedRep.byteSize,\n creationMethod: validatedCreationMethod,\n entityTypes: input.entityTypes || [],\n language: input.language || undefined,\n isDraft: false,\n generatedFrom: undefined,\n generationPrompt: undefined,\n },\n });\n\n // Build and return response\n const backendUrl = config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n const normalizedBase = backendUrl.endsWith('/') ? backendUrl.slice(0, -1) : backendUrl;\n\n const resourceMetadata: ResourceDescriptor = {\n '@context': 'https://schema.org/',\n '@id': `${normalizedBase}/resources/${rId}`,\n name: input.name,\n archived: false,\n entityTypes: input.entityTypes || [],\n creationMethod: validatedCreationMethod,\n dateCreated: new Date().toISOString(),\n representations: [\n {\n mediaType: storedRep.mediaType,\n checksum: storedRep.checksum,\n byteSize: storedRep.byteSize,\n rel: 'original',\n language: storedRep.language,\n },\n ],\n };\n\n return {\n resource: resourceMetadata,\n annotations: [],\n };\n }\n\n /**\n * Update resource metadata by computing diffs and emitting events\n * Handles: archived status changes, entity type additions/removals\n */\n static async updateResource(\n input: UpdateResourceInput,\n eventStore: EventStore\n ): Promise<void> {\n // Handle archived status change\n if (input.updatedArchived !== undefined && input.updatedArchived !== input.currentArchived) {\n await this.updateArchivedStatus(\n input.resourceId,\n input.userId,\n input.updatedArchived,\n eventStore\n );\n }\n\n // Handle entity type changes\n if (input.updatedEntityTypes && input.currentEntityTypes) {\n await this.updateEntityTypes(\n input.resourceId,\n input.userId,\n input.currentEntityTypes,\n input.updatedEntityTypes,\n eventStore\n );\n }\n }\n\n /**\n * Update archived status by emitting resource.archived or resource.unarchived event\n */\n private static async updateArchivedStatus(\n resourceId: ResourceId,\n userId: UserId,\n archived: boolean,\n eventStore: EventStore\n ): Promise<void> {\n if (archived) {\n await eventStore.appendEvent({\n type: 'resource.archived',\n resourceId,\n userId,\n version: 1,\n payload: {\n reason: undefined,\n },\n });\n } else {\n await eventStore.appendEvent({\n type: 'resource.unarchived',\n resourceId,\n userId,\n version: 1,\n payload: {},\n });\n }\n }\n\n /**\n * Update entity types by computing diff and emitting events for added/removed types\n */\n private static async updateEntityTypes(\n resourceId: ResourceId,\n userId: UserId,\n currentEntityTypes: string[],\n updatedEntityTypes: string[],\n eventStore: EventStore\n ): Promise<void> {\n const diff = this.computeEntityTypeDiff(currentEntityTypes, updatedEntityTypes);\n\n // Emit entitytag.added for new types\n for (const entityType of diff.added) {\n await eventStore.appendEvent({\n type: 'entitytag.added',\n resourceId,\n userId,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n\n // Emit entitytag.removed for removed types\n for (const entityType of diff.removed) {\n await eventStore.appendEvent({\n type: 'entitytag.removed',\n resourceId,\n userId,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n }\n\n /**\n * Compute diff between current and updated entity types\n * Returns arrays of added and removed entity types\n */\n private static computeEntityTypeDiff(\n current: string[],\n updated: string[]\n ): { added: string[]; removed: string[] } {\n const added = updated.filter(et => !current.includes(et));\n const removed = current.filter(et => !updated.includes(et));\n return { added, removed };\n }\n}\n","/**\n * Annotation Operations\n *\n * Business logic for annotation CRUD operations:\n * - Create annotations (ID generation, validation, event emission)\n * - Update annotation body (operations: add/remove/replace)\n * - Delete annotations (validation, event emission)\n *\n */\n\nimport type { EventStore } from '@semiont/event-sourcing';\nimport { generateAnnotationId } from '@semiont/event-sourcing';\nimport type { components } from '@semiont/core';\nimport { getTextPositionSelector, getTargetSource } from '@semiont/api-client';\nimport type {\n AnnotationAddedEvent,\n BodyOperation,\n EnvironmentConfig,\n ResourceId,\n UserId,\n Logger,\n} from '@semiont/core';\nimport { annotationId, uriToResourceId, uriToAnnotationId } from '@semiont/core';\nimport { AnnotationContext } from './annotation-context';\n\ntype Annotation = components['schemas']['Annotation'];\ntype CreateAnnotationRequest = components['schemas']['CreateAnnotationRequest'];\ntype UpdateAnnotationBodyRequest = components['schemas']['UpdateAnnotationBodyRequest'];\n\nexport interface CreateAnnotationResult {\n annotation: Annotation;\n}\n\nexport interface UpdateAnnotationBodyResult {\n annotation: Annotation;\n}\n\nexport class AnnotationOperations {\n /**\n * Create a new annotation\n */\n static async createAnnotation(\n request: CreateAnnotationRequest,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig\n ): Promise<CreateAnnotationResult> {\n // Generate annotation ID\n const backendUrl = config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n const newAnnotationId = generateAnnotationId(backendUrl);\n\n // Validate required fields\n const posSelector = getTextPositionSelector(request.target.selector);\n if (!posSelector) {\n throw new Error('TextPositionSelector required for creating annotations');\n }\n\n if (!request.motivation) {\n throw new Error('motivation is required');\n }\n\n // Build annotation object\n const annotation: Annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n id: newAnnotationId,\n motivation: request.motivation,\n target: request.target,\n body: request.body as Annotation['body'],\n created: new Date().toISOString(),\n modified: new Date().toISOString(),\n };\n\n // Emit annotation.added event\n const eventPayload: Omit<AnnotationAddedEvent, 'id' | 'timestamp'> = {\n type: 'annotation.added',\n resourceId: uriToResourceId(request.target.source),\n userId,\n version: 1,\n payload: {\n annotation: {\n '@context': annotation['@context'],\n 'type': annotation.type,\n id: annotation.id,\n motivation: annotation.motivation,\n target: annotation.target,\n body: annotation.body,\n modified: annotation.modified,\n },\n },\n };\n await eventStore.appendEvent(eventPayload);\n\n return { annotation };\n }\n\n /**\n * Update annotation body with operations (add/remove/replace)\n */\n static async updateAnnotationBody(\n id: string,\n request: UpdateAnnotationBodyRequest,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig\n ): Promise<UpdateAnnotationBodyResult> {\n // Get annotation from view storage\n const annotation = await AnnotationContext.getAnnotation(\n annotationId(id),\n uriToResourceId(request.resourceId) as ResourceId,\n config\n );\n\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Emit annotation.body.updated event\n await eventStore.appendEvent({\n type: 'annotation.body.updated',\n resourceId: uriToResourceId(getTargetSource(annotation.target)),\n userId,\n version: 1,\n payload: {\n annotationId: annotationId(id),\n operations: request.operations as BodyOperation[],\n },\n });\n\n // Apply operations optimistically for response\n const updatedBody = this.applyBodyOperations(annotation.body, request.operations);\n\n return {\n annotation: {\n ...annotation,\n body: updatedBody,\n },\n };\n }\n\n /**\n * Delete an annotation\n */\n static async deleteAnnotation(\n id: string,\n resourceIdUri: string,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<void> {\n const resourceId = uriToResourceId(resourceIdUri);\n\n // Verify annotation exists\n const projection = await AnnotationContext.getResourceAnnotations(resourceId, config);\n const annotation = projection.annotations.find((a: Annotation) => a.id === id);\n\n if (!annotation) {\n throw new Error('Annotation not found in resource');\n }\n\n // Emit annotation.removed event\n logger?.debug('Emitting annotation.removed event', { annotationId: id });\n const storedEvent = await eventStore.appendEvent({\n type: 'annotation.removed',\n resourceId,\n userId,\n version: 1,\n payload: {\n annotationId: uriToAnnotationId(id),\n },\n });\n logger?.debug('Event emitted', { sequenceNumber: storedEvent.metadata.sequenceNumber });\n }\n\n /**\n * Apply body operations (add/remove/replace) to annotation body\n */\n private static applyBodyOperations(\n body: Annotation['body'],\n operations: UpdateAnnotationBodyRequest['operations']\n ): Annotation['body'] {\n const bodyArray = Array.isArray(body) ? [...body] : [];\n\n for (const op of operations) {\n if (op.op === 'add') {\n // Add item (idempotent - don't add if already exists)\n const exists = bodyArray.some(item =>\n JSON.stringify(item) === JSON.stringify(op.item)\n );\n if (!exists) {\n bodyArray.push(op.item);\n }\n } else if (op.op === 'remove') {\n // Remove item\n const index = bodyArray.findIndex(item =>\n JSON.stringify(item) === JSON.stringify(op.item)\n );\n if (index !== -1) {\n bodyArray.splice(index, 1);\n }\n } else if (op.op === 'replace') {\n // Replace item\n const index = bodyArray.findIndex(item =>\n JSON.stringify(item) === JSON.stringify(op.oldItem)\n );\n if (index !== -1) {\n bodyArray[index] = op.newItem;\n }\n }\n }\n\n return bodyArray;\n }\n}\n","/**\n * Annotation Context\n *\n * Assembles annotation context from view storage and content store.\n * Provides methods for:\n * - Getting resource annotations\n * - Building LLM context for annotations\n * - Extracting annotation text context\n * - Generating AI summaries\n *\n * NOTE: This class contains static utility methods without logger access.\n * Console statements kept for debugging - consider adding logger parameter in future.\n */\n\nimport { getInferenceClient } from '@semiont/inference';\nimport { generateResourceSummary } from './generation/resource-generation';\nimport {\n getBodySource,\n getTargetSource,\n getTargetSelector,\n getResourceEntityTypes,\n getTextPositionSelector,\n getPrimaryRepresentation,\n decodeRepresentation,\n} from '@semiont/api-client';\nimport type { components, AnnotationUri, GenerationContext } from '@semiont/core';\n\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport type {\n EnvironmentConfig,\n ResourceId,\n ResourceAnnotations,\n AnnotationId,\n AnnotationCategory,\n Logger,\n} from '@semiont/core';\nimport { resourceId as createResourceId, uriToResourceId } from '@semiont/core';\nimport { getEntityTypes } from '@semiont/ontology';\nimport { ResourceContext } from './resource-context';\n\ntype AnnotationLLMContextResponse = components['schemas']['AnnotationLLMContextResponse'];\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype AnnotationContextResponse = components['schemas']['AnnotationContextResponse'];\ntype ContextualSummaryResponse = components['schemas']['ContextualSummaryResponse'];\n\nexport interface BuildContextOptions {\n includeSourceContext?: boolean;\n includeTargetContext?: boolean;\n contextWindow?: number;\n}\n\ninterface AnnotationTextContext {\n before: string;\n selected: string;\n after: string;\n}\n\nexport class AnnotationContext {\n /**\n * Build LLM context for an annotation\n *\n * @param annotationUri - Full annotation URI (e.g., http://localhost:4000/annotations/abc123)\n * @param resourceId - Source resource ID\n * @param config - Application configuration\n * @param options - Context building options\n * @returns Rich context for LLM processing\n * @throws Error if annotation or resource not found\n */\n static async buildLLMContext(\n annotationUri: AnnotationUri,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n options: BuildContextOptions = {},\n logger?: Logger\n ): Promise<AnnotationLLMContextResponse> {\n const {\n includeSourceContext = true,\n includeTargetContext = true,\n contextWindow = 1000\n } = options;\n\n // Validate contextWindow range\n if (contextWindow < 100 || contextWindow > 5000) {\n throw new Error('contextWindow must be between 100 and 5000');\n }\n\n logger?.debug('Building LLM context', { annotationUri, resourceId });\n\n const basePath = config.services.filesystem!.path;\n logger?.debug('Filesystem basePath', { basePath });\n\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get source resource view\n logger?.debug('Getting view for resource', { resourceId });\n let sourceView;\n try {\n sourceView = await viewStorage.get(resourceId);\n logger?.debug('Retrieved view', { hasView: !!sourceView });\n\n if (!sourceView) {\n throw new Error('Source resource not found');\n }\n } catch (error) {\n logger?.error('Error getting view', { resourceId, error });\n throw error;\n }\n\n logger?.debug('Looking for annotation in resource', {\n annotationUri,\n resourceId,\n totalAnnotations: sourceView.annotations.annotations.length,\n firstFiveIds: sourceView.annotations.annotations.slice(0, 5).map((a: Annotation) => a.id)\n });\n\n // Find the annotation in the view (annotations have full URIs as their id)\n const annotation = sourceView.annotations.annotations.find((a: Annotation) => a.id === annotationUri);\n logger?.debug('Annotation search result', { found: !!annotation });\n\n if (!annotation) {\n throw new Error('Annotation not found in view');\n }\n\n const targetSource = getTargetSource(annotation.target);\n // Extract resource ID from the target source URI (format: http://host/resources/{id})\n const targetResourceId = targetSource.split('/').pop();\n logger?.debug('Validating target resource', { targetSource, expectedResourceId: resourceId, extractedId: targetResourceId });\n\n if (targetResourceId !== resourceId) {\n throw new Error(`Annotation target resource ID (${targetResourceId}) does not match expected resource ID (${resourceId})`);\n }\n\n const sourceDoc = sourceView.resource;\n\n // Get target resource if annotation is a reference (has resolved body source)\n const bodySource = getBodySource(annotation.body);\n\n // Extract target document from body source URI if present\n let targetDoc = null;\n if (bodySource) {\n // Inline extraction: \"http://localhost:4000/resources/abc123\" → \"abc123\"\n const parts = (bodySource as string).split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart) {\n throw new Error(`Invalid body source URI: ${bodySource}`);\n }\n const targetResourceId = createResourceId(lastPart);\n const targetView = await viewStorage.get(targetResourceId);\n targetDoc = targetView?.resource || null;\n }\n\n // Build source context if requested\n let sourceContext;\n if (includeSourceContext) {\n const primaryRep = getPrimaryRepresentation(sourceDoc);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Source content not found');\n }\n const sourceContent = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentStr = decodeRepresentation(sourceContent, primaryRep.mediaType);\n\n const targetSelectorRaw = getTargetSelector(annotation.target);\n\n // Handle array of selectors - take the first one\n const targetSelector = Array.isArray(targetSelectorRaw) ? targetSelectorRaw[0] : targetSelectorRaw;\n\n logger?.debug('Target selector', { type: targetSelector?.type });\n\n if (!targetSelector) {\n logger?.warn('No target selector found');\n } else if (targetSelector.type === 'TextPositionSelector') {\n // TypeScript now knows this is TextPositionSelector with required start/end\n const selector = targetSelector as TextPositionSelector;\n const start = selector.start;\n const end = selector.end;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = contentStr.slice(start, end);\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n logger?.debug('Built source context using TextPositionSelector', { start, end });\n } else if (targetSelector.type === 'TextQuoteSelector') {\n // TypeScript now knows this is TextQuoteSelector with required exact\n const selector = targetSelector as TextQuoteSelector;\n const exact = selector.exact;\n const index = contentStr.indexOf(exact);\n\n if (index !== -1) {\n const start = index;\n const end = index + exact.length;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = exact;\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n logger?.debug('Built source context using TextQuoteSelector', { foundAt: index });\n } else {\n logger?.warn('TextQuoteSelector exact text not found in content', { exactPreview: exact.substring(0, 50) });\n }\n } else {\n logger?.warn('Unknown selector type', { type: (targetSelector as any).type });\n }\n }\n\n // Build target context if requested and available\n let targetContext;\n if (includeTargetContext && targetDoc) {\n const targetRep = getPrimaryRepresentation(targetDoc);\n if (targetRep?.checksum && targetRep?.mediaType) {\n const targetContent = await repStore.retrieve(targetRep.checksum, targetRep.mediaType);\n const contentStr = decodeRepresentation(targetContent, targetRep.mediaType);\n\n // Create inference client for this request (HTTP handler context)\n const client = await getInferenceClient(config, logger);\n\n targetContext = {\n content: contentStr.slice(0, contextWindow * 2),\n summary: await generateResourceSummary(targetDoc.name, contentStr, getResourceEntityTypes(targetDoc), client),\n };\n }\n }\n\n // TODO: Generate suggested resolution using AI\n const suggestedResolution = undefined;\n\n // Build GenerationContext structure\n const generationContext: GenerationContext | undefined = sourceContext ? {\n sourceContext: {\n before: sourceContext.before || '',\n selected: sourceContext.selected,\n after: sourceContext.after || '',\n },\n metadata: {\n resourceType: 'document',\n language: sourceDoc.language as string | undefined,\n entityTypes: getEntityTypes(annotation),\n },\n } : undefined;\n\n const response: AnnotationLLMContextResponse = {\n annotation,\n sourceResource: sourceDoc,\n targetResource: targetDoc,\n ...(generationContext ? { context: generationContext } : {}),\n ...(sourceContext ? { sourceContext } : {}), // Keep for backward compatibility\n ...(targetContext ? { targetContext } : {}),\n ...(suggestedResolution ? { suggestedResolution } : {}),\n };\n\n return response;\n }\n\n /**\n * Get resource annotations from view storage (fast path)\n * Throws if view missing\n */\n static async getResourceAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceAnnotations> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(resourceId);\n\n if (!view) {\n throw new Error(`Resource ${resourceId} not found in view storage`);\n }\n\n return view.annotations;\n }\n\n /**\n * Get all annotations\n * @returns Array of all annotation objects\n */\n static async getAllAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n\n // Enrich resolved references with document names\n // NOTE: Future optimization - make this optional via query param if performance becomes an issue\n return await this.enrichResolvedReferences(annotations.annotations, config);\n }\n\n /**\n * Enrich reference annotations with resolved document names\n * Adds _resolvedDocumentName property to annotations that link to documents\n * @private\n */\n private static async enrichResolvedReferences(annotations: Annotation[], config: EnvironmentConfig): Promise<Annotation[]> {\n if (!config.services?.filesystem?.path) {\n return annotations;\n }\n\n // Extract unique resolved document URIs from reference annotations\n const resolvedUris = new Set<string>();\n for (const ann of annotations) {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.type === 'SpecificResource' && item.purpose === 'linking' && item.source) {\n resolvedUris.add(item.source);\n }\n }\n }\n }\n\n if (resolvedUris.size === 0) {\n return annotations;\n }\n\n // Batch fetch all resolved documents in parallel\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const metadataPromises = Array.from(resolvedUris).map(async (uri) => {\n const docId = uri.split('/resources/')[1];\n if (!docId) return null;\n\n try {\n const view = await viewStorage.get(docId as ResourceId);\n if (view?.resource?.name) {\n return {\n uri,\n metadata: {\n name: view.resource.name,\n mediaType: view.resource.mediaType as string | undefined\n }\n };\n }\n } catch (e) {\n // Document might not exist, skip\n }\n return null;\n });\n\n const results = await Promise.all(metadataPromises);\n const uriToMetadata = new Map<string, { name: string; mediaType?: string }>();\n for (const result of results) {\n if (result) {\n uriToMetadata.set(result.uri, result.metadata);\n }\n }\n\n // Add _resolvedDocumentName and _resolvedDocumentMediaType to annotations\n return annotations.map(ann => {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.type === 'SpecificResource' && item.purpose === 'linking' && item.source) {\n const metadata = uriToMetadata.get(item.source);\n if (metadata) {\n return {\n ...ann,\n _resolvedDocumentName: metadata.name,\n _resolvedDocumentMediaType: metadata.mediaType\n } as Annotation;\n }\n }\n }\n }\n return ann;\n });\n }\n\n /**\n * Get resource stats (version info)\n * @returns Version and timestamp info for the annotations\n */\n static async getResourceStats(resourceId: ResourceId, config: EnvironmentConfig): Promise<{\n resourceId: ResourceId;\n version: number;\n updatedAt: string;\n }> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n return {\n resourceId: annotations.resourceId,\n version: annotations.version,\n updatedAt: annotations.updatedAt,\n };\n }\n\n /**\n * Check if resource exists in view storage\n */\n static async resourceExists(resourceId: ResourceId, config: EnvironmentConfig): Promise<boolean> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n return await viewStorage.exists(resourceId);\n }\n\n /**\n * Get a single annotation by ID\n * O(1) lookup using resource ID to access view storage\n */\n static async getAnnotation(annotationId: AnnotationId, resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation | null> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n // Extract short ID from annotation's full URI for comparison\n return annotations.annotations.find((a: Annotation) => {\n const shortId = a.id.split('/').pop();\n return shortId === annotationId;\n }) || null;\n }\n\n /**\n * List annotations with optional filtering\n * @param filters - Optional filters like resourceId and type\n * @throws Error if resourceId not provided (cross-resource queries not supported in view storage)\n */\n static async listAnnotations(filters: { resourceId?: ResourceId; type?: AnnotationCategory } | undefined, config: EnvironmentConfig): Promise<Annotation[]> {\n if (!filters?.resourceId) {\n throw new Error('resourceId is required for annotation listing - cross-resource queries not supported in view storage');\n }\n\n // Use view storage directly\n return await this.getAllAnnotations(filters.resourceId, config);\n }\n\n /**\n * Get annotation context (selected text with surrounding context)\n */\n static async getAnnotationContext(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n contextBefore: number,\n contextAfter: number,\n config: EnvironmentConfig\n ): Promise<AnnotationContextResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource metadata from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract context based on annotation position\n const context = this.extractAnnotationContext(annotation, contentStr, contextBefore, contextAfter);\n\n return {\n annotation: annotation,\n context,\n resource: {\n '@context': resource['@context'],\n '@id': resource['@id'],\n name: resource.name,\n entityTypes: resource.entityTypes,\n representations: resource.representations,\n archived: resource.archived,\n creationMethod: resource.creationMethod,\n wasAttributedTo: resource.wasAttributedTo,\n dateCreated: resource.dateCreated,\n },\n };\n }\n\n /**\n * Generate AI summary of annotation in context\n */\n static async generateAnnotationSummary(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<ContextualSummaryResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract annotation text with context (fixed 500 chars for summary)\n const contextSize = 500;\n const context = this.extractAnnotationContext(annotation, contentStr, contextSize, contextSize);\n\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes(annotation);\n\n // Generate summary using LLM\n const summary = await this.generateSummary(resource, context, annotationEntityTypes, config, logger);\n\n return {\n summary,\n relevantFields: {\n resourceId: resource.id,\n resourceName: resource.name,\n entityTypes: annotationEntityTypes,\n },\n context: {\n before: context.before.substring(Math.max(0, context.before.length - 200)), // Last 200 chars\n selected: context.selected,\n after: context.after.substring(0, 200), // First 200 chars\n },\n };\n }\n\n /**\n * Get resource content as string\n */\n private static async getResourceContent(\n resource: ResourceDescriptor,\n repStore: FilesystemRepresentationStore\n ): Promise<string> {\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Resource content not found');\n }\n const content = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(content, primaryRep.mediaType);\n }\n\n /**\n * Extract annotation context from resource content\n */\n private static extractAnnotationContext(\n annotation: Annotation,\n contentStr: string,\n contextBefore: number,\n contextAfter: number\n ): AnnotationTextContext {\n const targetSelector = getTargetSelector(annotation.target);\n const posSelector = targetSelector ? getTextPositionSelector(targetSelector) : null;\n if (!posSelector) {\n throw new Error('TextPositionSelector required for context');\n }\n\n const selStart = posSelector.start;\n const selEnd = posSelector.end;\n const start = Math.max(0, selStart - contextBefore);\n const end = Math.min(contentStr.length, selEnd + contextAfter);\n\n return {\n before: contentStr.substring(start, selStart),\n selected: contentStr.substring(selStart, selEnd),\n after: contentStr.substring(selEnd, end),\n };\n }\n\n /**\n * Generate LLM summary of annotation in context\n * Creates inference client per-request (HTTP handler context)\n */\n private static async generateSummary(\n resource: ResourceDescriptor,\n context: AnnotationTextContext,\n entityTypes: string[],\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<string> {\n const summaryPrompt = `Summarize this text in context:\n\nContext before: \"${context.before.substring(Math.max(0, context.before.length - 200))}\"\nSelected exact: \"${context.selected}\"\nContext after: \"${context.after.substring(0, 200)}\"\n\nResource: ${resource.name}\nEntity types: ${entityTypes.join(', ')}`;\n\n // Create client for this HTTP request\n const client = await getInferenceClient(config, logger);\n return await client.generateText(summaryPrompt, 500, 0.5);\n }\n}\n","/**\n * Resource Context\n *\n * Assembles resource context from view storage and content store\n * Does NOT touch the graph - graph queries go through GraphContext\n */\n\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { components } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface ListResourcesFilters {\n search?: string;\n archived?: boolean;\n}\n\nexport class ResourceContext {\n /**\n * Get resource metadata from view storage\n */\n static async getResourceMetadata(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceDescriptor | null> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const view = await viewStorage.get(resourceId);\n if (!view) {\n return null;\n }\n\n return view.resource;\n }\n\n /**\n * List all resources by scanning view storage\n */\n static async listResources(filters: ListResourcesFilters | undefined, config: EnvironmentConfig): Promise<ResourceDescriptor[]> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const allViews = await viewStorage.getAll();\n const resources: ResourceDescriptor[] = [];\n\n for (const view of allViews) {\n const doc = view.resource;\n\n // Apply filters\n if (filters?.archived !== undefined && doc.archived !== filters.archived) {\n continue;\n }\n\n if (filters?.search) {\n const searchLower = filters.search.toLowerCase();\n if (!doc.name.toLowerCase().includes(searchLower)) {\n continue;\n }\n }\n\n resources.push(doc);\n }\n\n // Sort by creation date (newest first)\n resources.sort((a, b) => {\n const aTime = a.dateCreated ? new Date(a.dateCreated).getTime() : 0;\n const bTime = b.dateCreated ? new Date(b.dateCreated).getTime() : 0;\n return bTime - aTime;\n });\n\n return resources;\n }\n\n /**\n * Add content previews to resources (for search results)\n * Retrieves and decodes the first 200 characters of each resource's primary representation\n */\n static async addContentPreviews(\n resources: ResourceDescriptor[],\n config: EnvironmentConfig\n ): Promise<Array<ResourceDescriptor & { content: string }>> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n return await Promise.all(\n resources.map(async (doc) => {\n try {\n const primaryRep = getPrimaryRepresentation(doc);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentPreview = decodeRepresentation(contentBuffer, primaryRep.mediaType).slice(0, 200);\n return { ...doc, content: contentPreview };\n }\n return { ...doc, content: '' };\n } catch {\n return { ...doc, content: '' };\n }\n })\n );\n }\n\n /**\n * Get full content for a resource\n * Retrieves and decodes the primary representation\n */\n static async getResourceContent(\n resource: ResourceDescriptor,\n config: EnvironmentConfig\n ): Promise<string | undefined> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n return undefined;\n }\n}\n","/**\n * Graph Context\n *\n * Provides graph database operations for resources and annotations.\n * All methods require graph traversal - must use graph database.\n */\n\nimport { getGraphDatabase } from '@semiont/graph';\nimport { resourceIdToURI } from '@semiont/core';\nimport type {\n ResourceId,\n EnvironmentConfig,\n GraphConnection,\n GraphPath,\n} from '@semiont/core';\nimport type { components } from '@semiont/core';\nimport { getResourceId, getResourceEntityTypes } from '@semiont/api-client';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface GraphNode {\n id: string;\n type: string;\n label: string;\n metadata: { entityTypes: string[] };\n}\n\nexport interface GraphEdge {\n source: string;\n target: string;\n type: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface GraphRepresentation {\n nodes: GraphNode[];\n edges: GraphEdge[];\n}\n\nexport class GraphContext {\n /**\n * Get all resources referencing this resource (backlinks)\n * Requires graph traversal - must use graph database\n */\n static async getBacklinks(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const graphDb = await getGraphDatabase(config);\n const resourceUri = resourceIdToURI(resourceId, config.services.backend!.publicURL);\n return await graphDb.getResourceReferencedBy(resourceUri);\n }\n\n /**\n * Find shortest path between two resources\n * Requires graph traversal - must use graph database\n */\n static async findPath(\n fromResourceId: ResourceId,\n toResourceId: ResourceId,\n config: EnvironmentConfig,\n maxDepth?: number\n ): Promise<GraphPath[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.findPath(fromResourceId, toResourceId, maxDepth);\n }\n\n /**\n * Get resource connections (graph edges)\n * Requires graph traversal - must use graph database\n */\n static async getResourceConnections(resourceId: ResourceId, config: EnvironmentConfig): Promise<GraphConnection[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.getResourceConnections(resourceId);\n }\n\n /**\n * Search resources by name (cross-resource query)\n * Requires full-text search - must use graph database\n */\n static async searchResources(query: string, config: EnvironmentConfig, limit?: number): Promise<ResourceDescriptor[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.searchResources(query, limit);\n }\n\n /**\n * Build graph representation with nodes and edges for a resource and its connections\n * Retrieves connections from graph and builds visualization-ready structure\n */\n static async buildGraphRepresentation(\n resourceId: ResourceId,\n maxRelated: number,\n config: EnvironmentConfig\n ): Promise<GraphRepresentation> {\n const graphDb = await getGraphDatabase(config);\n const publicURL = config.services.backend!.publicURL;\n const resourceUri = resourceIdToURI(resourceId, publicURL);\n\n // Get main resource\n const mainDoc = await graphDb.getResource(resourceUri);\n if (!mainDoc) {\n throw new Error('Resource not found');\n }\n\n // Get connections\n const connections = await graphDb.getResourceConnections(resourceId);\n const relatedDocs = connections.map(conn => conn.targetResource).slice(0, maxRelated - 1);\n\n // Build nodes\n const nodes = [\n {\n id: getResourceId(mainDoc),\n type: 'resource',\n label: mainDoc.name,\n metadata: { entityTypes: getResourceEntityTypes(mainDoc) },\n },\n ...relatedDocs.map(doc => ({\n id: getResourceId(doc),\n type: 'resource',\n label: doc.name,\n metadata: { entityTypes: getResourceEntityTypes(doc) },\n })),\n ].filter(node => node.id !== undefined) as GraphNode[];\n\n // Build edges\n const edges = connections\n .slice(0, maxRelated - 1)\n .map(conn => ({\n source: resourceId,\n target: getResourceId(conn.targetResource),\n type: conn.relationshipType || 'link',\n metadata: {},\n }))\n .filter(edge => edge.target !== undefined) as GraphEdge[];\n\n return { nodes, edges };\n }\n}\n","/**\n * LLM Context\n *\n * Builds comprehensive context for LLM processing of resources\n * Orchestrates: ResourceContext, GraphContext, AnnotationContext, and generation functions\n */\n\nimport { ResourceContext } from './resource-context';\nimport { GraphContext } from './graph-context';\nimport { AnnotationContext } from './annotation-context';\nimport { generateResourceSummary, generateReferenceSuggestions } from './generation/resource-generation';\nimport type { InferenceClient } from '@semiont/inference';\nimport { getResourceEntityTypes, getResourceId } from '@semiont/api-client';\nimport { resourceId as makeResourceId, type EnvironmentConfig, type ResourceId } from '@semiont/core';\nimport type { components } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype ResourceLLMContextResponse = components['schemas']['ResourceLLMContextResponse'];\n\nexport interface LLMContextOptions {\n depth: number;\n maxResources: number;\n includeContent: boolean;\n includeSummary: boolean;\n}\n\nexport class LLMContext {\n /**\n * Get comprehensive LLM context for a resource\n * Includes: main resource, related resources, annotations, graph, content, summary, references\n */\n static async getResourceContext(\n resourceId: ResourceId,\n options: LLMContextOptions,\n config: EnvironmentConfig,\n inferenceClient: InferenceClient\n ): Promise<ResourceLLMContextResponse> {\n // Get main resource from view storage\n const mainDoc = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!mainDoc) {\n throw new Error('Resource not found');\n }\n\n // Get content for main resource\n const mainContent = options.includeContent\n ? await ResourceContext.getResourceContent(mainDoc, config)\n : undefined;\n\n // Get graph representation (includes related resources and connections)\n const graph = await GraphContext.buildGraphRepresentation(\n resourceId,\n options.maxResources,\n config\n );\n\n // Extract related resources from graph nodes (excluding main resource)\n const relatedDocs: ResourceDescriptor[] = [];\n const resourceIdStr = resourceId.toString();\n for (const node of graph.nodes) {\n if (node.id !== resourceIdStr) {\n const relatedDoc = await ResourceContext.getResourceMetadata(makeResourceId(node.id), config);\n if (relatedDoc) {\n relatedDocs.push(relatedDoc);\n }\n }\n }\n\n // Get content for related resources\n const relatedResourcesContent: Record<string, string> = {};\n if (options.includeContent) {\n await Promise.all(\n relatedDocs.map(async (doc) => {\n const docId = getResourceId(doc);\n if (!docId) return;\n const content = await ResourceContext.getResourceContent(doc, config);\n if (content) {\n relatedResourcesContent[docId] = content;\n }\n })\n );\n }\n\n // Get annotations from view storage\n const annotations = await AnnotationContext.getAllAnnotations(resourceId, config);\n\n // Generate summary if requested\n const summary = options.includeSummary && mainContent\n ? await generateResourceSummary(\n mainDoc.name,\n mainContent,\n getResourceEntityTypes(mainDoc),\n inferenceClient\n )\n : undefined;\n\n // Generate reference suggestions if we have content\n const suggestedReferences = mainContent\n ? await generateReferenceSuggestions(mainContent, inferenceClient)\n : undefined;\n\n // Build response\n return {\n mainResource: mainDoc,\n relatedResources: relatedDocs,\n annotations,\n graph,\n ...(mainContent ? { mainResourceContent: mainContent } : {}),\n ...(options.includeContent ? { relatedResourcesContent } : {}),\n ...(summary ? { summary } : {}),\n ...(suggestedReferences ? { suggestedReferences } : {}),\n };\n }\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Fetch resource metadata and content\n * 2. Build AI prompts using MotivationPrompts\n * 3. Call AI inference\n * 4. Parse and validate results using MotivationParsers\n *\n * This is the high-level API for AI-powered annotation detection.\n * Workers and other consumers should use these methods instead of\n * implementing detection logic directly.\n */\n\nimport { ResourceContext } from './resource-context';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { InferenceClient } from '@semiont/inference';\nimport { MotivationPrompts } from './detection/motivation-prompts';\nimport {\n MotivationParsers,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from './detection/motivation-parsers';\nimport { getTagSchema, getSchemaCategory } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\nexport class AnnotationDetection {\n /**\n * Detect comments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for comment generation\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Array of validated comment matches\n */\n static async detectComments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<CommentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildCommentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 3000, // maxTokens: Higher than highlights/assessments due to comment text\n 0.4 // temperature: Slightly higher to allow creative context\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseComments(response, content);\n }\n\n /**\n * Detect highlights in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for highlight selection\n * @param density - Optional target number of highlights per 2000 words\n * @returns Array of validated highlight matches\n */\n static async detectHighlights(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n density?: number\n ): Promise<HighlightMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildHighlightPrompt(content, instructions, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 2000, // maxTokens: Lower than comments/assessments (no body text)\n 0.3 // temperature: Low for consistent importance judgments\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseHighlights(response, content);\n }\n\n /**\n * Detect assessments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for assessment generation\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Array of validated assessment matches\n */\n static async detectAssessments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<AssessmentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildAssessmentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 3000, // maxTokens: Higher for assessment text\n 0.3 // temperature: Lower for analytical consistency\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseAssessments(response, content);\n }\n\n /**\n * Detect tags in a resource for a specific category\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param schemaId - The tag schema identifier (e.g., \"irac\", \"imrad\")\n * @param category - The specific category to detect\n * @returns Array of validated tag matches\n */\n static async detectTags(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n schemaId: string,\n category: string\n ): Promise<TagMatch[]> {\n // Validate schema and category\n const schema = getTagSchema(schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${schemaId}`);\n }\n\n const categoryInfo = getSchemaCategory(schemaId, category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schemaId}`);\n }\n\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store (FULL content for structural analysis)\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt with schema and category information\n const prompt = MotivationPrompts.buildTagPrompt(\n content,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples\n );\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 4000, // maxTokens: Higher for full document analysis\n 0.2 // temperature: Lower for structural consistency\n );\n\n // 5. Parse response (without validation)\n const parsedTags = MotivationParsers.parseTags(response);\n\n // 6. Validate offsets and add category\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n\n /**\n * Load resource content from representation store\n * Helper method used by all detection methods\n *\n * @param resourceId - The resource ID to load\n * @param config - Environment configuration\n * @returns Resource content as string, or null if not available\n */\n private static async loadResourceContent(\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<string | null> {\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) return null;\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return null;\n\n // Only process text content\n const baseMediaType = primaryRep.mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType !== 'text/plain' && baseMediaType !== 'text/markdown') {\n return null;\n }\n\n if (!primaryRep.checksum || !primaryRep.mediaType) return null;\n\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n}\n","/**\n * Prompt builders for annotation detection motivations\n *\n * Provides static methods to build AI prompts for each Web Annotation motivation type.\n * Extracted from worker implementations to centralize prompt logic.\n */\n\nexport class MotivationPrompts {\n /**\n * Build a prompt for detecting comment-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Formatted prompt string\n */\n static buildCommentPrompt(\n content: string,\n instructions?: string,\n tone?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const toneGuidance = tone ? ` Use a ${tone} tone.` : '';\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} comments per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Add comments to passages in this text following these instructions:\n\n${instructions}${toneGuidance}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of comments. Each comment must have:\n- \"exact\": the exact text passage being commented on (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"comment\": your comment following the instructions above\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"the quarterly review meeting\", \"start\": 142, \"end\": 169, \"prefix\": \"We need to schedule \", \"suffix\": \" for next month.\", \"comment\": \"Who will lead this? Should we invite the external auditors?\"}\n]`;\n } else {\n // No specific instructions - fall back to explanatory/educational mode\n const toneGuidance = tone\n ? `\\n\\nTone: Use a ${tone} style in your comments.`\n : '';\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} comments per 2000 words`\n : `\\n- Aim for 3-8 comments per 2000 words (not too sparse or dense)`;\n\n prompt = `Identify passages in this text that would benefit from explanatory comments.\nFor each passage, provide contextual information, clarification, or background.${toneGuidance}\n\nGuidelines:\n- Select passages that reference technical terms, historical figures, complex concepts, or unclear references\n- Provide comments that ADD VALUE beyond restating the text\n- Focus on explanation, background, or connections to other ideas\n- Avoid obvious or trivial comments\n- Keep comments concise (1-3 sentences typically)${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of comments. Each comment should have:\n- \"exact\": the exact text passage being commented on (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"comment\": your explanatory comment (1-3 sentences, provide context/background/clarification)\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"Ouranos\", \"start\": 52, \"end\": 59, \"prefix\": \"In the beginning, \", \"suffix\": \" ruled the universe\", \"comment\": \"Ouranos (also spelled Uranus) is the primordial Greek deity personifying the sky. In Hesiod's Theogony, he is the son and husband of Gaia (Earth) and father of the Titans.\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting highlight-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param density - Optional target number of highlights per 2000 words\n * @returns Formatted prompt string\n */\n static buildHighlightPrompt(\n content: string,\n instructions?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} highlights per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Identify passages in this text to highlight following these instructions:\n\n${instructions}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of highlights. Each highlight must have:\n- \"exact\": the exact text passage to highlight (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"revenue grew 45% year-over-year\", \"start\": 142, \"end\": 174, \"prefix\": \"In Q3 2024, \", \"suffix\": \", exceeding all forecasts.\"}\n]`;\n } else {\n // No specific instructions - fall back to importance/salience mode\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} highlights per 2000 words`\n : `\\n- Aim for 3-8 highlights per 2000 words (be selective)`;\n\n prompt = `Identify passages in this text that merit highlighting for their importance or salience.\nFocus on content that readers should notice and remember.\n\nGuidelines:\n- Highlight key claims, findings, or conclusions\n- Highlight important definitions, terminology, or concepts\n- Highlight notable quotes or particularly striking statements\n- Highlight critical decisions, action items, or turning points\n- Select passages that are SIGNIFICANT, not just interesting\n- Avoid trivial or obvious content${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of highlights. Each highlight should have:\n- \"exact\": the exact text passage to highlight (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"we will discontinue support for legacy systems by March 2025\", \"start\": 52, \"end\": 113, \"prefix\": \"After careful consideration, \", \"suffix\": \". This decision affects\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting assessment-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Formatted prompt string\n */\n static buildAssessmentPrompt(\n content: string,\n instructions?: string,\n tone?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const toneGuidance = tone ? ` Use a ${tone} tone.` : '';\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} assessments per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Assess passages in this text following these instructions:\n\n${instructions}${toneGuidance}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of assessments. Each assessment must have:\n- \"exact\": the exact text passage being assessed (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"assessment\": your assessment following the instructions above\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"the quarterly revenue target\", \"start\": 142, \"end\": 169, \"prefix\": \"We established \", \"suffix\": \" for Q4 2024.\", \"assessment\": \"This target seems ambitious given market conditions. Consider revising based on recent trends.\"}\n]`;\n } else {\n // No specific instructions - fall back to analytical/evaluation mode\n const toneGuidance = tone\n ? `\\n\\nTone: Use a ${tone} style in your assessments.`\n : '';\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} assessments per 2000 words`\n : `\\n- Aim for 2-6 assessments per 2000 words (focus on key passages)`;\n\n prompt = `Identify passages in this text that merit critical assessment or evaluation.\nFor each passage, provide analysis of its validity, strength, or implications.${toneGuidance}\n\nGuidelines:\n- Select passages containing claims, arguments, conclusions, or assertions\n- Assess evidence quality, logical soundness, or practical implications\n- Provide assessments that ADD INSIGHT beyond restating the text\n- Focus on passages where evaluation would help readers form judgments\n- Keep assessments concise yet substantive (1-3 sentences typically)${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of assessments. Each assessment should have:\n- \"exact\": the exact text passage being assessed (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"assessment\": your analytical assessment (1-3 sentences, evaluate validity/strength/implications)\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"AI will replace most jobs by 2030\", \"start\": 52, \"end\": 89, \"prefix\": \"Many experts predict that \", \"suffix\": \", fundamentally reshaping\", \"assessment\": \"This claim lacks nuance and supporting evidence. Employment patterns historically show job transformation rather than wholesale replacement. The timeline appears speculative without specific sector analysis.\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting structural tags\n *\n * @param content - The full text content to analyze (NOT truncated for structural analysis)\n * @param category - The specific category to detect\n * @param schemaName - Human-readable schema name\n * @param schemaDescription - Schema description\n * @param schemaDomain - Schema domain\n * @param categoryDescription - Category description\n * @param categoryExamples - Example questions/guidance for this category\n * @returns Formatted prompt string\n */\n static buildTagPrompt(\n content: string,\n category: string,\n schemaName: string,\n schemaDescription: string,\n schemaDomain: string,\n categoryDescription: string,\n categoryExamples: string[]\n ): string {\n // Build prompt with schema context and category-specific guidance\n const prompt = `You are analyzing a text using the ${schemaName} framework.\n\nSchema: ${schemaDescription}\nDomain: ${schemaDomain}\n\nYour task: Identify passages that serve the structural role of \"${category}\".\n\nCategory: ${category}\nDescription: ${categoryDescription}\nKey questions:\n${categoryExamples.map(ex => `- ${ex}`).join('\\n')}\n\nGuidelines:\n- Focus on STRUCTURAL FUNCTION, not semantic content\n- A passage serves the \"${category}\" role if it performs this function in the document's structure\n- Look for passages that explicitly fulfill this role\n- Passages can be sentences, paragraphs, or sections\n- Aim for precision - only tag passages that clearly serve this structural role\n- Typical documents have 1-5 instances of each category (some may have 0)\n\nText to analyze:\n---\n${content}\n---\n\nReturn a JSON array of tags. Each tag should have:\n- \"exact\": the exact text passage (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"What duty did the defendant owe?\", \"start\": 142, \"end\": 175, \"prefix\": \"The central question is: \", \"suffix\": \" This question must be\"},\n {\"exact\": \"In tort law, a duty of care is established when...\", \"start\": 412, \"end\": 520, \"prefix\": \"Legal framework:\\\\n\", \"suffix\": \"\\\\n\\\\nApplying this standard\"}\n]`;\n\n return prompt;\n }\n}\n","/**\n * Response parsers for annotation detection motivations\n *\n * Provides static methods to parse and validate AI responses for each motivation type.\n * Includes offset validation and correction logic.\n * Extracted from worker implementations to centralize parsing logic.\n *\n * NOTE: These are static utility methods without logger access.\n * Console statements kept for debugging - consider adding logger parameter in future.\n */\n\nimport { validateAndCorrectOffsets } from '@semiont/api-client';\n\n/**\n * Represents a detected comment with validated position\n */\nexport interface CommentMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n comment: string;\n}\n\n/**\n * Represents a detected highlight with validated position\n */\nexport interface HighlightMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * Represents a detected assessment with validated position\n */\nexport interface AssessmentMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n assessment: string;\n}\n\n/**\n * Represents a detected tag with validated position\n */\nexport interface TagMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n category: string;\n}\n\nexport class MotivationParsers {\n /**\n * Parse and validate AI response for comment detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated comment matches\n */\n static parseComments(response: string, content: string): CommentMatch[] {\n try {\n // Clean up markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const parsed = JSON.parse(cleaned);\n\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Comment response is not an array');\n return [];\n }\n\n // Validate and filter\n const valid = parsed.filter((c: any) =>\n c &&\n typeof c.exact === 'string' &&\n typeof c.start === 'number' &&\n typeof c.end === 'number' &&\n typeof c.comment === 'string' &&\n c.comment.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid comments from ${parsed.length} total`);\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedComments: CommentMatch[] = [];\n\n for (const comment of valid) {\n try {\n const validated = validateAndCorrectOffsets(content, comment.start, comment.end, comment.exact);\n validatedComments.push({\n ...comment,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid comment \"${comment.exact}\":`, error);\n // Skip this comment - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedComments;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI comment response:', error);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for highlight detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated highlight matches\n */\n static parseHighlights(response: string, content: string): HighlightMatch[] {\n try {\n // Clean up response - remove markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```json') || cleaned.startsWith('```')) {\n cleaned = cleaned.slice(cleaned.indexOf('\\n') + 1);\n const endIndex = cleaned.lastIndexOf('```');\n if (endIndex !== -1) {\n cleaned = cleaned.slice(0, endIndex);\n }\n }\n\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Highlight response was not an array');\n return [];\n }\n\n // Validate and filter results\n const highlights = parsed.filter((h: any) =>\n h && typeof h.exact === 'string' &&\n typeof h.start === 'number' &&\n typeof h.end === 'number'\n );\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedHighlights: HighlightMatch[] = [];\n\n for (const highlight of highlights) {\n try {\n const validated = validateAndCorrectOffsets(content, highlight.start, highlight.end, highlight.exact);\n validatedHighlights.push({\n ...highlight,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid highlight \"${highlight.exact}\":`, error);\n // Skip this highlight - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedHighlights;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI highlight response:', error);\n console.error('Raw response:', response);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for assessment detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated assessment matches\n */\n static parseAssessments(response: string, content: string): AssessmentMatch[] {\n try {\n // Clean up response - remove markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```json') || cleaned.startsWith('```')) {\n cleaned = cleaned.slice(cleaned.indexOf('\\n') + 1);\n const endIndex = cleaned.lastIndexOf('```');\n if (endIndex !== -1) {\n cleaned = cleaned.slice(0, endIndex);\n }\n }\n\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Assessment response was not an array');\n return [];\n }\n\n // Validate and filter results\n const assessments = parsed.filter((a: any) =>\n a && typeof a.exact === 'string' &&\n typeof a.start === 'number' &&\n typeof a.end === 'number' &&\n typeof a.assessment === 'string'\n );\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedAssessments: AssessmentMatch[] = [];\n\n for (const assessment of assessments) {\n try {\n const validated = validateAndCorrectOffsets(content, assessment.start, assessment.end, assessment.exact);\n validatedAssessments.push({\n ...assessment,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid assessment \"${assessment.exact}\":`, error);\n // Skip this assessment - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedAssessments;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI assessment response:', error);\n console.error('Raw response:', response);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for tag detection\n * Note: Does NOT validate offsets - caller must do that with content\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @returns Array of tag matches (offsets not yet validated)\n */\n static parseTags(response: string): Omit<TagMatch, 'category'>[] {\n try {\n // Clean up markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const parsed = JSON.parse(cleaned);\n\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Tag response is not an array');\n return [];\n }\n\n // Validate and filter\n const valid = parsed.filter((t: any) =>\n t &&\n typeof t.exact === 'string' &&\n typeof t.start === 'number' &&\n typeof t.end === 'number' &&\n t.exact.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid tags from ${parsed.length} total`);\n\n return valid;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI tag response:', error);\n return [];\n }\n }\n\n /**\n * Validate tag offsets against content and add category\n * Helper for tag detection after initial parsing\n *\n * @param tags - Parsed tags without validated offsets\n * @param content - Original content to validate against\n * @param category - Category to assign to validated tags\n * @returns Array of validated tag matches\n */\n static validateTagOffsets(\n tags: Omit<TagMatch, 'category'>[],\n content: string,\n category: string\n ): TagMatch[] {\n const validatedTags: TagMatch[] = [];\n\n for (const tag of tags) {\n try {\n const validated = validateAndCorrectOffsets(content, tag.start, tag.end, tag.exact);\n validatedTags.push({\n ...tag,\n category,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid tag for category \"${category}\":`, error);\n // Skip this tag - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedTags;\n }\n}\n","// @semiont/make-meaning - Making meaning from resources\n// Transforms raw resources into meaningful, interconnected knowledge\n\n// Service (primary export)\nexport { startMakeMeaning } from './service';\nexport type { MakeMeaningService } from './service';\n\n// Bootstrap\nexport { bootstrapEntityTypes, resetBootstrap } from './bootstrap/entity-types';\n\n// Views\nexport { readEntityTypesProjection } from './views/entity-types-reader';\n\n// Graph Consumer\nexport { GraphDBConsumer } from './graph/consumer';\n\n// Resource operations\nexport { ResourceOperations } from './resource-operations';\nexport type { UpdateResourceInput, CreateResourceInput } from './resource-operations';\n\n// Annotation operations\nexport { AnnotationOperations } from './annotation-operations';\nexport type { CreateAnnotationResult, UpdateAnnotationBodyResult } from './annotation-operations';\n\n// Context assembly exports\nexport { ResourceContext } from './resource-context';\nexport type { ListResourcesFilters } from './resource-context';\nexport { AnnotationContext } from './annotation-context';\nexport type { BuildContextOptions } from './annotation-context';\nexport { GraphContext } from './graph-context';\nexport type { GraphNode, GraphEdge, GraphRepresentation } from './graph-context';\nexport { LLMContext } from './llm-context';\nexport type { LLMContextOptions } from './llm-context';\n\n// Detection exports\nexport { AnnotationDetection } from './annotation-assistance';\nexport { MotivationPrompts } from './detection/motivation-prompts';\nexport { MotivationParsers } from './detection/motivation-parsers';\nexport type {\n CommentMatch,\n HighlightMatch,\n AssessmentMatch,\n TagMatch,\n} from './detection/motivation-parsers';\nexport { extractEntities } from './detection/entity-extractor';\nexport type { ExtractedEntity } from './detection/entity-extractor';\n\n// Generation exports\nexport {\n generateResourceFromTopic,\n generateResourceSummary,\n generateReferenceSuggestions,\n} from './generation/resource-generation';\n\n// Job workers (exported for direct instantiation if needed)\nexport { CommentAnnotationWorker } from './jobs/comment-annotation-worker';\nexport { HighlightAnnotationWorker } from './jobs/highlight-annotation-worker';\nexport { AssessmentAnnotationWorker } from './jobs/assessment-annotation-worker';\nexport { TagAnnotationWorker } from './jobs/tag-annotation-worker';\nexport { ReferenceAnnotationWorker } from './jobs/reference-annotation-worker';\nexport { GenerationWorker } from './jobs/generation-worker';\n\n// Reasoning exports (future)\n// export { ResourceReasoning } from './resource-reasoning';\n\n// ID generation\nexport { generateUuid } from './id-generation';\n\n// Placeholder for initial build\nexport const PACKAGE_NAME = '@semiont/make-meaning';\nexport const VERSION = '0.1.0';\n"],"mappings":";AAYA,YAAYA,WAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,oBAAoB,4BAA6C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A,IACrE;AAGA,UAAM,SAAS,kBAAkB;AAAA,MAC/B;AAAA,MACA;AAAA,MACA,OAAO;AAAA,MACP,OAAO;AAAA,MACP,OAAO;AAAA,MACP,aAAa;AAAA,MACb,aAAa;AAAA,IACf;AAGA,UAAM,WAAW,MAAM,OAAO;AAAA,MAC5B;AAAA,MACA;AAAA;AAAA,MACA;AAAA;AAAA,IACF;AAGA,UAAM,aAAa,kBAAkB,UAAU,QAAQ;AAGvD,WAAO,kBAAkB,mBAAmB,YAAY,SAAS,QAAQ;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,aAAqB,oBACnBA,aACAC,SACwB;AACxB,UAAM,WAAW,MAAM,gBAAgB,oBAAoBD,aAAYC,OAAM;AAC7E,QAAI,CAAC,SAAU,QAAO;AAEtB,UAAM,aAAaC,0BAAyB,QAAQ;AACpD,QAAI,CAAC,WAAY,QAAO;AAGxB,UAAM,gBAAgB,WAAW,WAAW,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AACrE,QAAI,kBAAkB,gBAAgB,kBAAkB,iBAAiB;AACvE,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,WAAW,YAAY,CAAC,WAAW,UAAW,QAAO;AAE1D,UAAM,WAAWD,QAAO,SAAS,WAAY;AAC7C,UAAM,cAAcA,QAAO,WAAW;AACtC,UAAM,WAAW,IAAIE,+BAA8B,EAAE,SAAS,GAAG,WAAW;AAC5E,UAAM,gBAAgB,MAAM,SAAS,SAAS,WAAW,UAAU,WAAW,SAAS;AACvF,WAAOC,sBAAqB,eAAe,WAAW,SAAS;AAAA,EACjE;AACF;;;AG/LO,IAAM,eAAe;AACrB,IAAM,UAAU;","names":["path","FilesystemRepresentationStore","config","JobWorker","FilesystemRepresentationStore","response","JobWorker","config","FilesystemRepresentationStore","FilesystemViewStorage","JobWorker","generateAnnotationId","resourceIdToURI","JobWorker","config","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","resourceUri","annotationId","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","resourceUri","annotationId","d","b","UnsubscriptionErrorImpl","Subscription","empty","Subscriber","SafeSubscriber","Observable","observable","resolve","ObjectUnsubscribedErrorImpl","SubjectSubscription","SubjectSubscriber","Subject","observable","AnonymousSubject","GroupByOperator","GroupBySubscriber","GroupDurationSubscriber","GroupedObservable","InnerRefCountSubscription","MapOperator","MapSubscriber","iterator","observable","iterator","SimpleInnerSubscriber","SimpleOuterSubscriber","MergeMapOperator","MergeMapSubscriber","config","resourceUri","annotationUri","resourceId","userId","config","config","FilesystemRepresentationStore","fs","path","config","CREATION_METHODS","resourceId","userId","config","resourceId","CREATION_METHODS","generateAnnotationId","getTextPositionSelector","getTargetSource","annotationId","uriToResourceId","getInferenceClient","getTargetSelector","getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","FilesystemViewStorage","getEntityTypes","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","resourceId","config","annotationUri","resourceId","config","FilesystemViewStorage","FilesystemRepresentationStore","targetResourceId","getPrimaryRepresentation","decodeRepresentation","getTargetSelector","getInferenceClient","getEntityTypes","annotationId","userId","config","generateAnnotationId","getTextPositionSelector","uriToResourceId","annotationId","getTargetSource","resourceId","getGraphDatabase","resourceIdToURI","getResourceEntityTypes","resourceId","config","resourceUri","getResourceEntityTypes","getResourceId","makeResourceId","resourceId","config","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","validateAndCorrectOffsets","getTagSchema","resourceId","config","getPrimaryRepresentation","FilesystemRepresentationStore","decodeRepresentation"]}
1
+ {"version":3,"sources":["../src/service.ts","../src/jobs/reference-annotation-worker.ts","../src/detection/entity-extractor.ts","../src/jobs/generation-worker.ts","../src/generation/resource-generation.ts","../src/id-generation.ts","../src/jobs/highlight-annotation-worker.ts","../src/jobs/assessment-annotation-worker.ts","../src/jobs/comment-annotation-worker.ts","../src/jobs/tag-annotation-worker.ts","../../../node_modules/rxjs/node_modules/tslib/tslib.es6.js","../../../node_modules/rxjs/src/internal/util/isFunction.ts","../../../node_modules/rxjs/src/internal/config.ts","../../../node_modules/rxjs/src/internal/util/hostReportError.ts","../../../node_modules/rxjs/src/internal/Observer.ts","../../../node_modules/rxjs/src/internal/util/isObject.ts","../../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../../node_modules/rxjs/src/internal/Subscription.ts","../../../node_modules/rxjs/src/internal/symbol/rxSubscriber.ts","../../../node_modules/rxjs/src/internal/Subscriber.ts","../../../node_modules/rxjs/src/internal/util/canReportError.ts","../../../node_modules/rxjs/src/internal/util/toSubscriber.ts","../../../node_modules/rxjs/src/internal/util/identity.ts","../../../node_modules/rxjs/src/internal/util/pipe.ts","../../../node_modules/rxjs/src/internal/Observable.ts","../../../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts","../../../node_modules/rxjs/src/internal/SubjectSubscription.ts","../../../node_modules/rxjs/src/internal/Subject.ts","../../../node_modules/rxjs/src/internal/operators/groupBy.ts","../../../node_modules/rxjs/src/internal/util/subscribeToArray.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../../node_modules/rxjs/src/internal/operators/map.ts","../../../node_modules/rxjs/src/internal/util/subscribeToPromise.ts","../../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../../node_modules/rxjs/src/internal/util/subscribeToIterable.ts","../../../node_modules/rxjs/src/internal/util/subscribeToObservable.ts","../../../node_modules/rxjs/src/internal/util/isPromise.ts","../../../node_modules/rxjs/src/internal/util/subscribeTo.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../../node_modules/rxjs/src/internal/util/isIterable.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../../node_modules/rxjs/src/internal/observable/from.ts","../../../node_modules/rxjs/src/internal/innerSubscribe.ts","../../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../../node_modules/rxjs/src/internal/operators/concatMap.ts","../src/graph/consumer.ts","../src/bootstrap/entity-types.ts","../src/views/entity-types-reader.ts","../src/resource-operations.ts","../src/annotation-operations.ts","../src/annotation-context.ts","../src/resource-context.ts","../src/graph-context.ts","../src/llm-context.ts","../src/annotation-assistance.ts","../src/detection/motivation-prompts.ts","../src/detection/motivation-parsers.ts","../src/index.ts"],"sourcesContent":["/**\n * Make-Meaning Service\n *\n * Consolidates all meaning-making infrastructure:\n * - Job queue initialization\n * - Worker instantiation and startup\n * - Graph consumer (event-to-graph synchronization)\n *\n * Provides a clean interface similar to createEventStore():\n * const makeMeaning = await startMakeMeaning(config);\n */\n\nimport * as path from 'path';\nimport { JobQueue } from '@semiont/jobs';\nimport { createEventStore as createEventStoreCore, type EventStore } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore, type RepresentationStore } from '@semiont/content';\nimport type { EnvironmentConfig, Logger } from '@semiont/core';\nimport { EventBus } from '@semiont/core';\nimport { getInferenceClient, type InferenceClient } from '@semiont/inference';\nimport { getGraphDatabase, type GraphDatabase } from '@semiont/graph';\nimport { ReferenceAnnotationWorker } from './jobs/reference-annotation-worker';\nimport { GenerationWorker } from './jobs/generation-worker';\nimport { HighlightAnnotationWorker } from './jobs/highlight-annotation-worker';\nimport { AssessmentAnnotationWorker } from './jobs/assessment-annotation-worker';\nimport { CommentAnnotationWorker } from './jobs/comment-annotation-worker';\nimport { TagAnnotationWorker } from './jobs/tag-annotation-worker';\nimport { GraphDBConsumer } from './graph/consumer';\nimport { bootstrapEntityTypes } from './bootstrap/entity-types';\n\nexport interface MakeMeaningService {\n jobQueue: JobQueue;\n eventStore: EventStore;\n eventBus: EventBus;\n repStore: RepresentationStore;\n inferenceClient: InferenceClient;\n graphDb: GraphDatabase;\n workers: {\n detection: ReferenceAnnotationWorker;\n generation: GenerationWorker;\n highlight: HighlightAnnotationWorker;\n assessment: AssessmentAnnotationWorker;\n comment: CommentAnnotationWorker;\n tag: TagAnnotationWorker;\n };\n graphConsumer: GraphDBConsumer;\n stop: () => Promise<void>;\n}\n\nexport async function startMakeMeaning(config: EnvironmentConfig, eventBus: EventBus, logger: Logger): Promise<MakeMeaningService> {\n // 1. Validate configuration\n const configuredPath = config.services?.filesystem?.path;\n if (!configuredPath) {\n throw new Error('services.filesystem.path is required for make-meaning service');\n }\n\n const baseUrl = config.services?.backend?.publicURL;\n if (!baseUrl) {\n throw new Error('services.backend.publicURL is required for make-meaning service');\n }\n\n // Resolve basePath to absolute path\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n // 2. Initialize job queue\n const jobQueueLogger = logger.child({ component: 'job-queue' });\n const jobQueue = new JobQueue({ dataDir: basePath }, jobQueueLogger, eventBus);\n await jobQueue.initialize();\n\n // 3. Create shared event store with EventBus integration\n const eventStoreLogger = logger.child({ component: 'event-store' });\n const eventStore = createEventStoreCore(basePath, baseUrl, undefined, eventBus, eventStoreLogger);\n\n // 4. Bootstrap entity types (if projection doesn't exist)\n const bootstrapLogger = logger.child({ component: 'entity-types-bootstrap' });\n await bootstrapEntityTypes(eventStore, config, bootstrapLogger);\n\n // 5. Create shared representation store\n const repStoreLogger = logger.child({ component: 'representation-store' });\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot, repStoreLogger);\n\n // 6. Create inference client (shared across all workers)\n const inferenceLogger = logger.child({ component: 'inference-client' });\n const inferenceClient = await getInferenceClient(config, inferenceLogger);\n\n // 7. Create graph database connection\n const graphDb = await getGraphDatabase(config);\n\n // 8. Create child loggers for each component\n const detectionLogger = logger.child({ component: 'reference-detection-worker' });\n const generationLogger = logger.child({ component: 'generation-worker' });\n const highlightLogger = logger.child({ component: 'highlight-detection-worker' });\n const assessmentLogger = logger.child({ component: 'assessment-detection-worker' });\n const commentLogger = logger.child({ component: 'comment-detection-worker' });\n const tagLogger = logger.child({ component: 'tag-detection-worker' });\n const graphConsumerLogger = logger.child({ component: 'graph-consumer' });\n\n // 9. Start graph consumer\n const graphConsumer = new GraphDBConsumer(config, eventStore, graphDb, graphConsumerLogger);\n await graphConsumer.initialize();\n\n // 10. Instantiate workers with EventBus and logger\n const workers = {\n detection: new ReferenceAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, detectionLogger),\n generation: new GenerationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, generationLogger),\n highlight: new HighlightAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, highlightLogger),\n assessment: new AssessmentAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, assessmentLogger),\n comment: new CommentAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, commentLogger),\n tag: new TagAnnotationWorker(jobQueue, config, eventStore, inferenceClient, eventBus, tagLogger),\n };\n\n // 11. Start all workers (non-blocking)\n workers.detection.start().catch((error: unknown) => {\n detectionLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.generation.start().catch((error: unknown) => {\n generationLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.highlight.start().catch((error: unknown) => {\n highlightLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.assessment.start().catch((error: unknown) => {\n assessmentLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.comment.start().catch((error: unknown) => {\n commentLogger.error('Worker stopped unexpectedly', { error });\n });\n workers.tag.start().catch((error: unknown) => {\n tagLogger.error('Worker stopped unexpectedly', { error });\n });\n\n return {\n jobQueue,\n eventStore,\n eventBus,\n repStore,\n inferenceClient,\n graphDb,\n workers,\n graphConsumer,\n stop: async () => {\n logger.info('Stopping Make-Meaning service');\n await Promise.all([\n workers.detection.stop(),\n workers.generation.stop(),\n workers.highlight.stop(),\n workers.assessment.stop(),\n workers.comment.stop(),\n workers.tag.stop(),\n ]);\n await graphConsumer.stop();\n await graphDb.disconnect();\n logger.info('Make-Meaning service stopped');\n },\n };\n}\n","/**\n * Reference Detection Worker\n *\n * Processes detection jobs: runs AI inference to find entities in resources\n * and emits reference.created events for each detected entity.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, DetectionJob, JobQueue, RunningJob, DetectionParams, DetectionProgress, DetectionResult } from '@semiont/jobs';\nimport { ResourceContext } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus } from '@semiont/core';\nimport type { EnvironmentConfig, Logger, components } from '@semiont/core';\nimport { getPrimaryRepresentation, decodeRepresentation, validateAndCorrectOffsets } from '@semiont/api-client';\nimport { extractEntities } from '../detection/entity-extractor';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport type { InferenceClient } from '@semiont/inference';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface DetectedAnnotation {\n annotation: {\n selector: {\n start: number;\n end: number;\n exact: string;\n prefix?: string;\n suffix?: string;\n };\n entityTypes: string[];\n };\n}\n\nexport class ReferenceAnnotationWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'ReferenceAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'reference-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<DetectionResult> {\n if (job.metadata.type !== 'reference-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n return await this.processDetectionJob(job as RunningJob<DetectionParams, DetectionProgress>);\n }\n\n /**\n * Detect entity references in resource using AI\n * Self-contained implementation for reference detection\n *\n * Public for testing charset handling - see entity-detection-charset.test.ts\n */\n public async detectReferences(\n resource: ResourceDescriptor,\n entityTypes: string[],\n includeDescriptiveReferences: boolean = false\n ): Promise<DetectedAnnotation[]> {\n this.logger?.debug('Detecting entities', {\n resourceId: resource.id,\n entityTypes,\n includeDescriptiveReferences\n });\n\n const detectedAnnotations: DetectedAnnotation[] = [];\n\n // Get primary representation\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return detectedAnnotations;\n\n // Only process text content (check base media type, ignoring charset parameters)\n const mediaType = primaryRep.mediaType;\n const baseMediaType = mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType === 'text/plain' || baseMediaType === 'text/markdown') {\n // Load content from representation store using content-addressed lookup\n if (!primaryRep.checksum || !primaryRep.mediaType) return detectedAnnotations;\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const content = decodeRepresentation(contentBuffer, primaryRep.mediaType);\n\n // Use AI to extract entities (with optional anaphoric/cataphoric references)\n const extractedEntities = await extractEntities(content, entityTypes, this.inferenceClient, includeDescriptiveReferences, this.logger);\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n for (const entity of extractedEntities) {\n try {\n const validated = validateAndCorrectOffsets(\n content,\n entity.startOffset,\n entity.endOffset,\n entity.exact\n );\n\n const annotation: DetectedAnnotation = {\n annotation: {\n selector: {\n start: validated.start,\n end: validated.end,\n exact: validated.exact,\n prefix: validated.prefix,\n suffix: validated.suffix,\n },\n entityTypes: [entity.entityType],\n },\n };\n detectedAnnotations.push(annotation);\n } catch (error) {\n this.logger?.warn('Skipping invalid entity', { exact: entity.exact, error });\n // Skip this entity - AI hallucinated text that doesn't exist\n }\n }\n }\n\n return detectedAnnotations;\n }\n\n private async processDetectionJob(job: RunningJob<DetectionParams, DetectionProgress>): Promise<DetectionResult> {\n this.logger?.info('Processing detection job', { resourceId: job.params.resourceId, jobId: job.metadata.id });\n this.logger?.debug('Entity types to detect', { entityTypes: job.params.entityTypes });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n let totalFound = 0;\n let totalEmitted = 0;\n let totalErrors = 0;\n\n // Create updated job with initial progress\n let updatedJob: RunningJob<DetectionParams, DetectionProgress> = {\n ...job,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: 0,\n entitiesFound: 0,\n entitiesEmitted: 0\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each entity type\n for (let i = 0; i < job.params.entityTypes.length; i++) {\n const entityType = job.params.entityTypes[i];\n\n if (!entityType) continue;\n\n this.logger?.info('Detecting entity type', {\n entityType,\n progress: `${i + 1}/${job.params.entityTypes.length}`\n });\n\n // Emit progress BEFORE inference call for immediate user feedback\n updatedJob = {\n ...updatedJob,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: i,\n currentEntityType: entityType,\n entitiesFound: totalFound,\n entitiesEmitted: totalEmitted\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Detect entities using AI (loads content from filesystem internally)\n // This is where the latency is - user now has feedback that work started\n const detectedAnnotations = await this.detectReferences(resource, [entityType], job.params.includeDescriptiveReferences);\n\n totalFound += detectedAnnotations.length;\n this.logger?.info('Found entities', { entityType, count: detectedAnnotations.length });\n\n // Emit events for each detected entity\n // This happens INDEPENDENT of any HTTP client!\n for (let idx = 0; idx < detectedAnnotations.length; idx++) {\n const detected = detectedAnnotations[idx];\n\n if (!detected) {\n this.logger?.warn('Skipping undefined entity', { index: idx });\n continue;\n }\n\n let referenceId: string;\n try {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n referenceId = generateAnnotationId(backendUrl);\n } catch (error) {\n this.logger?.error('Failed to generate annotation ID', { error });\n throw new Error('Configuration error: Backend publicURL not set');\n }\n\n try {\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotation: {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n id: referenceId,\n motivation: 'linking' as const,\n target: {\n source: resourceIdToURI(job.params.resourceId, this.config.services.backend!.publicURL), // Convert to full URI\n selector: [\n {\n type: 'TextPositionSelector',\n start: detected.annotation.selector.start,\n end: detected.annotation.selector.end,\n },\n {\n type: 'TextQuoteSelector',\n exact: detected.annotation.selector.exact,\n ...(detected.annotation.selector.prefix && { prefix: detected.annotation.selector.prefix }),\n ...(detected.annotation.selector.suffix && { suffix: detected.annotation.selector.suffix }),\n },\n ],\n },\n body: (detected.annotation.entityTypes || []).map(et => ({\n type: 'TextualBody' as const,\n value: et,\n purpose: 'tagging' as const,\n })),\n modified: new Date().toISOString(),\n },\n },\n });\n\n totalEmitted++;\n\n if ((idx + 1) % 10 === 0 || idx === detectedAnnotations.length - 1) {\n this.logger?.debug('Emitted events for entity type', {\n entityType,\n emitted: idx + 1,\n total: detectedAnnotations.length\n });\n }\n\n } catch (error) {\n totalErrors++;\n this.logger?.error('Failed to emit event', { referenceId, error });\n // Continue processing other entities even if one fails\n }\n }\n\n this.logger?.info('Completed entity type processing', {\n entityType,\n found: detectedAnnotations.length,\n emitted: detectedAnnotations.length - (totalErrors - (totalFound - totalEmitted))\n });\n\n // Update progress after processing this entity type\n updatedJob = {\n ...updatedJob,\n progress: {\n totalEntityTypes: job.params.entityTypes.length,\n processedEntityTypes: i + 1,\n currentEntityType: entityType,\n entitiesFound: totalFound,\n entitiesEmitted: totalEmitted\n }\n };\n await this.updateJobProgress(updatedJob);\n }\n\n this.logger?.info('Detection complete', { totalFound, totalEmitted, totalErrors });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n totalFound,\n totalEmitted,\n errors: totalErrors\n };\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event (domain + progress)\n */\n protected override async emitCompletionEvent(\n job: RunningJob<DetectionParams, DetectionProgress>,\n result: DetectionResult\n ): Promise<void> {\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'reference-annotation',\n result,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(job.params.resourceId);\n this.logger?.debug('[EventBus] Emitting job:completed to resource-scoped bus', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n resourceBus.get('job:completed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.completed' }>);\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'reference-annotation') {\n // Type narrowing: job is FailedJob<DetectionParams>\n const detJob = job as DetectionJob;\n\n const errorMessage = 'Entity detection failed. Please try again later.';\n\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n error: errorMessage,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(detJob.params.resourceId);\n this.logger?.debug('[EventBus] Emitting job:failed to resource-scoped bus', {\n resourceId: detJob.params.resourceId,\n jobId: detJob.metadata.id\n });\n resourceBus.get('job:failed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.failed' }>);\n }\n }\n\n /**\n * Update job progress and emit events to Event Store and EventBus\n * Overrides base class to emit both domain events and progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for detection jobs\n if (job.metadata.type !== 'reference-annotation') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const detJob = job as RunningJob<DetectionParams, DetectionProgress>;\n\n const baseEvent = {\n resourceId: detJob.params.resourceId,\n userId: detJob.metadata.userId,\n version: 1,\n };\n\n // Determine update type based on progress state\n const isFirstUpdate = detJob.progress.processedEntityTypes === 0 && !detJob.progress.currentEntityType;\n\n // \"Before processing\" updates are emitted when we're about to START an entity type\n // They have processedEntityTypes < totalEntityTypes (not done yet) and currentEntityType set\n // The key distinction: if the currentEntityType matches the NEXT entity to process (not yet in processed count),\n // then this is a \"before\" update that should only emit ephemeral progress, not a domain event\n const currentIndex = detJob.progress.currentEntityType\n ? detJob.params.entityTypes.findIndex(et => et === detJob.progress.currentEntityType)\n : -1;\n const isBeforeProcessing = currentIndex !== -1 && detJob.progress.processedEntityTypes === currentIndex;\n\n // Get resource-scoped EventBus for progress events\n const resourceBus = this.eventBus.scope(detJob.params.resourceId);\n this.logger?.debug('[EventBus] Scoping to resourceId', { resourceId: detJob.params.resourceId });\n\n if (isFirstUpdate) {\n // First progress update - emit job.started (domain event)\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n totalSteps: detJob.params.entityTypes.length,\n },\n });\n\n // ALSO emit initial mark:progress for immediate frontend feedback\n this.logger?.debug('[EventBus] Emitting initial mark:progress', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType\n });\n resourceBus.get('mark:progress').next({\n status: 'started',\n message: detJob.progress.currentEntityType\n ? `Starting ${detJob.progress.currentEntityType}...`\n : 'Starting detection...',\n currentEntityType: detJob.progress.currentEntityType,\n percentage: 0,\n });\n } else if (isBeforeProcessing) {\n // Before processing an entity type - only emit ephemeral mark:progress (no domain event)\n // This provides immediate UX feedback that we're starting work on this entity type\n const percentage = 0; // Starting this entity type\n this.logger?.debug('[EventBus] Emitting mark:progress (before processing)', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType\n });\n resourceBus.get('mark:progress').next({\n status: 'scanning',\n message: `Starting ${detJob.progress.currentEntityType}...`,\n currentEntityType: detJob.progress.currentEntityType,\n percentage,\n });\n } else {\n // After processing an entity type - emit job.progress (domain event)\n const percentage = Math.round((detJob.progress.processedEntityTypes / detJob.progress.totalEntityTypes) * 100);\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: detJob.metadata.id,\n jobType: detJob.metadata.type,\n percentage,\n currentStep: detJob.progress.currentEntityType,\n processedSteps: detJob.progress.processedEntityTypes,\n totalSteps: detJob.progress.totalEntityTypes,\n foundCount: detJob.progress.entitiesFound,\n },\n });\n\n // PROGRESS EVENT: Emit mark:progress directly to EventBus (ephemeral)\n this.logger?.debug('[EventBus] Emitting mark:progress', {\n resourceId: detJob.params.resourceId,\n currentEntityType: detJob.progress.currentEntityType,\n percentage\n });\n resourceBus.get('mark:progress').next({\n status: 'scanning',\n message: `Processing ${detJob.progress.currentEntityType}`,\n currentEntityType: detJob.progress.currentEntityType,\n percentage,\n });\n }\n }\n}\n","import type { InferenceClient } from '@semiont/inference';\nimport type { Logger } from '@semiont/core';\n\n/**\n * Entity reference extracted from text\n */\nexport interface ExtractedEntity {\n exact: string; // The actual text span\n entityType: string; // The detected entity type\n startOffset: number; // Character offset where entity starts\n endOffset: number; // Character offset where entity ends\n prefix?: string; // Text immediately before entity (for disambiguation)\n suffix?: string; // Text immediately after entity (for disambiguation)\n}\n\n/**\n * Extract entity references from text using AI\n *\n * @param text - The text to analyze\n * @param entityTypes - Array of entity types to detect (optionally with examples)\n * @param client - Inference client for AI operations\n * @param includeDescriptiveReferences - Include anaphoric/cataphoric references (default: false)\n * @param logger - Optional logger for debugging entity extraction\n * @returns Array of extracted entities with their character offsets\n */\nexport async function extractEntities(\n exact: string,\n entityTypes: string[] | { type: string; examples?: string[] }[],\n client: InferenceClient,\n includeDescriptiveReferences: boolean = false,\n logger?: Logger\n): Promise<ExtractedEntity[]> {\n\n // Format entity types for the prompt\n const entityTypesDescription = entityTypes.map(et => {\n if (typeof et === 'string') {\n return et;\n }\n return et.examples && et.examples.length > 0\n ? `${et.type} (examples: ${et.examples.slice(0, 3).join(', ')})`\n : et.type;\n }).join(', ');\n\n // Build prompt with optional support for anaphoric/cataphoric references\n // Anaphora: references that point backward (e.g., \"John arrived. He was tired.\")\n // Cataphora: references that point forward (e.g., \"When she arrived, Mary was surprised.\")\n // When enabled, include substantive descriptive references beyond simple pronouns\n const descriptiveReferenceGuidance = includeDescriptiveReferences\n ? `\nInclude both:\n- Direct mentions (names, proper nouns)\n- Descriptive references (substantive phrases that refer to entities)\n\nFor descriptive references, include:\n- Definite descriptions: \"the Nobel laureate\", \"the tech giant\", \"the former president\"\n- Role-based references: \"the CEO\", \"the physicist\", \"the author\", \"the owner\", \"the contractor\"\n- Epithets with context: \"the Cupertino-based company\", \"the iPhone maker\"\n- References to entities even when identity is unknown or unspecified\n\nDo NOT include:\n- Simple pronouns alone: he, she, it, they, him, her, them\n- Generic determiners alone: this, that, these, those\n- Possessives without substance: his, her, their, its\n\nExamples:\n- For \"Marie Curie\", include \"the Nobel laureate\" and \"the physicist\" but NOT \"she\"\n- For an unknown person, include \"the owner\" or \"the contractor\" (role-based references count even when identity is unspecified)\n`\n : `\nFind direct mentions only (names, proper nouns). Do not include pronouns or descriptive references.\n`;\n\n const prompt = `Identify entity references in the following text. Look for mentions of: ${entityTypesDescription}.\n${descriptiveReferenceGuidance}\nText to analyze:\n\"\"\"\n${exact}\n\"\"\"\n\nReturn ONLY a JSON array of entities found. Each entity should have:\n- exact: the exact text span from the input\n- entityType: one of the provided entity types\n- startOffset: character position where the entity starts (0-indexed)\n- endOffset: character position where the entity ends\n- prefix: up to 32 characters of text immediately before the entity (helps identify correct occurrence)\n- suffix: up to 32 characters of text immediately after the entity (helps identify correct occurrence)\n\nReturn empty array [] if no entities found.\nDo not include markdown formatting or code fences, just the raw JSON array.\n\nExample output:\n[{\"exact\":\"Alice\",\"entityType\":\"Person\",\"startOffset\":0,\"endOffset\":5,\"prefix\":\"\",\"suffix\":\" went to\"},{\"exact\":\"Paris\",\"entityType\":\"Location\",\"startOffset\":20,\"endOffset\":25,\"prefix\":\"went to \",\"suffix\":\" yesterday\"}]`;\n\n logger?.debug('Sending entity extraction request', { entityTypes: entityTypesDescription });\n const response = await client.generateTextWithMetadata(\n prompt,\n 4000, // Increased to handle many entities without truncation\n 0.3 // Lower temperature for more consistent extraction\n );\n logger?.debug('Got entity extraction response', { responseLength: response.text.length });\n\n try {\n // Clean up response if wrapped in markdown\n let jsonStr = response.text.trim();\n if (jsonStr.startsWith('```')) {\n jsonStr = jsonStr.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const entities = JSON.parse(jsonStr);\n logger?.debug('Parsed entities from AI response', { count: entities.length });\n\n // Check if response was truncated - this is an ERROR condition\n if (response.stopReason === 'max_tokens') {\n const errorMsg = `AI response truncated: Found ${entities.length} entities but response hit max_tokens limit. Increase max_tokens or reduce resource size.`;\n logger?.error(errorMsg);\n throw new Error(errorMsg);\n }\n\n // Validate and fix offsets\n return entities.map((entity: any, idx: number) => {\n let startOffset = entity.startOffset;\n let endOffset = entity.endOffset;\n\n logger?.debug('Processing entity', {\n index: idx + 1,\n total: entities.length,\n type: entity.entityType,\n text: entity.exact,\n offsetsFromAI: `[${startOffset}:${endOffset}]`\n });\n\n // Verify the offsets are correct by checking if the text matches\n const extractedText = exact.substring(startOffset, endOffset);\n\n // If the extracted text doesn't match, find the correct position using context\n if (extractedText !== entity.exact) {\n logger?.warn('Offset mismatch detected', {\n expected: entity.exact,\n foundAtOffsets: `[${startOffset}:${endOffset}]`,\n foundText: extractedText\n });\n\n // Show context around the AI-provided offset\n const contextStart = Math.max(0, startOffset - 50);\n const contextEnd = Math.min(exact.length, endOffset + 50);\n const contextBefore = exact.substring(contextStart, startOffset);\n const contextAfter = exact.substring(endOffset, contextEnd);\n logger?.debug('Context around AI offset', {\n before: contextBefore,\n extracted: extractedText,\n after: contextAfter\n });\n\n logger?.debug('Searching for exact match in resource');\n\n // Try to find using prefix/suffix context if provided\n let found = false;\n if (entity.prefix || entity.suffix) {\n logger?.debug('Using LLM-provided context for disambiguation', {\n prefix: entity.prefix,\n suffix: entity.suffix\n });\n\n // Search for all occurrences and find the one with matching context\n let searchPos = 0;\n while ((searchPos = exact.indexOf(entity.exact, searchPos)) !== -1) {\n const candidatePrefix = exact.substring(Math.max(0, searchPos - 32), searchPos);\n const candidateSuffix = exact.substring(\n searchPos + entity.exact.length,\n Math.min(exact.length, searchPos + entity.exact.length + 32)\n );\n\n // Check if context matches (allowing for partial matches at boundaries)\n const prefixMatch = !entity.prefix || candidatePrefix.endsWith(entity.prefix);\n const suffixMatch = !entity.suffix || candidateSuffix.startsWith(entity.suffix);\n\n if (prefixMatch && suffixMatch) {\n logger?.debug('Found match using context', {\n offset: searchPos,\n offsetDiff: searchPos - startOffset,\n candidatePrefix,\n candidateSuffix\n });\n startOffset = searchPos;\n endOffset = searchPos + entity.exact.length;\n found = true;\n break;\n }\n\n searchPos++;\n }\n\n if (!found) {\n logger?.warn('No occurrence found with matching context', { text: entity.exact });\n }\n }\n\n // Fallback to first occurrence if context didn't help\n if (!found) {\n const index = exact.indexOf(entity.exact);\n if (index !== -1) {\n logger?.warn('Using first occurrence', {\n text: entity.exact,\n offset: index,\n offsetDiff: index - startOffset\n });\n startOffset = index;\n endOffset = index + entity.exact.length;\n } else {\n logger?.error('Cannot find entity anywhere in resource', {\n text: entity.exact,\n resourceStart: exact.substring(0, 200)\n });\n // If we still can't find it, skip this entity\n return null;\n }\n }\n } else {\n logger?.debug('Offsets correct', { text: entity.exact });\n }\n\n return {\n exact: entity.exact,\n entityType: entity.entityType,\n startOffset: startOffset,\n endOffset: endOffset,\n prefix: entity.prefix,\n suffix: entity.suffix\n };\n }).filter((entity: ExtractedEntity | null): entity is ExtractedEntity => {\n // Filter out nulls and ensure we have valid offsets\n if (entity === null) {\n logger?.debug('Filtered entity: null');\n return false;\n }\n if (entity.startOffset === undefined || entity.endOffset === undefined) {\n logger?.warn('Filtered entity: missing offsets', { text: entity.exact });\n return false;\n }\n if (entity.startOffset < 0) {\n logger?.warn('Filtered entity: negative startOffset', {\n text: entity.exact,\n startOffset: entity.startOffset\n });\n return false;\n }\n if (entity.endOffset > exact.length) {\n logger?.warn('Filtered entity: endOffset exceeds text length', {\n text: entity.exact,\n endOffset: entity.endOffset,\n textLength: exact.length\n });\n return false;\n }\n\n // Verify the text at the offsets matches\n const extractedText = exact.substring(entity.startOffset, entity.endOffset);\n if (extractedText !== entity.exact) {\n logger?.warn('Filtered entity: offset mismatch', {\n expected: entity.exact,\n got: extractedText,\n offsets: `[${entity.startOffset}:${entity.endOffset}]`\n });\n return false;\n }\n\n logger?.debug('Accepted entity', {\n text: entity.exact,\n offsets: `[${entity.startOffset}:${entity.endOffset}]`\n });\n return true;\n });\n } catch (error) {\n logger?.error('Failed to parse entity extraction response', {\n error: error instanceof Error ? error.message : String(error)\n });\n return [];\n }\n}","/**\n * Generation Worker\n *\n * Processes generation jobs: runs AI inference to generate new resources\n * and emits resource.created and annotation.body.updated events.\n *\n * This worker is INDEPENDENT of HTTP clients - it just processes jobs and emits events.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, JobQueue, RunningJob, GenerationParams, YieldProgress, GenerationResult, GenerationJob } from '@semiont/jobs';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { ResourceContext } from '..';\nimport { generateResourceFromTopic } from '../generation/resource-generation';\nimport { resourceUri, annotationUri, EventBus, type Logger } from '@semiont/core';\nimport { getTargetSelector, getExactText } from '@semiont/api-client';\nimport { getEntityTypes } from '@semiont/ontology';\nimport {\n CREATION_METHODS,\n type BodyOperation,\n resourceId,\n annotationId,\n} from '@semiont/core';\nimport { generateUuid } from '../id-generation';\nimport { EventStore } from '@semiont/event-sourcing';\nimport type { EnvironmentConfig } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class GenerationWorker extends JobWorker {\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'GenerationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'generation';\n }\n\n protected async executeJob(job: AnyJob): Promise<GenerationResult> {\n if (job.metadata.type !== 'generation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n return await this.processGenerationJob(job as RunningJob<GenerationParams, YieldProgress>);\n }\n\n private async processGenerationJob(job: RunningJob<GenerationParams, YieldProgress>): Promise<GenerationResult> {\n this.logger?.info('Processing generation job', {\n referenceId: job.params.referenceId,\n jobId: job.metadata.id\n });\n\n const basePath = this.config.services.filesystem!.path;\n const projectRoot = this.config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Update progress: fetching\n let updatedJob: RunningJob<GenerationParams, YieldProgress> = {\n ...job,\n progress: {\n stage: 'fetching',\n percentage: 20,\n message: 'Fetching source resource...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Fetch annotation from view storage\n // TODO: Once AnnotationContext is consolidated, use it here\n const { FilesystemViewStorage } = await import('@semiont/event-sourcing');\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(job.params.sourceResourceId);\n if (!view) {\n throw new Error(`Resource ${job.params.sourceResourceId} not found`);\n }\n const projection = view.annotations;\n\n // Construct full annotation URI for comparison\n const expectedAnnotationUri = `${this.config.services.backend!.publicURL}/annotations/${job.params.referenceId}`;\n const annotation = projection.annotations.find((a: any) =>\n a.id === expectedAnnotationUri && a.motivation === 'linking'\n );\n\n if (!annotation) {\n throw new Error(`Annotation ${job.params.referenceId} not found in resource ${job.params.sourceResourceId}`);\n }\n\n const sourceResource = await ResourceContext.getResourceMetadata(job.params.sourceResourceId, this.config);\n if (!sourceResource) {\n throw new Error(`Source resource ${job.params.sourceResourceId} not found`);\n }\n\n // Determine resource name\n const targetSelector = getTargetSelector(annotation.target);\n const resourceName = job.params.title || (targetSelector ? getExactText(targetSelector) : '') || 'New Resource';\n this.logger?.info('Generating resource', { resourceName });\n\n // Verify context is provided (required for generation)\n if (!job.params.context) {\n throw new Error('Generation context is required but was not provided in job');\n }\n this.logger?.debug('Using pre-fetched context', {\n beforeLength: job.params.context.sourceContext?.before?.length || 0,\n selectedLength: job.params.context.sourceContext?.selected?.length || 0,\n afterLength: job.params.context.sourceContext?.after?.length || 0\n });\n\n // Update progress: generating (skip fetching context since it's already in job)\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 40,\n message: 'Creating content with AI...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Generate content using AI with context from job\n const prompt = job.params.prompt || `Create a comprehensive resource about \"${resourceName}\"`;\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes({ body: annotation.body });\n\n const generatedContent = await generateResourceFromTopic(\n resourceName,\n job.params.entityTypes || annotationEntityTypes,\n this.inferenceClient,\n prompt,\n job.params.language,\n job.params.context, // NEW - context from job (passed from modal)\n job.params.temperature, // NEW - from job\n job.params.maxTokens // NEW - from job\n );\n\n this.logger?.info('Content generated', { contentLength: generatedContent.content.length });\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'generating',\n percentage: 70,\n message: 'Content ready, creating resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Generate resource ID\n const rId = resourceId(generateUuid());\n\n // Update progress: creating\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 85,\n message: 'Saving resource...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Save content to RepresentationStore\n const storedRep = await repStore.store(Buffer.from(generatedContent.content), {\n mediaType: 'text/markdown',\n rel: 'original',\n });\n this.logger?.info('Saved resource representation', { resourceId: rId });\n\n // Emit resource.created event\n await this.eventStore.appendEvent({\n type: 'resource.created',\n resourceId: rId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n name: resourceName,\n format: 'text/markdown',\n contentChecksum: storedRep.checksum,\n creationMethod: CREATION_METHODS.GENERATED,\n entityTypes: job.params.entityTypes || annotationEntityTypes,\n language: job.params.language,\n isDraft: true,\n generatedFrom: job.params.referenceId,\n generationPrompt: undefined, // Could be added if we track the prompt\n },\n });\n this.logger?.info('Emitted resource.created event', { resourceId: rId });\n\n // Update progress: linking\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 95,\n message: 'Linking reference...'\n }\n };\n this.logger?.debug('Generation progress', { stage: updatedJob.progress.stage, message: updatedJob.progress.message });\n await this.updateJobProgress(updatedJob);\n\n // Emit annotation.body.updated event to link the annotation to the new resource\n // Build full resource URI for the annotation body\n const newResourceUri = resourceUri(`${this.config.services.backend!.publicURL}/resources/${rId}`);\n\n const operations: BodyOperation[] = [{\n op: 'add',\n item: {\n type: 'SpecificResource',\n source: newResourceUri,\n purpose: 'linking',\n },\n }];\n\n // Extract annotation ID from full URI (format: http://host/annotations/{id})\n const annotationIdSegment = job.params.referenceId.split('/').pop()!;\n\n await this.eventStore.appendEvent({\n type: 'annotation.body.updated',\n resourceId: job.params.sourceResourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n annotationId: annotationId(annotationIdSegment),\n operations,\n },\n });\n this.logger?.info('Emitted annotation.body.updated event', {\n referenceId: job.params.referenceId,\n targetResourceId: rId\n });\n\n // Final progress update\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'linking',\n percentage: 100,\n message: 'Complete!'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n this.logger?.info('Generation complete', { createdResourceId: rId });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n resourceId: rId,\n resourceName: resourceName\n };\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event with resultResourceId\n */\n protected override async emitCompletionEvent(\n job: RunningJob<GenerationParams, YieldProgress>,\n result: GenerationResult\n ): Promise<void> {\n // DOMAIN EVENT: Write to EventStore (auto-publishes to global EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.sourceResourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'generation',\n resultResourceId: result.resourceId,\n annotationUri: annotationUri(`${this.config.services.backend!.publicURL}/annotations/${job.params.referenceId}`),\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(job.params.sourceResourceId);\n this.logger?.debug('[EventBus] Emitting job:completed to resource-scoped bus', {\n resourceId: job.params.sourceResourceId,\n jobId: job.metadata.id\n });\n resourceBus.get('job:completed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.completed' }>);\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'generation') {\n // Type narrowing: job is FailedJob<GenerationParams>\n const genJob = job as GenerationJob;\n\n const errorMessage = 'Resource generation failed. Please try again later.';\n\n // DOMAIN EVENT: Write to EventStore (auto-publishes to EventBus)\n const storedEvent = await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: genJob.params.sourceResourceId,\n userId: genJob.metadata.userId,\n version: 1,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n error: errorMessage,\n },\n });\n\n // ALSO emit to resource-scoped EventBus for SSE streams\n const resourceBus = this.eventBus.scope(genJob.params.sourceResourceId);\n this.logger?.debug('[EventBus] Emitting job:failed to resource-scoped bus', {\n resourceId: genJob.params.sourceResourceId,\n jobId: genJob.metadata.id\n });\n resourceBus.get('job:failed').next(storedEvent.event as Extract<typeof storedEvent.event, { type: 'job.failed' }>);\n }\n }\n\n /**\n * Update job progress and emit events to Event Store\n * Overrides base class to also emit job progress events\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update job queue\n await super.updateJobProgress(job);\n\n // Emit events for generation jobs\n if (job.metadata.type !== 'generation') {\n return;\n }\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const genJob = job as RunningJob<GenerationParams, YieldProgress>;\n\n const baseEvent = {\n resourceId: genJob.params.sourceResourceId,\n userId: genJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(genJob.params.sourceResourceId);\n\n // Emit appropriate event based on progress stage\n if (genJob.progress.stage === 'fetching' && genJob.progress.percentage === 20) {\n // First progress update - emit job.started\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n totalSteps: 5, // fetching, generating, creating, linking, complete\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: genJob.metadata.id,\n jobType: genJob.metadata.type,\n currentStep: genJob.progress.stage,\n percentage: genJob.progress.percentage,\n message: genJob.progress.message,\n },\n });\n resourceBus.get('yield:progress').next({\n status: genJob.progress.stage as 'fetching' | 'generating' | 'creating',\n referenceId: genJob.params.referenceId,\n sourceResourceId: genJob.params.sourceResourceId,\n percentage: genJob.progress.percentage,\n message: genJob.progress.message\n });\n }\n }\n}\n","/**\n * Resource Generation Functions\n *\n * Application-specific resource generation logic including:\n * - Markdown resource generation from topics\n * - Resource summary generation\n * - Reference suggestion generation\n * - Language handling and template processing\n *\n */\n\nimport { getLocaleEnglishName } from '@semiont/api-client';\nimport type { YieldContext, Logger } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\n\n\nfunction getLanguageName(locale: string): string {\n return getLocaleEnglishName(locale) || locale;\n}\n\n/**\n * Generate resource content using inference\n */\nexport async function generateResourceFromTopic(\n topic: string,\n entityTypes: string[],\n client: InferenceClient,\n userPrompt?: string,\n locale?: string,\n context?: YieldContext,\n temperature?: number,\n maxTokens?: number,\n logger?: Logger\n): Promise<{ title: string; content: string }> {\n logger?.debug('Generating resource from topic', {\n topicPreview: topic.substring(0, 100),\n entityTypes,\n hasUserPrompt: !!userPrompt,\n locale,\n hasContext: !!context,\n temperature,\n maxTokens\n });\n\n // Use provided values or defaults\n const finalTemperature = temperature ?? 0.7;\n const finalMaxTokens = maxTokens ?? 500;\n\n // Determine language instruction\n const languageInstruction = locale && locale !== 'en'\n ? `\\n\\nIMPORTANT: Write the entire resource in ${getLanguageName(locale)}.`\n : '';\n\n // Build context section if available\n let contextSection = '';\n if (context?.sourceContext) {\n const { before, selected, after } = context.sourceContext;\n contextSection = `\\n\\nSource document context:\n---\n${before ? `...${before}` : ''}\n**[${selected}]**\n${after ? `${after}...` : ''}\n---\n`;\n }\n\n // Simple, direct prompt - just ask for markdown content\n const prompt = `Generate a concise, informative resource about \"${topic}\".\n${entityTypes.length > 0 ? `Focus on these entity types: ${entityTypes.join(', ')}.` : ''}\n${userPrompt ? `Additional context: ${userPrompt}` : ''}${contextSection}${languageInstruction}\n\nRequirements:\n- Start with a clear heading (# Title)\n- Write 2-3 paragraphs of substantive content\n- Be factual and informative\n- Use markdown formatting\n- Return ONLY the markdown content, no JSON, no code fences, no additional wrapper`;\n\n // Simple parser - just use the response directly as markdown\n const parseResponse = (response: string): { title: string; content: string } => {\n // Clean up any markdown code fences if present\n let content = response.trim();\n if (content.startsWith('```markdown') || content.startsWith('```md')) {\n content = content.slice(content.indexOf('\\n') + 1);\n const endIndex = content.lastIndexOf('```');\n if (endIndex !== -1) {\n content = content.slice(0, endIndex);\n }\n } else if (content.startsWith('```')) {\n content = content.slice(3);\n const endIndex = content.lastIndexOf('```');\n if (endIndex !== -1) {\n content = content.slice(0, endIndex);\n }\n }\n\n content = content.trim();\n\n // Title is provided by the caller (topic), not extracted from generated content\n // This matches how it's actually used in generation-worker.ts line 87\n return {\n title: topic,\n content: content\n };\n };\n\n logger?.debug('Sending prompt to inference', {\n promptLength: prompt.length,\n temperature: finalTemperature,\n maxTokens: finalMaxTokens\n });\n const response = await client.generateText(prompt, finalMaxTokens, finalTemperature);\n logger?.debug('Got response from inference', { responseLength: response.length });\n\n const result = parseResponse(response);\n logger?.debug('Parsed response', {\n hasTitle: !!result.title,\n titleLength: result.title?.length,\n hasContent: !!result.content,\n contentLength: result.content?.length\n });\n\n return result;\n}\n\n/**\n * Generate an intelligent summary for a resource\n */\nexport async function generateResourceSummary(\n resourceName: string,\n content: string,\n entityTypes: string[],\n client: InferenceClient\n): Promise<string> {\n // Truncate content if too long\n const truncatedContent = content.length > 2000\n ? content.substring(0, 2000) + '...'\n : content;\n\n const prompt = `Create a brief, intelligent summary of this resource titled \"${resourceName}\".\n${entityTypes.length > 0 ? `Key entity types: ${entityTypes.join(', ')}` : ''}\n\nResource content:\n${truncatedContent}\n\nWrite a 2-3 sentence summary that captures the key points and would help someone understand what this resource contains.`;\n\n return await client.generateText(prompt, 150, 0.5);\n}\n\n/**\n * Generate smart suggestions for a reference\n */\nexport async function generateReferenceSuggestions(\n referenceTitle: string,\n client: InferenceClient,\n entityType?: string,\n currentContent?: string\n): Promise<string[] | null> {\n const prompt = `For a reference titled \"${referenceTitle}\"${entityType ? ` (type: ${entityType})` : ''}${currentContent ? ` with current stub: \"${currentContent}\"` : ''}, suggest 3 specific, actionable next steps or related topics to explore.\n\nFormat as a simple list, one suggestion per line.`;\n\n const response = await client.generateText(prompt, 200, 0.8);\n if (!response) {\n return null;\n }\n\n // Parse into array of suggestions\n return response\n .split('\\n')\n .map(line => line.replace(/^[-*•]\\s*/, '').trim())\n .filter(line => line.length > 0)\n .slice(0, 3);\n}\n","/**\n * ID generation utilities\n */\n\nimport { randomBytes } from 'crypto';\n\n/**\n * Generate a UUID v4-like ID (without dashes)\n */\nexport function generateUuid(): string {\n return randomBytes(16).toString('hex');\n}\n","/**\n * Highlight Detection Worker\n *\n * Processes highlight-detection jobs: runs AI inference to find passages\n * that should be highlighted and creates highlight annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, HighlightDetectionJob, JobQueue, RunningJob, HighlightDetectionParams, HighlightDetectionProgress, HighlightDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { HighlightMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class HighlightAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'HighlightAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'highlight-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<HighlightDetectionResult> {\n if (job.metadata.type !== 'highlight-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processHighlightDetectionJob(job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<HighlightDetectionParams, HighlightDetectionProgress>,\n result: HighlightDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'highlight-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'highlight-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const hlJob = job as RunningJob<HighlightDetectionParams, HighlightDetectionProgress>;\n\n const baseEvent = {\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(hlJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n progress: hlJob.progress,\n },\n });\n resourceBus.get('mark:progress').next({\n status: hlJob.progress.stage,\n message: hlJob.progress.message,\n percentage: hlJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'highlight-annotation') {\n const hlJob = job as HighlightDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: hlJob.params.resourceId,\n userId: hlJob.metadata.userId,\n version: 1,\n payload: {\n jobId: hlJob.metadata.id,\n jobType: hlJob.metadata.type,\n error: 'Highlight detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processHighlightDetectionJob(job: RunningJob<HighlightDetectionParams, HighlightDetectionProgress>): Promise<HighlightDetectionResult> {\n this.logger?.info('Processing highlight detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<HighlightDetectionParams, HighlightDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect highlights\n const highlights = await AnnotationDetection.detectHighlights(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.density\n );\n\n this.logger?.info('Found highlights to create', { count: highlights.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${highlights.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each highlight\n let created = 0;\n for (const highlight of highlights) {\n try {\n await this.createHighlightAnnotation(job.params.resourceId, job.metadata.userId, highlight);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create highlight', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} highlights`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Highlight detection complete', { created, total: highlights.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n highlightsFound: highlights.length,\n highlightsCreated: created\n };\n }\n\n private async createHighlightAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n highlight: HighlightMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: highlighting\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'highlighting' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: highlight.start,\n end: highlight.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: highlight.exact,\n ...(highlight.prefix && { prefix: highlight.prefix }),\n ...(highlight.suffix && { suffix: highlight.suffix }),\n },\n ]\n },\n 'body': [] // Empty body for highlights\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Assessment Detection Worker\n *\n * Processes assessment-detection jobs: runs AI inference to assess/evaluate\n * passages in the text and creates assessment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, AssessmentDetectionJob, JobQueue, RunningJob, AssessmentDetectionParams, AssessmentDetectionProgress, AssessmentDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { AssessmentMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class AssessmentAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'AssessmentAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'assessment-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<AssessmentDetectionResult> {\n if (job.metadata.type !== 'assessment-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processAssessmentDetectionJob(job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>,\n result: AssessmentDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'assessment-annotation',\n result,\n },\n });\n\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'assessment-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const assJob = job as RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>;\n\n const baseEvent = {\n resourceId: assJob.params.resourceId,\n userId: assJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(assJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: assJob.metadata.id,\n jobType: assJob.metadata.type,\n progress: assJob.progress,\n },\n });\n resourceBus.get('mark:progress').next({\n status: assJob.progress.stage,\n message: assJob.progress.message,\n percentage: assJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'assessment-annotation') {\n const aJob = job as AssessmentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: aJob.params.resourceId,\n userId: aJob.metadata.userId,\n version: 1,\n payload: {\n jobId: aJob.metadata.id,\n jobType: aJob.metadata.type,\n error: 'Assessment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processAssessmentDetectionJob(job: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress>): Promise<AssessmentDetectionResult> {\n this.logger?.info('Processing assessment detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<AssessmentDetectionParams, AssessmentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect assessments\n const assessments = await AnnotationDetection.detectAssessments(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n this.logger?.info('Found assessments to create', { count: assessments.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${assessments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each assessment\n let created = 0;\n for (const assessment of assessments) {\n try {\n await this.createAssessmentAnnotation(job.params.resourceId, job.metadata.userId, assessment);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create assessment', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} assessments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Assessment detection complete', { created, total: assessments.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n assessmentsFound: assessments.length,\n assessmentsCreated: created\n };\n }\n\n private async createAssessmentAnnotation(\n resourceId: ResourceId,\n creatorUserId: string,\n assessment: AssessmentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n if (!backendUrl) throw new Error('Backend publicURL not configured');\n\n const annotationId = generateAnnotationId(backendUrl);\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n\n // Create W3C annotation with motivation: assessing\n // Use both TextPositionSelector and TextQuoteSelector (with prefix/suffix for fuzzy anchoring)\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationId,\n 'motivation': 'assessing' as const,\n 'creator': userId(creatorUserId),\n 'created': new Date().toISOString(),\n 'target': {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: assessment.start,\n end: assessment.end,\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: assessment.exact,\n ...(assessment.prefix && { prefix: assessment.prefix }),\n ...(assessment.suffix && { suffix: assessment.suffix }),\n },\n ]\n },\n 'body': {\n type: 'TextualBody' as const,\n value: assessment.assessment,\n format: 'text/plain'\n }\n };\n\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(creatorUserId),\n version: 1,\n payload: { annotation }\n });\n }\n}\n","/**\n * Comment Detection Worker\n *\n * Processes comment-detection jobs: runs AI inference to identify passages\n * that would benefit from explanatory comments and creates comment annotations.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, CommentDetectionJob, JobQueue, RunningJob, CommentDetectionParams, CommentDetectionProgress, CommentDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { CommentMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class CommentAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'CommentAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'comment-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<CommentDetectionResult> {\n if (job.metadata.type !== 'comment-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processCommentDetectionJob(job as RunningJob<CommentDetectionParams, CommentDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<CommentDetectionParams, CommentDetectionProgress>,\n result: CommentDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'comment-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'comment-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const cdJob = job as RunningJob<CommentDetectionParams, CommentDetectionProgress>;\n\n const baseEvent = {\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(cdJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n progress: cdJob.progress,\n },\n });\n resourceBus.get('mark:progress').next({\n status: cdJob.progress.stage,\n message: cdJob.progress.message,\n percentage: cdJob.progress.percentage\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'comment-annotation') {\n const cdJob = job as CommentDetectionJob;\n\n // Log the full error details to backend logs (already logged by parent)\n // Send generic error message to frontend\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: cdJob.params.resourceId,\n userId: cdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: cdJob.metadata.id,\n jobType: cdJob.metadata.type,\n error: 'Comment detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processCommentDetectionJob(job: RunningJob<CommentDetectionParams, CommentDetectionProgress>): Promise<CommentDetectionResult> {\n this.logger?.info('Processing comment detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started and start analyzing\n let updatedJob: RunningJob<CommentDetectionParams, CommentDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 30,\n message: 'Analyzing text and generating comments...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Use AI to detect passages needing comments\n const comments = await AnnotationDetection.detectComments(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.instructions,\n job.params.tone,\n job.params.density\n );\n\n this.logger?.info('Found comments to create', { count: comments.length });\n\n // Update progress\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n message: `Creating ${comments.length} annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Create annotations for each comment\n let created = 0;\n for (const comment of comments) {\n try {\n await this.createCommentAnnotation(job.params.resourceId, job.metadata.userId, comment);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create comment', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n message: `Complete! Created ${created} comments`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Comment detection complete', { created, total: comments.length });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n commentsFound: comments.length,\n commentsCreated: created\n };\n }\n\n private async createCommentAnnotation(\n resourceId: ResourceId,\n userId_: string,\n comment: CommentMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with motivation: \"commenting\"\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'commenting' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: comment.start,\n end: comment.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: comment.exact,\n prefix: comment.prefix || '',\n suffix: comment.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: comment.comment,\n purpose: 'commenting' as const,\n format: 'text/plain',\n language: 'en'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n this.logger?.debug('Created comment annotation', {\n annotationId,\n exactPreview: comment.exact.substring(0, 50)\n });\n }\n}\n","/**\n * Tag Detection Worker\n *\n * Processes tag-detection jobs: runs AI inference to identify passages\n * serving specific structural roles (IRAC, IMRAD, Toulmin, etc.) and\n * creates tag annotations with dual-body structure.\n */\n\nimport { JobWorker } from '@semiont/jobs';\nimport type { AnyJob, TagDetectionJob, JobQueue, RunningJob, TagDetectionParams, TagDetectionProgress, TagDetectionResult } from '@semiont/jobs';\nimport { ResourceContext, AnnotationDetection } from '..';\nimport { EventStore, generateAnnotationId } from '@semiont/event-sourcing';\nimport { resourceIdToURI, EventBus, type Logger } from '@semiont/core';\nimport { getTagSchema } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\nimport { userId } from '@semiont/core';\nimport type { TagMatch } from '../detection/motivation-parsers';\nimport type { InferenceClient } from '@semiont/inference';\n\nexport class TagAnnotationWorker extends JobWorker {\n private isFirstProgress = true;\n\n constructor(\n jobQueue: JobQueue,\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private inferenceClient: InferenceClient,\n private eventBus: EventBus,\n logger: Logger\n ) {\n super(jobQueue, undefined, undefined, logger);\n }\n\n protected getWorkerName(): string {\n return 'TagAnnotationWorker';\n }\n\n protected canProcessJob(job: AnyJob): boolean {\n return job.metadata.type === 'tag-annotation';\n }\n\n protected async executeJob(job: AnyJob): Promise<TagDetectionResult> {\n if (job.metadata.type !== 'tag-annotation') {\n throw new Error(`Invalid job type: ${job.metadata.type}`);\n }\n\n // Type guard: job must be running to execute\n if (job.status !== 'running') {\n throw new Error(`Job must be in running state to execute, got: ${job.status}`);\n }\n\n // Reset progress tracking\n this.isFirstProgress = true;\n return await this.processTagDetectionJob(job as RunningJob<TagDetectionParams, TagDetectionProgress>);\n }\n\n /**\n * Emit completion event with result data\n * Override base class to emit job.completed event\n */\n protected override async emitCompletionEvent(\n job: RunningJob<TagDetectionParams, TagDetectionProgress>,\n result: TagDetectionResult\n ): Promise<void> {\n await this.eventStore.appendEvent({\n type: 'job.completed',\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n version: 1,\n payload: {\n jobId: job.metadata.id,\n jobType: 'tag-annotation',\n result,\n },\n });\n\n // Emit to EventBus for real-time subscribers\n // Domain event (job.completed) is automatically published to EventBus by EventStore\n // Backend SSE endpoint will subscribe to job.completed and transform to annotate:detect-finished\n }\n\n /**\n * Override updateJobProgress to emit events to Event Store\n */\n protected override async updateJobProgress(job: AnyJob): Promise<void> {\n // Call parent to update filesystem\n await super.updateJobProgress(job);\n\n if (job.metadata.type !== 'tag-annotation') return;\n\n // Type guard: only running jobs have progress\n if (job.status !== 'running') {\n return;\n }\n\n const tdJob = job as RunningJob<TagDetectionParams, TagDetectionProgress>;\n\n const baseEvent = {\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n };\n\n const resourceBus = this.eventBus.scope(tdJob.params.resourceId);\n\n if (this.isFirstProgress) {\n // First progress update - emit job.started\n this.isFirstProgress = false;\n await this.eventStore.appendEvent({\n type: 'job.started',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n },\n });\n } else {\n // Intermediate progress - emit job.progress\n // Note: job.completed is now handled by emitCompletionEvent()\n await this.eventStore.appendEvent({\n type: 'job.progress',\n ...baseEvent,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n progress: tdJob.progress,\n },\n });\n resourceBus.get('mark:progress').next({\n status: tdJob.progress.stage,\n message: tdJob.progress.message,\n percentage: tdJob.progress.percentage,\n currentCategory: tdJob.progress.currentCategory,\n processedCategories: tdJob.progress.processedCategories,\n totalCategories: tdJob.progress.totalCategories\n });\n }\n }\n\n protected override async handleJobFailure(job: AnyJob, error: any): Promise<void> {\n // Call parent to handle the failure logic\n await super.handleJobFailure(job, error);\n\n // If job permanently failed, emit job.failed event\n if (job.status === 'failed' && job.metadata.type === 'tag-annotation') {\n const tdJob = job as TagDetectionJob;\n\n await this.eventStore.appendEvent({\n type: 'job.failed',\n resourceId: tdJob.params.resourceId,\n userId: tdJob.metadata.userId,\n version: 1,\n payload: {\n jobId: tdJob.metadata.id,\n jobType: tdJob.metadata.type,\n error: 'Tag detection failed. Please try again later.',\n },\n });\n }\n }\n\n private async processTagDetectionJob(job: RunningJob<TagDetectionParams, TagDetectionProgress>): Promise<TagDetectionResult> {\n this.logger?.info('Processing tag detection job', {\n resourceId: job.params.resourceId,\n jobId: job.metadata.id\n });\n\n // Validate schema\n const schema = getTagSchema(job.params.schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${job.params.schemaId}`);\n }\n\n // Validate categories\n for (const category of job.params.categories) {\n if (!schema.tags.some(t => t.name === category)) {\n throw new Error(`Invalid category \"${category}\" for schema ${job.params.schemaId}`);\n }\n }\n\n // Fetch resource content\n const resource = await ResourceContext.getResourceMetadata(job.params.resourceId, this.config);\n if (!resource) {\n throw new Error(`Resource ${job.params.resourceId} not found`);\n }\n\n // Emit job.started\n let updatedJob: RunningJob<TagDetectionParams, TagDetectionProgress> = {\n ...job,\n progress: {\n stage: 'analyzing',\n percentage: 10,\n processedCategories: 0,\n totalCategories: job.params.categories.length,\n message: 'Loading resource...'\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Process each category separately\n const allTags: TagMatch[] = [];\n const byCategory: Record<string, number> = {};\n\n for (let i = 0; i < job.params.categories.length; i++) {\n const category = job.params.categories[i]!; // Safe: i < length check guarantees element exists\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'analyzing',\n percentage: 10 + Math.floor((i / job.params.categories.length) * 50),\n currentCategory: category,\n processedCategories: i + 1,\n totalCategories: job.params.categories.length,\n message: `Analyzing ${category}...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n // Detect tags for this category\n const tags = await AnnotationDetection.detectTags(\n job.params.resourceId,\n this.config,\n this.inferenceClient,\n job.params.schemaId,\n category\n );\n this.logger?.info('Found tags for category', { category, count: tags.length });\n\n allTags.push(...tags);\n byCategory[category] = tags.length;\n }\n\n // Create annotations\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 60,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Creating ${allTags.length} tag annotations...`\n }\n };\n await this.updateJobProgress(updatedJob);\n\n let created = 0;\n for (const tag of allTags) {\n try {\n await this.createTagAnnotation(job.params.resourceId, job.metadata.userId, job.params.schemaId, tag);\n created++;\n } catch (error) {\n this.logger?.error('Failed to create tag', { error });\n }\n }\n\n updatedJob = {\n ...updatedJob,\n progress: {\n stage: 'creating',\n percentage: 100,\n processedCategories: job.params.categories.length,\n totalCategories: job.params.categories.length,\n message: `Complete! Created ${created} tags`\n }\n };\n\n await this.updateJobProgress(updatedJob);\n this.logger?.info('Tag detection complete', {\n created,\n total: allTags.length,\n categoryCount: job.params.categories.length\n });\n\n // Return result - base class will use this for CompleteJob and emitCompletionEvent\n return {\n tagsFound: allTags.length,\n tagsCreated: created,\n byCategory\n };\n }\n\n private async createTagAnnotation(\n resourceId: ResourceId,\n userId_: string,\n schemaId: string,\n tag: TagMatch\n ): Promise<void> {\n const backendUrl = this.config.services.backend?.publicURL;\n\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n\n const resourceUri = resourceIdToURI(resourceId, backendUrl);\n const annotationId = generateAnnotationId(backendUrl);\n\n // Create W3C-compliant annotation with dual-body structure:\n // 1. purpose: \"tagging\" with category value\n // 2. purpose: \"classifying\" with schema ID\n const annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n type: 'Annotation' as const,\n id: annotationId,\n motivation: 'tagging' as const,\n target: {\n type: 'SpecificResource' as const,\n source: resourceUri,\n selector: [\n {\n type: 'TextPositionSelector' as const,\n start: tag.start,\n end: tag.end\n },\n {\n type: 'TextQuoteSelector' as const,\n exact: tag.exact,\n prefix: tag.prefix || '',\n suffix: tag.suffix || ''\n }\n ]\n },\n body: [\n {\n type: 'TextualBody' as const,\n value: tag.category,\n purpose: 'tagging' as const,\n format: 'text/plain',\n language: 'en'\n },\n {\n type: 'TextualBody' as const,\n value: schemaId,\n purpose: 'classifying' as const,\n format: 'text/plain'\n }\n ]\n };\n\n // Append annotation.added event to Event Store\n await this.eventStore.appendEvent({\n type: 'annotation.added',\n resourceId,\n userId: userId(userId_),\n version: 1,\n payload: {\n annotation\n }\n });\n\n this.logger?.debug('Created tag annotation', {\n annotationId,\n category: tag.category,\n exactPreview: tag.exact.substring(0, 50)\n });\n }\n}\n","/*! *****************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (_) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport function __createBinding(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n}\r\n\r\nexport function __exportStar(m, exports) {\r\n for (var p in m) if (p !== \"default\" && !exports.hasOwnProperty(p)) exports[p] = m[p];\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n};\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: n === \"return\" } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];\r\n result.default = mod;\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, privateMap) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to get private field on non-instance\");\r\n }\r\n return privateMap.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, privateMap, value) {\r\n if (!privateMap.has(receiver)) {\r\n throw new TypeError(\"attempted to set private field on non-instance\");\r\n }\r\n privateMap.set(receiver, value);\r\n return value;\r\n}\r\n","export function isFunction(x: any): x is Function {\n return typeof x === 'function';\n}\n","let _enable_super_gross_mode_that_will_cause_bad_things = false;\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like what Promise contructor should used to create Promises\n */\nexport const config = {\n /**\n * The promise constructor used by default for methods such as\n * {@link toPromise} and {@link forEach}\n */\n Promise: undefined as PromiseConstructorLike,\n\n /**\n * If true, turns on synchronous error rethrowing, which is a deprecated behavior\n * in v6 and higher. This behavior enables bad patterns like wrapping a subscribe\n * call in a try/catch block. It also enables producer interference, a nasty bug\n * where a multicast can be broken for all observers by a downstream consumer with\n * an unhandled error. DO NOT USE THIS FLAG UNLESS IT'S NEEDED TO BY TIME\n * FOR MIGRATION REASONS.\n */\n set useDeprecatedSynchronousErrorHandling(value: boolean) {\n if (value) {\n const error = new Error();\n console.warn('DEPRECATED! RxJS was set to use deprecated synchronous error handling behavior by code at: \\n' + error.stack);\n } else if (_enable_super_gross_mode_that_will_cause_bad_things) {\n console.log('RxJS: Back to a better error behavior. Thank you. <3');\n }\n _enable_super_gross_mode_that_will_cause_bad_things = value;\n },\n\n get useDeprecatedSynchronousErrorHandling() {\n return _enable_super_gross_mode_that_will_cause_bad_things;\n },\n};\n","/**\n * Throws an error on another job so that it's picked up by the runtime's\n * uncaught error handling mechanism.\n * @param err the error to throw\n */\nexport function hostReportError(err: any) {\n setTimeout(() => { throw err; }, 0);\n}","import { Observer } from './types';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\nexport const empty: Observer<any> = {\n closed: true,\n next(value: any): void { /* noop */},\n error(err: any): void {\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n },\n complete(): void { /*noop*/ }\n};\n","export function isObject(x: any): x is Object {\n return x !== null && typeof x === 'object';\n}\n","export interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n new(errors: any[]): UnsubscriptionError;\n}\n\nconst UnsubscriptionErrorImpl = (() => {\n function UnsubscriptionErrorImpl(this: any, errors: any[]) {\n Error.call(this);\n this.message = errors ?\n `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}` : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n return this;\n }\n\n UnsubscriptionErrorImpl.prototype = Object.create(Error.prototype);\n\n return UnsubscriptionErrorImpl;\n})();\n\n/**\n * An error thrown when one or more errors have occurred during the\n * `unsubscribe` of a {@link Subscription}.\n */\nexport const UnsubscriptionError: UnsubscriptionErrorCtor = UnsubscriptionErrorImpl as any;","import { isArray } from './util/isArray';\nimport { isObject } from './util/isObject';\nimport { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic } from './types';\n\n/**\n * Represents a disposable resource, such as the execution of an Observable. A\n * Subscription has one important method, `unsubscribe`, that takes no argument\n * and just disposes the resource held by the subscription.\n *\n * Additionally, subscriptions may be grouped together through the `add()`\n * method, which will attach a child Subscription to the current Subscription.\n * When a Subscription is unsubscribed, all its children (and its grandchildren)\n * will be unsubscribed as well.\n *\n * @class Subscription\n */\nexport class Subscription implements SubscriptionLike {\n /** @nocollapse */\n public static EMPTY: Subscription = (function(empty: any) {\n empty.closed = true;\n return empty;\n }(new Subscription()));\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n * @type {boolean}\n */\n public closed: boolean = false;\n\n /** @internal */\n protected _parentOrParents: Subscription | Subscription[] = null;\n /** @internal */\n private _subscriptions: SubscriptionLike[] = null;\n\n /**\n * @param {function(): void} [unsubscribe] A function describing how to\n * perform the disposal of resources when the `unsubscribe` method is called.\n */\n constructor(unsubscribe?: () => void) {\n if (unsubscribe) {\n (this as any)._ctorUnsubscribe = true;\n (this as any)._unsubscribe = unsubscribe;\n }\n }\n\n /**\n * Disposes the resources held by the subscription. May, for instance, cancel\n * an ongoing Observable execution or cancel any other type of work that\n * started when the Subscription was created.\n * @return {void}\n */\n unsubscribe(): void {\n let errors: any[];\n\n if (this.closed) {\n return;\n }\n\n let { _parentOrParents, _ctorUnsubscribe, _unsubscribe, _subscriptions } = (this as any);\n\n this.closed = true;\n this._parentOrParents = null;\n // null out _subscriptions first so any child subscriptions that attempt\n // to remove themselves from this subscription will noop\n this._subscriptions = null;\n\n if (_parentOrParents instanceof Subscription) {\n _parentOrParents.remove(this);\n } else if (_parentOrParents !== null) {\n for (let index = 0; index < _parentOrParents.length; ++index) {\n const parent = _parentOrParents[index];\n parent.remove(this);\n }\n }\n\n if (isFunction(_unsubscribe)) {\n // It's only possible to null _unsubscribe - to release the reference to\n // any teardown function passed in the constructor - if the property was\n // actually assigned in the constructor, as there are some classes that\n // are derived from Subscriber (which derives from Subscription) that\n // implement an _unsubscribe method as a mechanism for obtaining\n // unsubscription notifications and some of those subscribers are\n // recycled. Also, in some of those subscribers, _unsubscribe switches\n // from a prototype method to an instance property - see notifyNext in\n // RetryWhenSubscriber.\n if (_ctorUnsubscribe) {\n (this as any)._unsubscribe = undefined;\n }\n try {\n _unsubscribe.call(this);\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? flattenUnsubscriptionErrors(e.errors) : [e];\n }\n }\n\n if (isArray(_subscriptions)) {\n let index = -1;\n let len = _subscriptions.length;\n\n while (++index < len) {\n const sub = _subscriptions[index];\n if (isObject(sub)) {\n try {\n sub.unsubscribe();\n } catch (e) {\n errors = errors || [];\n if (e instanceof UnsubscriptionError) {\n errors = errors.concat(flattenUnsubscriptionErrors(e.errors));\n } else {\n errors.push(e);\n }\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n\n /**\n * Adds a tear down to be called during the unsubscribe() of this\n * Subscription. Can also be used to add a child subscription.\n *\n * If the tear down being added is a subscription that is already\n * unsubscribed, is the same reference `add` is being called on, or is\n * `Subscription.EMPTY`, it will not be added.\n *\n * If this subscription is already in an `closed` state, the passed\n * tear down logic will be executed immediately.\n *\n * When a parent subscription is unsubscribed, any child subscriptions that were added to it are also unsubscribed.\n *\n * @param {TeardownLogic} teardown The additional logic to execute on\n * teardown.\n * @return {Subscription} Returns the Subscription used or created to be\n * added to the inner subscriptions list. This Subscription can be used with\n * `remove()` to remove the passed teardown logic from the inner subscriptions\n * list.\n */\n add(teardown: TeardownLogic): Subscription {\n let subscription = (<Subscription>teardown);\n\n if (!teardown) {\n return Subscription.EMPTY;\n }\n\n switch (typeof teardown) {\n case 'function':\n subscription = new Subscription(<(() => void)>teardown);\n case 'object':\n if (subscription === this || subscription.closed || typeof subscription.unsubscribe !== 'function') {\n // This also covers the case where `subscription` is `Subscription.EMPTY`, which is always in `closed` state.\n return subscription;\n } else if (this.closed) {\n subscription.unsubscribe();\n return subscription;\n } else if (!(subscription instanceof Subscription)) {\n const tmp = subscription;\n subscription = new Subscription();\n subscription._subscriptions = [tmp];\n }\n break;\n default: {\n throw new Error('unrecognized teardown ' + teardown + ' added to Subscription.');\n }\n }\n\n // Add `this` as parent of `subscription` if that's not already the case.\n let { _parentOrParents } = subscription;\n if (_parentOrParents === null) {\n // If we don't have a parent, then set `subscription._parents` to\n // the `this`, which is the common case that we optimize for.\n subscription._parentOrParents = this;\n } else if (_parentOrParents instanceof Subscription) {\n if (_parentOrParents === this) {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n // If there's already one parent, but not multiple, allocate an\n // Array to store the rest of the parent Subscriptions.\n subscription._parentOrParents = [_parentOrParents, this];\n } else if (_parentOrParents.indexOf(this) === -1) {\n // Only add `this` to the _parentOrParents list if it's not already there.\n _parentOrParents.push(this);\n } else {\n // The `subscription` already has `this` as a parent.\n return subscription;\n }\n\n // Optimize for the common case when adding the first subscription.\n const subscriptions = this._subscriptions;\n if (subscriptions === null) {\n this._subscriptions = [subscription];\n } else {\n subscriptions.push(subscription);\n }\n\n return subscription;\n }\n\n /**\n * Removes a Subscription from the internal list of subscriptions that will\n * unsubscribe during the unsubscribe process of this Subscription.\n * @param {Subscription} subscription The subscription to remove.\n * @return {void}\n */\n remove(subscription: Subscription): void {\n const subscriptions = this._subscriptions;\n if (subscriptions) {\n const subscriptionIndex = subscriptions.indexOf(subscription);\n if (subscriptionIndex !== -1) {\n subscriptions.splice(subscriptionIndex, 1);\n }\n }\n }\n}\n\nfunction flattenUnsubscriptionErrors(errors: any[]) {\n return errors.reduce((errs, err) => errs.concat((err instanceof UnsubscriptionError) ? err.errors : err), []);\n}\n","/** @deprecated do not use, this is no longer checked by RxJS internals */\nexport const rxSubscriber = (() =>\n typeof Symbol === 'function'\n ? Symbol('rxSubscriber')\n : '@@rxSubscriber_' + Math.random())();\n\n/**\n * @deprecated use rxSubscriber instead\n */\nexport const $$rxSubscriber = rxSubscriber;\n","import { isFunction } from './util/isFunction';\nimport { empty as emptyObserver } from './Observer';\nimport { Observer, PartialObserver, TeardownLogic } from './types';\nimport { Subscription } from './Subscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\nimport { config } from './config';\nimport { hostReportError } from './util/hostReportError';\n\n/**\n * Implements the {@link Observer} interface and extends the\n * {@link Subscription} class. While the {@link Observer} is the public API for\n * consuming the values of an {@link Observable}, all Observers get converted to\n * a Subscriber, in order to provide Subscription-like capabilities such as\n * `unsubscribe`. Subscriber is a common type in RxJS, and crucial for\n * implementing operators, but it is rarely used as a public API.\n *\n * @class Subscriber<T>\n */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n\n [rxSubscriberSymbol]() { return this; }\n\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param {function(x: ?T): void} [next] The `next` callback of an Observer.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n * @return {Subscriber<T>} A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @nocollapse\n */\n static create<T>(next?: (x?: T) => void,\n error?: (e?: any) => void,\n complete?: () => void): Subscriber<T> {\n const subscriber = new Subscriber(next, error, complete);\n subscriber.syncErrorThrowable = false;\n return subscriber;\n }\n\n /** @internal */ syncErrorValue: any = null;\n /** @internal */ syncErrorThrown: boolean = false;\n /** @internal */ syncErrorThrowable: boolean = false;\n\n protected isStopped: boolean = false;\n protected destination: PartialObserver<any> | Subscriber<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @param {Observer|function(value: T): void} [destinationOrNext] A partially\n * defined Observer or a `next` callback function.\n * @param {function(e: ?any): void} [error] The `error` callback of an\n * Observer.\n * @param {function(): void} [complete] The `complete` callback of an\n * Observer.\n */\n constructor(destinationOrNext?: PartialObserver<any> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n switch (arguments.length) {\n case 0:\n this.destination = emptyObserver;\n break;\n case 1:\n if (!destinationOrNext) {\n this.destination = emptyObserver;\n break;\n }\n if (typeof destinationOrNext === 'object') {\n if (destinationOrNext instanceof Subscriber) {\n this.syncErrorThrowable = destinationOrNext.syncErrorThrowable;\n this.destination = destinationOrNext;\n destinationOrNext.add(this);\n } else {\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <PartialObserver<any>> destinationOrNext);\n }\n break;\n }\n default:\n this.syncErrorThrowable = true;\n this.destination = new SafeSubscriber<T>(this, <((value: T) => void)> destinationOrNext, error, complete);\n break;\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `next` from\n * the Observable, with a value. The Observable may call this method 0 or more\n * times.\n * @param {T} [value] The `next` value.\n * @return {void}\n */\n next(value?: T): void {\n if (!this.isStopped) {\n this._next(value);\n }\n }\n\n /**\n * The {@link Observer} callback to receive notifications of type `error` from\n * the Observable, with an attached `Error`. Notifies the Observer that\n * the Observable has experienced an error condition.\n * @param {any} [err] The `error` exception.\n * @return {void}\n */\n error(err?: any): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._error(err);\n }\n }\n\n /**\n * The {@link Observer} callback to receive a valueless notification of type\n * `complete` from the Observable. Notifies the Observer that the Observable\n * has finished sending push-based notifications.\n * @return {void}\n */\n complete(): void {\n if (!this.isStopped) {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (this.closed) {\n return;\n }\n this.isStopped = true;\n super.unsubscribe();\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n this.destination.error(err);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.destination.complete();\n this.unsubscribe();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribeAndRecycle(): Subscriber<T> {\n const { _parentOrParents } = this;\n this._parentOrParents = null;\n this.unsubscribe();\n this.closed = false;\n this.isStopped = false;\n this._parentOrParents = _parentOrParents;\n return this;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SafeSubscriber<T> extends Subscriber<T> {\n\n private _context: any;\n\n constructor(private _parentSubscriber: Subscriber<T>,\n observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (e?: any) => void,\n complete?: () => void) {\n super();\n\n let next: ((value: T) => void);\n let context: any = this;\n\n if (isFunction(observerOrNext)) {\n next = (<((value: T) => void)> observerOrNext);\n } else if (observerOrNext) {\n next = (<PartialObserver<T>> observerOrNext).next;\n error = (<PartialObserver<T>> observerOrNext).error;\n complete = (<PartialObserver<T>> observerOrNext).complete;\n if (observerOrNext !== emptyObserver) {\n context = Object.create(observerOrNext);\n if (isFunction(context.unsubscribe)) {\n this.add(<() => void> context.unsubscribe.bind(context));\n }\n context.unsubscribe = this.unsubscribe.bind(this);\n }\n }\n\n this._context = context;\n this._next = next;\n this._error = error;\n this._complete = complete;\n }\n\n next(value?: T): void {\n if (!this.isStopped && this._next) {\n const { _parentSubscriber } = this;\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._next, value);\n } else if (this.__tryOrSetError(_parentSubscriber, this._next, value)) {\n this.unsubscribe();\n }\n }\n }\n\n error(err?: any): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n const { useDeprecatedSynchronousErrorHandling } = config;\n if (this._error) {\n if (!useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(this._error, err);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, this._error, err);\n this.unsubscribe();\n }\n } else if (!_parentSubscriber.syncErrorThrowable) {\n this.unsubscribe();\n if (useDeprecatedSynchronousErrorHandling) {\n throw err;\n }\n hostReportError(err);\n } else {\n if (useDeprecatedSynchronousErrorHandling) {\n _parentSubscriber.syncErrorValue = err;\n _parentSubscriber.syncErrorThrown = true;\n } else {\n hostReportError(err);\n }\n this.unsubscribe();\n }\n }\n }\n\n complete(): void {\n if (!this.isStopped) {\n const { _parentSubscriber } = this;\n if (this._complete) {\n const wrappedComplete = () => this._complete.call(this._context);\n\n if (!config.useDeprecatedSynchronousErrorHandling || !_parentSubscriber.syncErrorThrowable) {\n this.__tryOrUnsub(wrappedComplete);\n this.unsubscribe();\n } else {\n this.__tryOrSetError(_parentSubscriber, wrappedComplete);\n this.unsubscribe();\n }\n } else {\n this.unsubscribe();\n }\n }\n }\n\n private __tryOrUnsub(fn: Function, value?: any): void {\n try {\n fn.call(this._context, value);\n } catch (err) {\n this.unsubscribe();\n if (config.useDeprecatedSynchronousErrorHandling) {\n throw err;\n } else {\n hostReportError(err);\n }\n }\n }\n\n private __tryOrSetError(parent: Subscriber<T>, fn: Function, value?: any): boolean {\n if (!config.useDeprecatedSynchronousErrorHandling) {\n throw new Error('bad call');\n }\n try {\n fn.call(this._context, value);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n parent.syncErrorValue = err;\n parent.syncErrorThrown = true;\n return true;\n } else {\n hostReportError(err);\n return true;\n }\n }\n return false;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _unsubscribe(): void {\n const { _parentSubscriber } = this;\n this._context = null;\n this._parentSubscriber = null;\n _parentSubscriber.unsubscribe();\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subject } from '../Subject';\n\n/**\n * Determines whether the ErrorObserver is closed or stopped or has a\n * destination that is closed or stopped - in which case errors will\n * need to be reported via a different mechanism.\n * @param observer the observer\n */\nexport function canReportError(observer: Subscriber<any> | Subject<any>): boolean {\n while (observer) {\n const { closed, destination, isStopped } = observer as any;\n if (closed || isStopped) {\n return false;\n } else if (destination && destination instanceof Subscriber) {\n observer = destination;\n } else {\n observer = null;\n }\n }\n return true;\n}\n","import { Subscriber } from '../Subscriber';\nimport { rxSubscriber as rxSubscriberSymbol } from '../symbol/rxSubscriber';\nimport { empty as emptyObserver } from '../Observer';\nimport { PartialObserver } from '../types';\n\nexport function toSubscriber<T>(\n nextOrObserver?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscriber<T> {\n\n if (nextOrObserver) {\n if (nextOrObserver instanceof Subscriber) {\n return (<Subscriber<T>> nextOrObserver);\n }\n\n if (nextOrObserver[rxSubscriberSymbol]) {\n return nextOrObserver[rxSubscriberSymbol]();\n }\n }\n\n if (!nextOrObserver && !error && !complete) {\n return new Subscriber(emptyObserver);\n }\n\n return new Subscriber(nextOrObserver, error, complete);\n}\n","export function identity<T>(x: T): T {\n return x;\n}\n","import { noop } from './noop';\nimport { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function pipe<T>(): UnaryFunction<T, T>;\nexport function pipe<T, A>(fn1: UnaryFunction<T, A>): UnaryFunction<T, A>;\nexport function pipe<T, A, B>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>): UnaryFunction<T, B>;\nexport function pipe<T, A, B, C>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>): UnaryFunction<T, C>;\nexport function pipe<T, A, B, C, D>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(fn1: UnaryFunction<T, A>, fn2: UnaryFunction<A, B>, fn3: UnaryFunction<B, C>, fn4: UnaryFunction<C, D>, fn5: UnaryFunction<D, E>, fn6: UnaryFunction<E, F>, fn7: UnaryFunction<F, G>, fn8: UnaryFunction<G, H>, fn9: UnaryFunction<H, I>, ...fns: UnaryFunction<any, any>[]): UnaryFunction<T, {}>;\n/* tslint:enable:max-line-length */\n\nexport function pipe(...fns: Array<UnaryFunction<any, any>>): UnaryFunction<any, any> {\n return pipeFromArray(fns);\n}\n\n/** @internal */\nexport function pipeFromArray<T, R>(fns: Array<UnaryFunction<T, R>>): UnaryFunction<T, R> {\n if (fns.length === 0) {\n return identity as UnaryFunction<any, any>;\n }\n\n if (fns.length === 1) {\n return fns[0];\n }\n\n return function piped(input: T): R {\n return fns.reduce((prev: any, fn: UnaryFunction<T, R>) => fn(prev), input as any);\n };\n}\n","import { Operator } from './Operator';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, PartialObserver, Subscribable } from './types';\nimport { canReportError } from './util/canReportError';\nimport { toSubscriber } from './util/toSubscriber';\nimport { iif } from './observable/iif';\nimport { throwError } from './observable/throwError';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\n\n/**\n * A representation of any set of values over any amount of time. This is the most basic building block\n * of RxJS.\n *\n * @class Observable<T>\n */\nexport class Observable<T> implements Subscribable<T> {\n\n /** Internal implementation detail, do not use directly. */\n public _isScalar: boolean = false;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n source: Observable<any>;\n\n /** @deprecated This is an internal implementation detail, do not use. */\n operator: Operator<any, T>;\n\n /**\n * @constructor\n * @param {Function} subscribe the function that is called when the Observable is\n * initially subscribed to. This function is given a Subscriber, to which new values\n * can be `next`ed, or an `error` method can be called to raise an error, or\n * `complete` can be called to notify of a successful completion.\n */\n constructor(subscribe?: (this: Observable<T>, subscriber: Subscriber<T>) => TeardownLogic) {\n if (subscribe) {\n this._subscribe = subscribe;\n }\n }\n\n // HACK: Since TypeScript inherits static properties too, we have to\n // fight against TypeScript here so Subject can have a different static create signature\n /**\n * Creates a new cold Observable by calling the Observable constructor\n * @static true\n * @owner Observable\n * @method create\n * @param {Function} subscribe? the subscriber function to be passed to the Observable constructor\n * @return {Observable} a new cold observable\n * @nocollapse\n * @deprecated use new Observable() instead\n */\n static create: Function = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n }\n\n /**\n * Creates a new Observable, with this Observable as the source, and the passed\n * operator defined as the new observable's operator.\n * @method lift\n * @param {Operator} operator the operator defining the operation to take on the observable\n * @return {Observable} a new observable with the Operator applied\n */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const observable = new Observable<R>();\n observable.source = this;\n observable.operator = operator;\n return observable;\n }\n\n subscribe(observer?: PartialObserver<T>): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: null | undefined, error: null | undefined, complete: () => void): Subscription;\n /** @deprecated Use an observer instead of an error callback */\n subscribe(next: null | undefined, error: (error: any) => void, complete?: () => void): Subscription;\n /** @deprecated Use an observer instead of a complete callback */\n subscribe(next: (value: T) => void, error: null | undefined, complete: () => void): Subscription;\n subscribe(next?: (value: T) => void, error?: (error: any) => void, complete?: () => void): Subscription;\n /**\n * Invokes an execution of an Observable and registers Observer handlers for notifications it will emit.\n *\n * <span class=\"informal\">Use it when you have all these Observables, but still nothing is happening.</span>\n *\n * `subscribe` is not a regular operator, but a method that calls Observable's internal `subscribe` function. It\n * might be for example a function that you passed to Observable's constructor, but most of the time it is\n * a library implementation, which defines what will be emitted by an Observable, and when it be will emitted. This means\n * that calling `subscribe` is actually the moment when Observable starts its work, not when it is created, as it is often\n * the thought.\n *\n * Apart from starting the execution of an Observable, this method allows you to listen for values\n * that an Observable emits, as well as for when it completes or errors. You can achieve this in two\n * of the following ways.\n *\n * The first way is creating an object that implements {@link Observer} interface. It should have methods\n * defined by that interface, but note that it should be just a regular JavaScript object, which you can create\n * yourself in any way you want (ES6 class, classic function constructor, object literal etc.). In particular do\n * not attempt to use any RxJS implementation details to create Observers - you don't need them. Remember also\n * that your object does not have to implement all methods. If you find yourself creating a method that doesn't\n * do anything, you can simply omit it. Note however, if the `error` method is not provided, all errors will\n * be left uncaught.\n *\n * The second way is to give up on Observer object altogether and simply provide callback functions in place of its methods.\n * This means you can provide three functions as arguments to `subscribe`, where the first function is equivalent\n * of a `next` method, the second of an `error` method and the third of a `complete` method. Just as in case of Observer,\n * if you do not need to listen for something, you can omit a function, preferably by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to `error` function, just as before, if not provided, errors emitted by an Observable will be thrown.\n *\n * Whichever style of calling `subscribe` you use, in both cases it returns a Subscription object.\n * This object allows you to call `unsubscribe` on it, which in turn will stop the work that an Observable does and will clean\n * up all resources that an Observable used. Note that cancelling a subscription will not call `complete` callback\n * provided to `subscribe` function, which is reserved for a regular completion signal that comes from an Observable.\n *\n * Remember that callbacks provided to `subscribe` are not guaranteed to be called asynchronously.\n * It is an Observable itself that decides when these functions will be called. For example {@link of}\n * by default emits all its values synchronously. Always check documentation for how given Observable\n * will behave when subscribed and if its default behavior can be modified with a `scheduler`.\n *\n * ## Example\n * ### Subscribe with an Observer\n * ```ts\n * import { of } from 'rxjs';\n *\n * const sumObserver = {\n * sum: 0,\n * next(value) {\n * console.log('Adding: ' + value);\n * this.sum = this.sum + value;\n * },\n * error() {\n * // We actually could just remove this method,\n * // since we do not really care about errors right now.\n * },\n * complete() {\n * console.log('Sum equals: ' + this.sum);\n * }\n * };\n *\n * of(1, 2, 3) // Synchronously emits 1, 2, 3 and then completes.\n * .subscribe(sumObserver);\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Subscribe with functions\n * ```ts\n * import { of } from 'rxjs'\n *\n * let sum = 0;\n *\n * of(1, 2, 3).subscribe(\n * value => {\n * console.log('Adding: ' + value);\n * sum = sum + value;\n * },\n * undefined,\n * () => console.log('Sum equals: ' + sum)\n * );\n *\n * // Logs:\n * // \"Adding: 1\"\n * // \"Adding: 2\"\n * // \"Adding: 3\"\n * // \"Sum equals: 6\"\n * ```\n *\n * ### Cancel a subscription\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe(\n * num => console.log(num),\n * undefined,\n * () => {\n * // Will not be called, even when cancelling subscription.\n * console.log('completed!');\n * }\n * );\n *\n * setTimeout(() => {\n * subscription.unsubscribe();\n * console.log('unsubscribed!');\n * }, 2500);\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // \"unsubscribed!\" after 2.5s\n * ```\n *\n * @param {Observer|Function} observerOrNext (optional) Either an observer with methods to be called,\n * or the first of three possible handlers, which is the handler for each value emitted from the subscribed\n * Observable.\n * @param {Function} error (optional) A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown as unhandled.\n * @param {Function} complete (optional) A handler for a terminal event resulting from successful completion.\n * @return {ISubscription} a subscription reference to the registered handlers\n * @method subscribe\n */\n subscribe(observerOrNext?: PartialObserver<T> | ((value: T) => void),\n error?: (error: any) => void,\n complete?: () => void): Subscription {\n\n const { operator } = this;\n const sink = toSubscriber(observerOrNext, error, complete);\n\n if (operator) {\n sink.add(operator.call(sink, this.source));\n } else {\n sink.add(\n this.source || (config.useDeprecatedSynchronousErrorHandling && !sink.syncErrorThrowable) ?\n this._subscribe(sink) :\n this._trySubscribe(sink)\n );\n }\n\n if (config.useDeprecatedSynchronousErrorHandling) {\n if (sink.syncErrorThrowable) {\n sink.syncErrorThrowable = false;\n if (sink.syncErrorThrown) {\n throw sink.syncErrorValue;\n }\n }\n }\n\n return sink;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n sink.syncErrorThrown = true;\n sink.syncErrorValue = err;\n }\n if (canReportError(sink)) {\n sink.error(err);\n } else {\n console.warn(err);\n }\n }\n }\n\n /**\n * @method forEach\n * @param {Function} next a handler for each value emitted by the observable\n * @param {PromiseConstructor} [promiseCtor] a constructor function used to instantiate the Promise\n * @return {Promise} a promise that either resolves on observable completion or\n * rejects with the handled error\n */\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n // Must be declared in a separate statement to avoid a ReferenceError when\n // accessing subscription below in the closure due to Temporal Dead Zone.\n let subscription: Subscription;\n subscription = this.subscribe((value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n if (subscription) {\n subscription.unsubscribe();\n }\n }\n }, reject, resolve);\n }) as Promise<void>;\n }\n\n /** @internal This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n const { source } = this;\n return source && source.subscribe(subscriber);\n }\n\n // `if` and `throw` are special snow flakes, the compiler sees them as reserved words. Deprecated in\n // favor of iif and throwError functions.\n /**\n * @nocollapse\n * @deprecated In favor of iif creation function: import { iif } from 'rxjs';\n */\n static if: typeof iif;\n /**\n * @nocollapse\n * @deprecated In favor of throwError creation function: import { throwError } from 'rxjs';\n */\n static throw: typeof throwError;\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @method Symbol.observable\n * @return {Observable} this instance of the observable\n */\n [Symbol_observable]() {\n return this;\n }\n\n /* tslint:disable:max-line-length */\n pipe(): Observable<T>;\n pipe<A>(op1: OperatorFunction<T, A>): Observable<A>;\n pipe<A, B>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>): Observable<B>;\n pipe<A, B, C>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>): Observable<C>;\n pipe<A, B, C, D>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>): Observable<D>;\n pipe<A, B, C, D, E>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>): Observable<E>;\n pipe<A, B, C, D, E, F>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>): Observable<F>;\n pipe<A, B, C, D, E, F, G>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(op1: OperatorFunction<T, A>, op2: OperatorFunction<A, B>, op3: OperatorFunction<B, C>, op4: OperatorFunction<C, D>, op5: OperatorFunction<D, E>, op6: OperatorFunction<E, F>, op7: OperatorFunction<F, G>, op8: OperatorFunction<G, H>, op9: OperatorFunction<H, I>, ...operations: OperatorFunction<any, any>[]): Observable<{}>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n * @method pipe\n * @return {Observable} the Observable result of all of the operators having\n * been called in the order they were passed in.\n *\n * ### Example\n * ```ts\n * import { interval } from 'rxjs';\n * import { map, filter, scan } from 'rxjs/operators';\n *\n * interval(1000)\n * .pipe(\n * filter(x => x % 2 === 0),\n * map(x => x + x),\n * scan((acc, x) => acc + x)\n * )\n * .subscribe(x => console.log(x))\n * ```\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n if (operations.length === 0) {\n return this as any;\n }\n\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n toPromise<T>(this: Observable<T>): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: typeof Promise): Promise<T>;\n toPromise<T>(this: Observable<T>, PromiseCtor: PromiseConstructorLike): Promise<T>;\n /* tslint:enable:max-line-length */\n\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: any;\n this.subscribe((x: T) => value = x, (err: any) => reject(err), () => resolve(value));\n }) as Promise<T>;\n }\n}\n\n/**\n * Decides between a passed promise constructor from consuming code,\n * A default configured promise constructor, and the native promise\n * constructor and returns it. If nothing can be found, it will throw\n * an error.\n * @param promiseCtor The optional promise constructor to passed by consuming code\n */\nfunction getPromiseCtor(promiseCtor: PromiseConstructorLike | undefined) {\n if (!promiseCtor) {\n promiseCtor = config.Promise || Promise;\n }\n\n if (!promiseCtor) {\n throw new Error('no Promise impl found');\n }\n\n return promiseCtor;\n}\n","export interface ObjectUnsubscribedError extends Error {\n}\n\nexport interface ObjectUnsubscribedErrorCtor {\n new(): ObjectUnsubscribedError;\n}\n\nconst ObjectUnsubscribedErrorImpl = (() => {\n function ObjectUnsubscribedErrorImpl(this: any) {\n Error.call(this);\n this.message = 'object unsubscribed';\n this.name = 'ObjectUnsubscribedError';\n return this;\n }\n\n ObjectUnsubscribedErrorImpl.prototype = Object.create(Error.prototype);\n\n return ObjectUnsubscribedErrorImpl;\n})();\n\n/**\n * An error thrown when an action is invalid because the object has been\n * unsubscribed.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n *\n * @class ObjectUnsubscribedError\n */\nexport const ObjectUnsubscribedError: ObjectUnsubscribedErrorCtor = ObjectUnsubscribedErrorImpl as any;","import { Subject } from './Subject';\nimport { Observer } from './types';\nimport { Subscription } from './Subscription';\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class SubjectSubscription<T> extends Subscription {\n closed: boolean = false;\n\n constructor(public subject: Subject<T>, public subscriber: Observer<T>) {\n super();\n }\n\n unsubscribe() {\n if (this.closed) {\n return;\n }\n\n this.closed = true;\n\n const subject = this.subject;\n const observers = subject.observers;\n\n this.subject = null;\n\n if (!observers || observers.length === 0 || subject.isStopped || subject.closed) {\n return;\n }\n\n const subscriberIndex = observers.indexOf(this.subscriber);\n\n if (subscriberIndex !== -1) {\n observers.splice(subscriberIndex, 1);\n }\n }\n}\n","import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { SubjectSubscription } from './SubjectSubscription';\nimport { rxSubscriber as rxSubscriberSymbol } from '../internal/symbol/rxSubscriber';\n\n/**\n * @class SubjectSubscriber<T>\n */\nexport class SubjectSubscriber<T> extends Subscriber<T> {\n constructor(protected destination: Subject<T>) {\n super(destination);\n }\n}\n\n/**\n * A Subject is a special type of Observable that allows values to be\n * multicasted to many Observers. Subjects are like EventEmitters.\n *\n * Every Subject is an Observable and an Observer. You can subscribe to a\n * Subject, and you can call next to feed values as well as error and complete.\n *\n * @class Subject<T>\n */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n\n [rxSubscriberSymbol]() {\n return new SubjectSubscriber(this);\n }\n\n observers: Observer<T>[] = [];\n\n closed = false;\n\n isStopped = false;\n\n hasError = false;\n\n thrownError: any = null;\n\n constructor() {\n super();\n }\n\n /**@nocollapse\n * @deprecated use new Subject() instead\n */\n static create: Function = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n return new AnonymousSubject<T>(destination, source);\n }\n\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const subject = new AnonymousSubject(this, this);\n subject.operator = <any>operator;\n return <any>subject;\n }\n\n next(value?: T) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n if (!this.isStopped) {\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].next(value);\n }\n }\n }\n\n error(err: any) {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.hasError = true;\n this.thrownError = err;\n this.isStopped = true;\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].error(err);\n }\n this.observers.length = 0;\n }\n\n complete() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n this.isStopped = true;\n const { observers } = this;\n const len = observers.length;\n const copy = observers.slice();\n for (let i = 0; i < len; i++) {\n copy[i].complete();\n }\n this.observers.length = 0;\n }\n\n unsubscribe() {\n this.isStopped = true;\n this.closed = true;\n this.observers = null;\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else {\n return super._trySubscribe(subscriber);\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>): Subscription {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n } else if (this.hasError) {\n subscriber.error(this.thrownError);\n return Subscription.EMPTY;\n } else if (this.isStopped) {\n subscriber.complete();\n return Subscription.EMPTY;\n } else {\n this.observers.push(subscriber);\n return new SubjectSubscription(this, subscriber);\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create customize Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return {Observable} Observable that the Subject casts to\n */\n asObservable(): Observable<T> {\n const observable = new Observable<T>();\n (<any>observable).source = this;\n return observable;\n }\n}\n\n/**\n * @class AnonymousSubject<T>\n */\nexport class AnonymousSubject<T> extends Subject<T> {\n constructor(protected destination?: Observer<T>, source?: Observable<T>) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n const { destination } = this;\n if (destination && destination.next) {\n destination.next(value);\n }\n }\n\n error(err: any) {\n const { destination } = this;\n if (destination && destination.error) {\n this.destination.error(err);\n }\n }\n\n complete() {\n const { destination } = this;\n if (destination && destination.complete) {\n this.destination.complete();\n }\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>): Subscription {\n const { source } = this;\n if (source) {\n return this.source.subscribe(subscriber);\n } else {\n return Subscription.EMPTY;\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function groupBy<T, K>(keySelector: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K>(keySelector: (value: T) => K, elementSelector: void, durationSelector: (grouped: GroupedObservable<K, T>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, T>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>): OperatorFunction<T, GroupedObservable<K, R>>;\nexport function groupBy<T, K, R>(keySelector: (value: T) => K, elementSelector?: (value: T) => R, durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>, subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Groups the items emitted by an Observable according to a specified criterion,\n * and emits these grouped items as `GroupedObservables`, one\n * {@link GroupedObservable} per group.\n *\n * ![](groupBy.png)\n *\n * When the Observable emits an item, a key is computed for this item with the keySelector function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Elsewhere, a new\n * {@link GroupedObservable} for this key is created and emits.\n *\n * A {@link GroupedObservable} represents values belonging to the same group represented by a common key. The common\n * key is available as the key field of a {@link GroupedObservable} instance.\n *\n * The elements emitted by {@link GroupedObservable}s are by default the items emitted by the Observable, or elements\n * returned by the elementSelector function.\n *\n * ## Examples\n *\n * ### Group objects by id and return as array\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { mergeMap, groupBy, reduce } from 'rxjs/operators';\n *\n * of(\n * {id: 1, name: 'JavaScript'},\n * {id: 2, name: 'Parcel'},\n * {id: 2, name: 'webpack'},\n * {id: 1, name: 'TypeScript'},\n * {id: 3, name: 'TSLint'}\n * ).pipe(\n * groupBy(p => p.id),\n * mergeMap((group$) => group$.pipe(reduce((acc, cur) => [...acc, cur], []))),\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // [ { id: 1, name: 'JavaScript'},\n * // { id: 1, name: 'TypeScript'} ]\n * //\n * // [ { id: 2, name: 'Parcel'},\n * // { id: 2, name: 'webpack'} ]\n * //\n * // [ { id: 3, name: 'TSLint'} ]\n * ```\n *\n * ### Pivot data on the id field\n *\n * ```ts\n * import { of } from 'rxjs';\n * import { groupBy, map, mergeMap, reduce } from 'rxjs/operators';\n *\n * of(\n * { id: 1, name: 'JavaScript' },\n * { id: 2, name: 'Parcel' },\n * { id: 2, name: 'webpack' },\n * { id: 1, name: 'TypeScript' },\n * { id: 3, name: 'TSLint' }\n * )\n * .pipe(\n * groupBy(p => p.id, p => p.name),\n * mergeMap(group$ =>\n * group$.pipe(reduce((acc, cur) => [...acc, cur], [`${group$.key}`]))\n * ),\n * map(arr => ({ id: parseInt(arr[0], 10), values: arr.slice(1) }))\n * )\n * .subscribe(p => console.log(p));\n *\n * // displays:\n * // { id: 1, values: [ 'JavaScript', 'TypeScript' ] }\n * // { id: 2, values: [ 'Parcel', 'webpack' ] }\n * // { id: 3, values: [ 'TSLint' ] }\n * ```\n *\n * @param {function(value: T): K} keySelector A function that extracts the key\n * for each item.\n * @param {function(value: T): R} [elementSelector] A function that extracts the\n * return element for each item.\n * @param {function(grouped: GroupedObservable<K,R>): Observable<any>} [durationSelector]\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @return {Observable<GroupedObservable<K,R>>} An Observable that emits\n * GroupedObservables, each of which corresponds to a unique key value and each\n * of which emits those items from the source Observable that share that key\n * value.\n * @method groupBy\n * @owner Observable\n */\nexport function groupBy<T, K, R>(keySelector: (value: T) => K,\n elementSelector?: ((value: T) => R) | void,\n durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n subjectSelector?: () => Subject<R>): OperatorFunction<T, GroupedObservable<K, R>> {\n return (source: Observable<T>) =>\n source.lift(new GroupByOperator(keySelector, elementSelector, durationSelector, subjectSelector));\n}\n\nexport interface RefCountSubscription {\n count: number;\n unsubscribe: () => void;\n closed: boolean;\n attemptedToUnsubscribe: boolean;\n}\n\nclass GroupByOperator<T, K, R> implements Operator<T, GroupedObservable<K, R>> {\n constructor(private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n private subjectSelector?: () => Subject<R>) {\n }\n\n call(subscriber: Subscriber<GroupedObservable<K, R>>, source: any): any {\n return source.subscribe(new GroupBySubscriber(\n subscriber, this.keySelector, this.elementSelector, this.durationSelector, this.subjectSelector\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupBySubscriber<T, K, R> extends Subscriber<T> implements RefCountSubscription {\n private groups: Map<K, Subject<T | R>> = null;\n public attemptedToUnsubscribe: boolean = false;\n public count: number = 0;\n\n constructor(destination: Subscriber<GroupedObservable<K, R>>,\n private keySelector: (value: T) => K,\n private elementSelector?: ((value: T) => R) | void,\n private durationSelector?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n private subjectSelector?: () => Subject<R>) {\n super(destination);\n }\n\n protected _next(value: T): void {\n let key: K;\n try {\n key = this.keySelector(value);\n } catch (err) {\n this.error(err);\n return;\n }\n\n this._group(value, key);\n }\n\n private _group(value: T, key: K) {\n let groups = this.groups;\n\n if (!groups) {\n groups = this.groups = new Map<K, Subject<T | R>>();\n }\n\n let group = groups.get(key);\n\n let element: R;\n if (this.elementSelector) {\n try {\n element = this.elementSelector(value);\n } catch (err) {\n this.error(err);\n }\n } else {\n element = <any>value;\n }\n\n if (!group) {\n group = (this.subjectSelector ? this.subjectSelector() : new Subject<R>()) as Subject<T | R>;\n groups.set(key, group);\n const groupedObservable = new GroupedObservable(key, group, this);\n this.destination.next(groupedObservable);\n if (this.durationSelector) {\n let duration: any;\n try {\n duration = this.durationSelector(new GroupedObservable<K, R>(key, <Subject<R>>group));\n } catch (err) {\n this.error(err);\n return;\n }\n this.add(duration.subscribe(new GroupDurationSubscriber(key, group, this)));\n }\n }\n\n if (!group.closed) {\n group.next(element);\n }\n }\n\n protected _error(err: any): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.error(err);\n });\n\n groups.clear();\n }\n this.destination.error(err);\n }\n\n protected _complete(): void {\n const groups = this.groups;\n if (groups) {\n groups.forEach((group, key) => {\n group.complete();\n });\n\n groups.clear();\n }\n this.destination.complete();\n }\n\n removeGroup(key: K): void {\n this.groups.delete(key);\n }\n\n unsubscribe() {\n if (!this.closed) {\n this.attemptedToUnsubscribe = true;\n if (this.count === 0) {\n super.unsubscribe();\n }\n }\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass GroupDurationSubscriber<K, T> extends Subscriber<T> {\n constructor(private key: K,\n private group: Subject<T>,\n private parent: GroupBySubscriber<any, K, T | any>) {\n super(group);\n }\n\n protected _next(value: T): void {\n this.complete();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _unsubscribe() {\n const { parent, key } = this;\n this.key = this.parent = null;\n if (parent) {\n parent.removeGroup(key);\n }\n }\n}\n\n/**\n * An Observable representing values belonging to the same group represented by\n * a common key. The values emitted by a GroupedObservable come from the source\n * Observable. The common key is available as the field `key` on a\n * GroupedObservable instance.\n *\n * @class GroupedObservable<K, T>\n */\nexport class GroupedObservable<K, T> extends Observable<T> {\n /** @deprecated Do not construct this type. Internal use only */\n constructor(public key: K,\n private groupSubject: Subject<T>,\n private refCountSubscription?: RefCountSubscription) {\n super();\n }\n\n /** @deprecated This is an internal implementation detail, do not use. */\n _subscribe(subscriber: Subscriber<T>) {\n const subscription = new Subscription();\n const { refCountSubscription, groupSubject } = this;\n if (refCountSubscription && !refCountSubscription.closed) {\n subscription.add(new InnerRefCountSubscription(refCountSubscription));\n }\n subscription.add(groupSubject.subscribe(subscriber));\n return subscription;\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass InnerRefCountSubscription extends Subscription {\n constructor(private parent: RefCountSubscription) {\n super();\n parent.count++;\n }\n\n unsubscribe() {\n const parent = this.parent;\n if (!parent.closed && !this.closed) {\n super.unsubscribe();\n parent.count -= 1;\n if (parent.count === 0 && parent.attemptedToUnsubscribe) {\n parent.unsubscribe();\n }\n }\n }\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Subscribes to an ArrayLike with a subscriber\n * @param array The array or array-like to subscribe to\n */\nexport const subscribeToArray = <T>(array: ArrayLike<T>) => (subscriber: Subscriber<T>) => {\n for (let i = 0, len = array.length; i < len && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n};\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let i = 0;\n sub.add(scheduler.schedule(function () {\n if (i === input.length) {\n subscriber.complete();\n return;\n }\n subscriber.next(input[i++]);\n if (!subscriber.closed) {\n sub.add(this.schedule());\n }\n }));\n return sub;\n });\n}\n","import { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\n\n/**\n * Applies a given `project` function to each value emitted by the source\n * Observable, and emits the resulting values as an Observable.\n *\n * <span class=\"informal\">Like [Array.prototype.map()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map),\n * it passes each source value through a transformation function to get\n * corresponding output values.</span>\n *\n * ![](map.png)\n *\n * Similar to the well known `Array.prototype.map` function, this operator\n * applies a projection to each value and emits that projection in the output\n * Observable.\n *\n * ## Example\n * Map every click to the clientX position of that click\n * ```ts\n * import { fromEvent } from 'rxjs';\n * import { map } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param {function(value: T, index: number): R} project The function to apply\n * to each `value` emitted by the source Observable. The `index` parameter is\n * the number `i` for the i-th emission that has happened since the\n * subscription, starting from the number `0`.\n * @param {any} [thisArg] An optional argument to define what `this` is in the\n * `project` function.\n * @return {Observable<R>} An Observable that emits the values from the source\n * Observable transformed by the given `project` function.\n * @method map\n * @owner Observable\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return function mapOperation(source: Observable<T>): Observable<R> {\n if (typeof project !== 'function') {\n throw new TypeError('argument is not a function. Are you looking for `mapTo()`?');\n }\n return source.lift(new MapOperator(project, thisArg));\n };\n}\n\nexport class MapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => R, private thisArg: any) {\n }\n\n call(subscriber: Subscriber<R>, source: any): any {\n return source.subscribe(new MapSubscriber(subscriber, this.project, this.thisArg));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nclass MapSubscriber<T, R> extends Subscriber<T> {\n count: number = 0;\n private thisArg: any;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => R,\n thisArg: any) {\n super(destination);\n this.thisArg = thisArg || this;\n }\n\n // NOTE: This looks unoptimized, but it's actually purposefully NOT\n // using try/catch optimizations.\n protected _next(value: T) {\n let result: R;\n try {\n result = this.project.call(this.thisArg, value, this.count++);\n } catch (err) {\n this.destination.error(err);\n return;\n }\n this.destination.next(result);\n }\n}\n","import { Subscriber } from '../Subscriber';\nimport { hostReportError } from './hostReportError';\n\nexport const subscribeToPromise = <T>(promise: PromiseLike<T>) => (subscriber: Subscriber<T>) => {\n promise.then(\n (value) => {\n if (!subscriber.closed) {\n subscriber.next(value);\n subscriber.complete();\n }\n },\n (err: any) => subscriber.error(err)\n )\n .then(null, hostReportError);\n return subscriber;\n};\n","export function getSymbolIterator(): symbol {\n if (typeof Symbol !== 'function' || !Symbol.iterator) {\n return '@@iterator' as any;\n }\n\n return Symbol.iterator;\n}\n\nexport const iterator = getSymbolIterator();\n\n/**\n * @deprecated use {@link iterator} instead\n */\nexport const $$iterator = iterator;\n","import { Subscriber } from '../Subscriber';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport const subscribeToIterable = <T>(iterable: Iterable<T>) => (subscriber: Subscriber<T>) => {\n const iterator = (iterable as any)[Symbol_iterator]();\n\n do {\n let item: IteratorResult<T>;\n try {\n item = iterator.next();\n } catch (err) {\n subscriber.error(err);\n return subscriber;\n }\n if (item.done) {\n subscriber.complete();\n break;\n }\n subscriber.next(item.value);\n if (subscriber.closed) {\n break;\n }\n } while (true);\n\n // Finalize the iterator if it happens to be a Generator\n if (typeof iterator.return === 'function') {\n subscriber.add(() => {\n if (iterator.return) {\n iterator.return();\n }\n });\n }\n\n return subscriber;\n};\n","import { Subscriber } from '../Subscriber';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/**\n * Subscribes to an object that implements Symbol.observable with the given\n * Subscriber.\n * @param obj An object that implements Symbol.observable\n */\nexport const subscribeToObservable = <T>(obj: any) => (subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (typeof obs.subscribe !== 'function') {\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n } else {\n return obs.subscribe(subscriber);\n }\n};\n","/**\n * Tests to see if the object is an ES2015 (ES6) Promise\n * @see {@link https://www.ecma-international.org/ecma-262/6.0/#sec-promise-objects}\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return !!value && typeof (<any>value).subscribe !== 'function' && typeof (value as any).then === 'function';\n}\n","import { ObservableInput } from '../types';\nimport { subscribeToArray } from './subscribeToArray';\nimport { subscribeToPromise } from './subscribeToPromise';\nimport { subscribeToIterable } from './subscribeToIterable';\nimport { subscribeToObservable } from './subscribeToObservable';\nimport { isArrayLike } from './isArrayLike';\nimport { isPromise } from './isPromise';\nimport { isObject } from './isObject';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { Subscription } from '../Subscription';\nimport { Subscriber } from '../Subscriber';\n\nexport const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {\n if (!!result && typeof result[Symbol_observable] === 'function') {\n return subscribeToObservable(result as any);\n } else if (isArrayLike(result)) {\n return subscribeToArray(result);\n } else if (isPromise(result)) {\n return subscribeToPromise(result as Promise<any>);\n } else if (!!result && typeof result[Symbol_iterator] === 'function') {\n return subscribeToIterable(result as any);\n } else {\n const value = isObject(result) ? 'an invalid object' : `'${result}'`;\n const msg = `You provided ${value} where a stream was expected.`\n + ' You can provide an Observable, Promise, Array, or Iterable.';\n throw new TypeError(msg);\n }\n};\n","import { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { InteropObservable, SchedulerLike, Subscribable } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => {\n const observable: Subscribable<T> = input[Symbol_observable]();\n sub.add(observable.subscribe({\n next(value) { sub.add(scheduler.schedule(() => subscriber.next(value))); },\n error(err) { sub.add(scheduler.schedule(() => subscriber.error(err))); },\n complete() { sub.add(scheduler.schedule(() => subscriber.complete())); },\n }));\n }));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n sub.add(scheduler.schedule(() => input.then(\n value => {\n sub.add(scheduler.schedule(() => {\n subscriber.next(value);\n sub.add(scheduler.schedule(() => subscriber.complete()));\n }));\n },\n err => {\n sub.add(scheduler.schedule(() => subscriber.error(err)));\n }\n )));\n return sub;\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { Subscription } from '../Subscription';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\n\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>(subscriber => {\n const sub = new Subscription();\n let iterator: Iterator<T>;\n sub.add(() => {\n // Finalize generators\n if (iterator && typeof iterator.return === 'function') {\n iterator.return();\n }\n });\n sub.add(scheduler.schedule(() => {\n iterator = input[Symbol_iterator]();\n sub.add(scheduler.schedule(function () {\n if (subscriber.closed) {\n return;\n }\n let value: T;\n let done: boolean;\n try {\n const result = iterator.next();\n value = result.value;\n done = result.done;\n } catch (err) {\n subscriber.error(err);\n return;\n }\n if (done) {\n subscriber.complete();\n } else {\n subscriber.next(value);\n this.schedule();\n }\n }));\n }));\n return sub;\n });\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\n/** Identifies an input as being Observable (but not necessary an Rx Observable) */\nexport function isInteropObservable(input: any): input is InteropObservable<any> {\n return input && typeof input[Symbol_observable] === 'function';\n}\n","import { iterator as Symbol_iterator } from '../symbol/iterator';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return input && typeof input[Symbol_iterator] === 'function';\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { ObservableInput, SchedulerLike, Observable } from 'rxjs';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\n\n/**\n * Converts from a common {@link ObservableInput} type to an observable where subscription and emissions\n * are scheduled on the provided scheduler.\n *\n * @see from\n * @see of\n *\n * @param input The observable, array, promise, iterable, etc you would like to schedule\n * @param scheduler The scheduler to use to schedule the subscription and emissions from\n * the returned observable.\n */\nexport function scheduled<T>(input: ObservableInput<T>, scheduler: SchedulerLike): Observable<T> {\n if (input != null) {\n if (isInteropObservable(input)) {\n return scheduleObservable(input, scheduler);\n } else if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n } else if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n } else if (isIterable(input) || typeof input === 'string') {\n return scheduleIterable(input, scheduler);\n }\n }\n\n throw new TypeError((input !== null && typeof input || input) + ' is not observable');\n}\n","import { Observable } from '../Observable';\nimport { subscribeTo } from '../util/subscribeTo';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated use {@link scheduled} instead. */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike): Observable<ObservedValueOf<O>>;\n\n/**\n * Creates an Observable from an Array, an array-like object, a Promise, an iterable object, or an Observable-like object.\n *\n * <span class=\"informal\">Converts almost anything to an Observable.</span>\n *\n * ![](from.png)\n *\n * `from` converts various other objects and data types into Observables. It also converts a Promise, an array-like, or an\n * <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable\" target=\"_blank\">iterable</a>\n * object into an Observable that emits the items in that promise, array, or iterable. A String, in this context, is treated\n * as an array of characters. Observable-like objects (contains a function named with the ES2015 Symbol for Observable) can also be\n * converted through this operator.\n *\n * ## Examples\n *\n * ### Converts an array to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n *\n * const array = [10, 20, 30];\n * const result = from(array);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 10\n * // 20\n * // 30\n * ```\n *\n * ---\n *\n * ### Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from } from 'rxjs';\n * import { take } from 'rxjs/operators';\n *\n * function* generateDoubles(seed) {\n * let i = seed;\n * while (true) {\n * yield i;\n * i = 2 * i; // double it\n * }\n * }\n *\n * const iterator = generateDoubles(3);\n * const result = from(iterator).pipe(take(10));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 3\n * // 6\n * // 12\n * // 24\n * // 48\n * // 96\n * // 192\n * // 384\n * // 768\n * // 1536\n * ```\n *\n * ---\n *\n * ### With async scheduler\n *\n * ```ts\n * import { from, asyncScheduler } from 'rxjs';\n *\n * console.log('start');\n *\n * const array = [10, 20, 30];\n * const result = from(array, asyncScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * console.log('end');\n *\n * // Logs:\n * // start\n * // end\n * // 10\n * // 20\n * // 30\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link fromEventPattern}\n *\n * @param {ObservableInput<T>} A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param {SchedulerLike} An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return {Observable<T>}\n * @name from\n * @owner Observable\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n if (!scheduler) {\n if (input instanceof Observable) {\n return input;\n }\n return new Observable<T>(subscribeTo(input));\n } else {\n return scheduled(input, scheduler);\n }\n}\n","/** @prettier */\nimport { Subscription } from './Subscription';\nimport { Subscriber } from './Subscriber';\nimport { Observable } from './Observable';\nimport { subscribeTo } from './util/subscribeTo';\n\ninterface SimpleOuterSubscriberLike<T> {\n /**\n * A handler for inner next notifications from the inner subscription\n * @param innerValue the value nexted by the inner producer\n */\n notifyNext(innerValue: T): void;\n /**\n * A handler for inner error notifications from the inner subscription\n * @param err the error from the inner producer\n */\n notifyError(err: any): void;\n /**\n * A handler for inner complete notifications from the inner subscription.\n */\n notifyComplete(): void;\n}\n\nexport class SimpleInnerSubscriber<T> extends Subscriber<T> {\n constructor(private parent: SimpleOuterSubscriberLike<any>) {\n super();\n }\n\n protected _next(value: T): void {\n this.parent.notifyNext(value);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete();\n this.unsubscribe();\n }\n}\n\nexport class ComplexInnerSubscriber<T, R> extends Subscriber<R> {\n constructor(private parent: ComplexOuterSubscriber<T, R>, public outerValue: T, public outerIndex: number) {\n super();\n }\n\n protected _next(value: R): void {\n this.parent.notifyNext(this.outerValue, value, this.outerIndex, this);\n }\n\n protected _error(error: any): void {\n this.parent.notifyError(error);\n this.unsubscribe();\n }\n\n protected _complete(): void {\n this.parent.notifyComplete(this);\n this.unsubscribe();\n }\n}\n\nexport class SimpleOuterSubscriber<T, R> extends Subscriber<T> implements SimpleOuterSubscriberLike<R> {\n notifyNext(innerValue: R): void {\n this.destination.next(innerValue);\n }\n\n notifyError(err: any): void {\n this.destination.error(err);\n }\n\n notifyComplete(): void {\n this.destination.complete();\n }\n}\n\n/**\n * DO NOT USE (formerly \"OuterSubscriber\")\n * TODO: We want to refactor this and remove it. It is retaining values it shouldn't for long\n * periods of time.\n */\nexport class ComplexOuterSubscriber<T, R> extends Subscriber<T> {\n /**\n * @param _outerValue Used by: bufferToggle, delayWhen, windowToggle\n * @param innerValue Used by: subclass default, combineLatest, race, bufferToggle, windowToggle, withLatestFrom\n * @param _outerIndex Used by: combineLatest, race, withLatestFrom\n * @param _innerSub Used by: delayWhen\n */\n notifyNext(_outerValue: T, innerValue: R, _outerIndex: number, _innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.next(innerValue);\n }\n\n notifyError(error: any): void {\n this.destination.error(error);\n }\n\n /**\n * @param _innerSub Used by: race, bufferToggle, delayWhen, windowToggle, windowWhen\n */\n notifyComplete(_innerSub: ComplexInnerSubscriber<T, R>): void {\n this.destination.complete();\n }\n}\n\nexport function innerSubscribe(result: any, innerSubscriber: Subscriber<any>): Subscription | undefined {\n if (innerSubscriber.closed) {\n return undefined;\n }\n if (result instanceof Observable) {\n return result.subscribe(innerSubscriber);\n }\n let subscription: Subscription;\n try {\n subscription = subscribeTo(result)(innerSubscriber) as Subscription;\n } catch (error) {\n innerSubscriber.error(error);\n }\n return subscription;\n}\n","import { Observable } from '../Observable';\nimport { Operator } from '../Operator';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { from } from '../observable/from';\nimport { SimpleOuterSubscriber, SimpleInnerSubscriber, innerSubscribe } from '../innerSubscribe';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined, concurrent?: number): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R, concurrent?: number): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link mergeAll}.</span>\n *\n * ![](mergeMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an Observable, and then merging those resulting Observables and\n * emitting the results of this merger.\n *\n * ## Example\n * Map and flatten each letter to an Observable ticking every 1 second\n * ```ts\n * import { of, interval } from 'rxjs';\n * import { mergeMap, map } from 'rxjs/operators';\n *\n * const letters = of('a', 'b', 'c');\n * const result = letters.pipe(\n * mergeMap(x => interval(1000).pipe(map(i => x+i))),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // a0\n * // b0\n * // c0\n * // a1\n * // b1\n * // c1\n * // continues to list a,b,c with respective ascending integers\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @param {number} [concurrent=Number.POSITIVE_INFINITY] Maximum number of input\n * Observables being subscribed to concurrently.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item\n * emitted by the source Observable and merging the results of the Observables\n * obtained from this transformation.\n */\nexport function mergeMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Number.POSITIVE_INFINITY\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n if (typeof resultSelector === 'function') {\n // DEPRECATED PATH\n return (source: Observable<T>) => source.pipe(\n mergeMap((a, i) => from(project(a, i)).pipe(\n map((b: any, ii: number) => resultSelector(a, b, i, ii)),\n ), concurrent)\n );\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return (source: Observable<T>) => source.lift(new MergeMapOperator(project, concurrent));\n}\n\nexport class MergeMapOperator<T, R> implements Operator<T, R> {\n constructor(private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n }\n\n call(observer: Subscriber<R>, source: any): any {\n return source.subscribe(new MergeMapSubscriber(\n observer, this.project, this.concurrent\n ));\n }\n}\n\n/**\n * We need this JSDoc comment for affecting ESDoc.\n * @ignore\n * @extends {Ignored}\n */\nexport class MergeMapSubscriber<T, R> extends SimpleOuterSubscriber<T, R> {\n private hasCompleted: boolean = false;\n private buffer: T[] = [];\n private active: number = 0;\n protected index: number = 0;\n\n constructor(destination: Subscriber<R>,\n private project: (value: T, index: number) => ObservableInput<R>,\n private concurrent: number = Number.POSITIVE_INFINITY) {\n super(destination);\n }\n\n protected _next(value: T): void {\n if (this.active < this.concurrent) {\n this._tryNext(value);\n } else {\n this.buffer.push(value);\n }\n }\n\n protected _tryNext(value: T) {\n let result: ObservableInput<R>;\n const index = this.index++;\n try {\n result = this.project(value, index);\n } catch (err) {\n this.destination.error!(err);\n return;\n }\n this.active++;\n this._innerSub(result);\n }\n\n private _innerSub(ish: ObservableInput<R>): void {\n const innerSubscriber = new SimpleInnerSubscriber(this);\n const destination = this.destination as Subscription;\n destination.add(innerSubscriber);\n const innerSubscription = innerSubscribe(ish, innerSubscriber);\n // The returned subscription will usually be the subscriber that was\n // passed. However, interop subscribers will be wrapped and for\n // unsubscriptions to chain correctly, the wrapper needs to be added, too.\n if (innerSubscription !== innerSubscriber) {\n destination.add(innerSubscription);\n }\n }\n\n protected _complete(): void {\n this.hasCompleted = true;\n if (this.active === 0 && this.buffer.length === 0) {\n this.destination.complete!();\n }\n this.unsubscribe();\n }\n\n notifyNext(innerValue: R): void {\n this.destination.next!(innerValue);\n }\n\n notifyComplete(): void {\n const buffer = this.buffer;\n this.active--;\n if (buffer.length > 0) {\n this._next(buffer.shift()!);\n } else if (this.active === 0 && this.hasCompleted) {\n this.destination.complete!();\n }\n }\n}\n\n/**\n * @deprecated renamed. Use {@link mergeMap}\n */\nexport const flatMap = mergeMap;","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: undefined): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated resultSelector no longer supported, use inner map instead */\nexport function concatMap<T, R, O extends ObservableInput<any>>(project: (value: T, index: number) => O, resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to an Observable which is merged in the output\n * Observable, in a serialized fashion waiting for each one to complete before\n * merging the next.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link concatAll}.</span>\n *\n * ![](concatMap.png)\n *\n * Returns an Observable that emits items based on applying a function that you\n * supply to each item emitted by the source Observable, where that function\n * returns an (so-called \"inner\") Observable. Each new inner Observable is\n * concatenated with the previous inner Observable.\n *\n * __Warning:__ if source values arrive endlessly and faster than their\n * corresponding inner Observables can complete, it will result in memory issues\n * as inner Observables amass in an unbounded buffer waiting for their turn to\n * be subscribed to.\n *\n * Note: `concatMap` is equivalent to `mergeMap` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, interval } from 'rxjs';\n * import { concatMap, take } from 'rxjs/operators';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMap(ev => interval(1000).pipe(take(4)))\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // (results are not concurrent)\n * // For every click on the \"document\" it will emit values 0 to 3 spaced\n * // on a 1000ms interval\n * // one click = 1000ms-> 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3\n * ```\n *\n * @see {@link concat}\n * @see {@link concatAll}\n * @see {@link concatMapTo}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param {function(value: T, ?index: number): ObservableInput} project A function\n * that, when applied to an item emitted by the source Observable, returns an\n * Observable.\n * @return {Observable} An Observable that emits the result of applying the\n * projection function (and the optional deprecated `resultSelector`) to each item emitted\n * by the source Observable and taking values from each projected inner\n * Observable sequentially.\n * @method concatMap\n * @owner Observable\n */\nexport function concatMap<T, R, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O>|R> {\n return mergeMap(project, resultSelector, 1);\n}\n","/**\n * GraphDB Consumer\n *\n * Subscribes to resource events and updates GraphDB accordingly.\n * Makes GraphDB a projection of Event Store events (single source of truth).\n *\n * Uses an RxJS pipeline with adaptive burst buffering:\n * - First event after idle passes through immediately (zero latency)\n * - Subsequent events in a burst are batched and flushed together\n * - After idle, returns to passthrough mode\n *\n * Per-resource ordering is preserved via groupBy(resourceId) + concatMap.\n * Cross-resource parallelism is provided via mergeMap over groups.\n *\n * Burst buffer thresholds (see BATCH-GRAPH-CONSUMER-RX.md for tuning guidance):\n * BURST_WINDOW_MS = 50 — debounce window before flushing a batch\n * MAX_BATCH_SIZE = 500 — force flush to bound memory\n * IDLE_TIMEOUT_MS = 200 — silence before returning to passthrough\n */\n\nimport { Subject, Subscription, from } from 'rxjs';\nimport { groupBy, mergeMap, concatMap } from 'rxjs/operators';\nimport { EventQuery, type EventStore } from '@semiont/event-sourcing';\nimport { didToAgent, burstBuffer } from '@semiont/core';\nimport type { GraphDatabase } from '@semiont/graph';\nimport type { components } from '@semiont/core';\nimport type { ResourceEvent, StoredEvent, AnnotationAddedEvent, EnvironmentConfig, ResourceId, Logger } from '@semiont/core';\nimport { resourceId as makeResourceId, findBodyItem } from '@semiont/core';\nimport { toResourceUri, toAnnotationUri } from '@semiont/event-sourcing';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport class GraphDBConsumer {\n // Event types that produce GraphDB mutations — filter everything else\n private static readonly GRAPH_RELEVANT_EVENTS = new Set([\n 'resource.created', 'resource.archived', 'resource.unarchived',\n 'annotation.added', 'annotation.removed', 'annotation.body.updated',\n 'entitytag.added', 'entitytag.removed', 'entitytype.added',\n ]);\n\n // Burst buffer thresholds — see class doc and BATCH-GRAPH-CONSUMER-RX.md\n private static readonly BURST_WINDOW_MS = 50;\n private static readonly MAX_BATCH_SIZE = 500;\n private static readonly IDLE_TIMEOUT_MS = 200;\n\n private _globalSubscription: any = null;\n private eventSubject = new Subject<StoredEvent>();\n private pipelineSubscription: Subscription | null = null;\n private lastProcessed: Map<string, number> = new Map();\n private readonly logger: Logger;\n\n constructor(\n private config: EnvironmentConfig,\n private eventStore: EventStore,\n private graphDb: GraphDatabase,\n logger: Logger\n ) {\n this.logger = logger;\n }\n\n async initialize() {\n this.logger.info('GraphDB consumer initialized');\n await this.subscribeToGlobalEvents();\n }\n\n /**\n * Subscribe globally to ALL events, pre-filter to graph-relevant types,\n * and wire through the RxJS burst-buffered pipeline.\n */\n private async subscribeToGlobalEvents() {\n // Bridge: callback-based EventBus subscription → RxJS Subject\n this._globalSubscription = this.eventStore.bus.subscriptions.subscribeGlobal(\n (storedEvent: StoredEvent) => {\n if (!GraphDBConsumer.GRAPH_RELEVANT_EVENTS.has(storedEvent.event.type)) return;\n this.eventSubject.next(storedEvent);\n }\n );\n\n // Build the RxJS pipeline\n this.pipelineSubscription = this.eventSubject.pipe(\n // Split into one inner Observable per resource (system events grouped under '__system__')\n groupBy((se: StoredEvent) => se.event.resourceId ?? '__system__'),\n\n mergeMap((group) => {\n if (group.key === '__system__') {\n // System events (e.g., entitytype.added): process immediately, sequentially\n return group.pipe(\n concatMap((se) => from(this.safeApplyEvent(se)))\n );\n }\n\n // Resource events: apply burst buffering per resource group\n return group.pipe(\n burstBuffer<StoredEvent>({\n burstWindowMs: GraphDBConsumer.BURST_WINDOW_MS,\n maxBatchSize: GraphDBConsumer.MAX_BATCH_SIZE,\n idleTimeoutMs: GraphDBConsumer.IDLE_TIMEOUT_MS,\n }),\n concatMap((eventOrBatch: StoredEvent | StoredEvent[]) => {\n if (Array.isArray(eventOrBatch)) {\n return from(this.processBatch(eventOrBatch));\n }\n return from(this.safeApplyEvent(eventOrBatch).then(() => {\n this.lastProcessed.set(\n eventOrBatch.event.resourceId!,\n eventOrBatch.metadata.sequenceNumber\n );\n }));\n })\n );\n })\n ).subscribe({\n error: (err) => {\n this.logger.error('GraphDB consumer pipeline error', { error: err });\n }\n });\n\n this.logger.info('Subscribed to global events with burst-buffered pipeline');\n }\n\n /**\n * Wrap applyEventToGraph in try/catch so one failed event doesn't kill the pipeline.\n */\n private async safeApplyEvent(storedEvent: StoredEvent): Promise<void> {\n try {\n await this.applyEventToGraph(storedEvent);\n } catch (error) {\n this.logger.error('Failed to apply event to graph', {\n eventType: storedEvent.event.type,\n resourceId: storedEvent.event.resourceId,\n error,\n });\n }\n }\n\n private ensureInitialized(): GraphDatabase {\n return this.graphDb;\n }\n\n /**\n * Stop the consumer, flush remaining buffered events, and unsubscribe.\n */\n async stop() {\n this.logger.info('Stopping GraphDB consumer');\n\n // Unsubscribe from event source (stops feeding the Subject)\n if (this._globalSubscription && typeof this._globalSubscription.unsubscribe === 'function') {\n this._globalSubscription.unsubscribe();\n }\n this._globalSubscription = null;\n\n // Complete the Subject — this triggers burst buffer flush of remaining events\n this.eventSubject.complete();\n\n // Unsubscribe from the pipeline\n if (this.pipelineSubscription) {\n this.pipelineSubscription.unsubscribe();\n this.pipelineSubscription = null;\n }\n\n // Create a fresh Subject for potential re-initialization\n this.eventSubject = new Subject<StoredEvent>();\n\n this.logger.info('GraphDB consumer stopped');\n }\n\n /**\n * Process a batch of events for the same resource.\n * Partitions into consecutive same-type runs for batch optimization.\n */\n private async processBatch(events: StoredEvent[]): Promise<void> {\n // Partition into runs of consecutive same-type events\n const runs: StoredEvent[][] = [];\n let currentRun: StoredEvent[] = [];\n\n for (const event of events) {\n if (currentRun.length > 0 && currentRun[0].event.type !== event.event.type) {\n runs.push(currentRun);\n currentRun = [];\n }\n currentRun.push(event);\n }\n if (currentRun.length > 0) runs.push(currentRun);\n\n for (const run of runs) {\n try {\n if (run.length === 1) {\n await this.applyEventToGraph(run[0]);\n } else {\n await this.applyBatchByType(run);\n }\n } catch (error) {\n this.logger.error('Failed to process batch run', {\n eventType: run[0].event.type,\n runSize: run.length,\n error,\n });\n }\n const last = run[run.length - 1];\n if (last.event.resourceId) {\n this.lastProcessed.set(last.event.resourceId, last.metadata.sequenceNumber);\n }\n }\n\n this.logger.debug('Processed batch', {\n resourceId: events[0]?.event.resourceId,\n batchSize: events.length,\n });\n }\n\n /**\n * Batch-optimized processing for consecutive events of the same type.\n * Uses batch graph methods where available, falls back to sequential.\n */\n private async applyBatchByType(events: StoredEvent[]): Promise<void> {\n const graphDb = this.ensureInitialized();\n const type = events[0].event.type;\n\n switch (type) {\n case 'resource.created': {\n const resources = events.map(e => this.buildResourceDescriptor(e));\n await graphDb.batchCreateResources(resources);\n this.logger.info('Batch created resources in graph', { count: events.length });\n break;\n }\n case 'annotation.added': {\n const inputs = events.map(e => {\n const event = e.event as AnnotationAddedEvent;\n return {\n ...event.payload.annotation,\n creator: didToAgent(event.userId),\n };\n });\n await graphDb.createAnnotations(inputs);\n this.logger.info('Batch created annotations in graph', { count: events.length });\n break;\n }\n default:\n // For types without batch optimization, fall back to sequential\n for (const event of events) {\n await this.applyEventToGraph(event);\n }\n }\n }\n\n /**\n * Build a ResourceDescriptor from a resource.created event.\n * Extracted for reuse by both applyEventToGraph and applyBatchByType.\n */\n private buildResourceDescriptor(storedEvent: StoredEvent): ResourceDescriptor {\n const event = storedEvent.event;\n if (event.type !== 'resource.created') {\n throw new Error('Expected resource.created event');\n }\n if (!event.resourceId) {\n throw new Error('resource.created requires resourceId');\n }\n\n const resourceUri = toResourceUri(\n { baseUrl: this.config.services.backend!.publicURL },\n event.resourceId\n );\n\n return {\n '@context': 'https://schema.org/',\n '@id': resourceUri,\n name: event.payload.name,\n entityTypes: event.payload.entityTypes || [],\n representations: [{\n mediaType: event.payload.format,\n checksum: event.payload.contentChecksum,\n rel: 'original',\n }],\n archived: false,\n dateCreated: new Date().toISOString(),\n wasAttributedTo: didToAgent(event.userId),\n creationMethod: event.payload.creationMethod,\n };\n }\n\n /**\n * Apply a single event to GraphDB.\n */\n protected async applyEventToGraph(storedEvent: StoredEvent): Promise<void> {\n const graphDb = this.ensureInitialized();\n const event = storedEvent.event;\n\n this.logger.debug('Applying event to GraphDB', {\n eventType: event.type,\n sequenceNumber: storedEvent.metadata.sequenceNumber\n });\n\n switch (event.type) {\n case 'resource.created': {\n const resource = this.buildResourceDescriptor(storedEvent);\n this.logger.debug('Creating resource in graph', { resourceUri: resource['@id'] });\n await graphDb.createResource(resource);\n this.logger.info('Resource created in graph', { resourceUri: resource['@id'] });\n break;\n }\n\n case 'resource.archived':\n if (!event.resourceId) throw new Error('resource.archived requires resourceId');\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n archived: true,\n });\n break;\n\n case 'resource.unarchived':\n if (!event.resourceId) throw new Error('resource.unarchived requires resourceId');\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n archived: false,\n });\n break;\n\n case 'annotation.added':\n this.logger.debug('Processing annotation.added event', {\n annotationId: event.payload.annotation.id\n });\n await graphDb.createAnnotation({\n ...event.payload.annotation,\n creator: didToAgent(event.userId),\n });\n this.logger.info('Annotation created in graph', {\n annotationId: event.payload.annotation.id\n });\n break;\n\n case 'annotation.removed':\n await graphDb.deleteAnnotation(toAnnotationUri({ baseUrl: this.config.services.backend!.publicURL }, event.payload.annotationId));\n break;\n\n case 'annotation.body.updated':\n this.logger.debug('Processing annotation.body.updated event', {\n annotationId: event.payload.annotationId,\n payload: event.payload\n });\n try {\n const annotationUri = toAnnotationUri({ baseUrl: this.config.services.backend!.publicURL }, event.payload.annotationId);\n\n const currentAnnotation = await graphDb.getAnnotation(annotationUri);\n\n if (currentAnnotation) {\n let bodyArray = Array.isArray(currentAnnotation.body)\n ? [...currentAnnotation.body]\n : currentAnnotation.body\n ? [currentAnnotation.body]\n : [];\n\n for (const op of event.payload.operations) {\n if (op.op === 'add') {\n const exists = findBodyItem(bodyArray, op.item) !== -1;\n if (!exists) {\n bodyArray.push(op.item);\n }\n } else if (op.op === 'remove') {\n const index = findBodyItem(bodyArray, op.item);\n if (index !== -1) {\n bodyArray.splice(index, 1);\n }\n } else if (op.op === 'replace') {\n const index = findBodyItem(bodyArray, op.oldItem);\n if (index !== -1) {\n bodyArray[index] = op.newItem;\n }\n }\n }\n\n await graphDb.updateAnnotation(annotationUri, {\n body: bodyArray,\n } as Partial<Annotation>);\n\n this.logger.info('updateAnnotation completed successfully');\n } else {\n this.logger.warn('Annotation not found in graph, skipping update');\n }\n } catch (error) {\n this.logger.error('Error in annotation.body.updated handler', {\n annotationId: event.payload.annotationId,\n error,\n stack: error instanceof Error ? error.stack : undefined\n });\n }\n break;\n\n case 'entitytag.added':\n if (!event.resourceId) throw new Error('entitytag.added requires resourceId');\n {\n const doc = await graphDb.getResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId));\n if (doc) {\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n entityTypes: [...(doc.entityTypes || []), event.payload.entityType],\n });\n }\n }\n break;\n\n case 'entitytag.removed':\n if (!event.resourceId) throw new Error('entitytag.removed requires resourceId');\n {\n const doc = await graphDb.getResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId));\n if (doc) {\n await graphDb.updateResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, event.resourceId), {\n entityTypes: (doc.entityTypes || []).filter(t => t !== event.payload.entityType),\n });\n }\n }\n break;\n\n case 'entitytype.added':\n await graphDb.addEntityType(event.payload.entityType);\n break;\n\n default:\n this.logger.warn('Unknown event type', { eventType: (event as ResourceEvent).type });\n }\n }\n\n /**\n * Rebuild entire resource from events.\n * Bypasses the live pipeline — reads directly from event store.\n */\n async rebuildResource(resourceId: ResourceId): Promise<void> {\n const graphDb = this.ensureInitialized();\n this.logger.info('Rebuilding resource from events', { resourceId });\n\n try {\n await graphDb.deleteResource(toResourceUri({ baseUrl: this.config.services.backend!.publicURL }, makeResourceId(resourceId)));\n } catch (error) {\n this.logger.debug('No existing resource to delete', { resourceId });\n }\n\n const query = new EventQuery(this.eventStore.log.storage);\n const events = await query.getResourceEvents(resourceId);\n\n for (const storedEvent of events) {\n await this.applyEventToGraph(storedEvent);\n }\n\n this.logger.info('Resource rebuild complete', { resourceId, eventCount: events.length });\n }\n\n /**\n * Rebuild entire GraphDB from all events.\n * Uses two-pass approach to ensure all resources exist before creating REFERENCES edges.\n * Bypasses the live pipeline — reads directly from event store.\n */\n async rebuildAll(): Promise<void> {\n const graphDb = this.ensureInitialized();\n this.logger.info('Rebuilding entire GraphDB from events');\n this.logger.info('Using two-pass approach: nodes first, then edges');\n\n await graphDb.clearDatabase();\n\n const query = new EventQuery(this.eventStore.log.storage);\n const allResourceIds = await this.eventStore.log.getAllResourceIds();\n\n this.logger.info('Found resources to rebuild', { count: allResourceIds.length });\n\n // PASS 1: Create all nodes (resources and annotations)\n this.logger.info('PASS 1: Creating all nodes (resources + annotations)');\n for (const resourceId of allResourceIds) {\n const events = await query.getResourceEvents(makeResourceId(resourceId as string));\n\n for (const storedEvent of events) {\n if (storedEvent.event.type === 'annotation.body.updated') {\n continue;\n }\n await this.applyEventToGraph(storedEvent);\n }\n }\n this.logger.info('Pass 1 complete - all nodes created');\n\n // PASS 2: Create all edges (REFERENCES relationships)\n this.logger.info('PASS 2: Creating all REFERENCES edges');\n for (const resourceId of allResourceIds) {\n const events = await query.getResourceEvents(makeResourceId(resourceId as string));\n\n for (const storedEvent of events) {\n if (storedEvent.event.type === 'annotation.body.updated') {\n await this.applyEventToGraph(storedEvent);\n }\n }\n }\n this.logger.info('Pass 2 complete - all edges created');\n\n this.logger.info('Rebuild complete');\n }\n\n /**\n * Get consumer health metrics.\n */\n getHealthMetrics(): {\n subscriptions: number;\n lastProcessed: Record<string, number>;\n pipelineActive: boolean;\n } {\n return {\n subscriptions: this._globalSubscription ? 1 : 0,\n lastProcessed: Object.fromEntries(this.lastProcessed),\n pipelineActive: !!this.pipelineSubscription,\n };\n }\n\n /**\n * Shutdown consumer.\n */\n async shutdown(): Promise<void> {\n await this.stop();\n this.logger.info('GraphDB consumer shut down');\n }\n}\n","/**\n * Entity Types Bootstrap Service\n *\n * On startup, checks if the entity types projection exists.\n * If not, emits entitytype.added events for each DEFAULT_ENTITY_TYPES entry.\n * This ensures the system has entity types available immediately after first deployment.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { EventStore } from '@semiont/event-sourcing';\nimport { DEFAULT_ENTITY_TYPES } from '@semiont/ontology';\nimport { userId, type EnvironmentConfig, type Logger } from '@semiont/core';\n\n// Singleton flag to ensure bootstrap only runs once per process\nlet bootstrapCompleted = false;\n\n/**\n * Bootstrap entity types projection if it doesn't exist.\n * Uses a system user ID (00000000-0000-0000-0000-000000000000) for bootstrap events.\n */\nexport async function bootstrapEntityTypes(eventStore: EventStore, config: EnvironmentConfig, logger?: Logger): Promise<void> {\n if (bootstrapCompleted) {\n logger?.debug('Entity types bootstrap already completed, skipping');\n return;\n }\n\n // Resolve basePath against project root if relative\n const configuredPath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n const projectionPath = path.join(\n basePath,\n 'projections',\n '__system__',\n 'entitytypes.json'\n );\n\n try {\n // Check if projection exists\n await fs.access(projectionPath);\n logger?.info('Entity types projection already exists, skipping bootstrap');\n bootstrapCompleted = true;\n return;\n } catch (error: any) {\n if (error.code !== 'ENOENT') {\n throw error;\n }\n // File doesn't exist - proceed with bootstrap\n logger?.info('Entity types projection does not exist, bootstrapping with DEFAULT_ENTITY_TYPES');\n }\n\n // System user ID for bootstrap events\n const SYSTEM_USER_ID = userId('00000000-0000-0000-0000-000000000000');\n\n // Emit one entitytype.added event for each default entity type\n for (const entityType of DEFAULT_ENTITY_TYPES) {\n logger?.debug('Emitting entitytype.added event', { entityType });\n await eventStore.appendEvent({\n type: 'entitytype.added',\n // resourceId: undefined - system-level event\n userId: SYSTEM_USER_ID,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n\n logger?.info('Entity types bootstrap completed', { count: DEFAULT_ENTITY_TYPES.length });\n bootstrapCompleted = true;\n}\n\n/**\n * Reset the bootstrap flag (used for testing)\n */\nexport function resetBootstrap(): void {\n bootstrapCompleted = false;\n}\n","/**\n * Entity Types Projection Reader\n *\n * Reads entity types from the view storage projection file.\n * This file is maintained by ViewMaterializer in response to entitytype.added events.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { EnvironmentConfig } from '@semiont/core';\n\n/**\n * Read entity types from view storage projection\n */\nexport async function readEntityTypesProjection(config: EnvironmentConfig): Promise<string[]> {\n // Resolve basePath against project root if relative\n const configuredPath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n let basePath: string;\n if (path.isAbsolute(configuredPath)) {\n basePath = configuredPath;\n } else if (projectRoot) {\n basePath = path.resolve(projectRoot, configuredPath);\n } else {\n basePath = path.resolve(configuredPath);\n }\n\n const entityTypesPath = path.join(\n basePath,\n 'projections',\n '__system__',\n 'entitytypes.json'\n );\n\n try {\n const content = await fs.readFile(entityTypesPath, 'utf-8');\n const projection = JSON.parse(content);\n return projection.entityTypes || [];\n } catch (error: any) {\n if (error.code === 'ENOENT') {\n // File doesn't exist yet - return empty array\n return [];\n }\n throw error;\n }\n}\n","/**\n * Resource Operations\n *\n * Business logic for resource operations including:\n * - Resource creation (ID generation, content storage, event emission)\n * - Archive/unarchive operations\n * - Entity type tagging (add/remove)\n * - Computing diffs and emitting appropriate events\n */\n\nimport type { EventStore } from '@semiont/event-sourcing';\nimport type { RepresentationStore } from '@semiont/content';\nimport type { components } from '@semiont/core';\nimport {\n CREATION_METHODS,\n type CreationMethod,\n resourceId,\n type UserId,\n type ResourceId,\n type EnvironmentConfig,\n} from '@semiont/core';\nimport { generateUuid } from './id-generation';\n\ntype CreateResourceResponse = components['schemas']['CreateResourceResponse'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype ContentFormat = components['schemas']['ContentFormat'];\n\nexport interface UpdateResourceInput {\n resourceId: ResourceId;\n userId: UserId;\n currentArchived?: boolean;\n updatedArchived?: boolean;\n currentEntityTypes?: string[];\n updatedEntityTypes?: string[];\n}\n\nexport interface CreateResourceInput {\n name: string;\n content: Buffer;\n format: ContentFormat;\n language?: string;\n entityTypes?: string[];\n creationMethod?: CreationMethod;\n}\n\nexport class ResourceOperations {\n /**\n * Create a new resource\n * Orchestrates: content storage → event emission → response building\n */\n static async createResource(\n input: CreateResourceInput,\n userId: UserId,\n eventStore: EventStore,\n repStore: RepresentationStore,\n config: EnvironmentConfig\n ): Promise<CreateResourceResponse> {\n // Generate resource ID\n const rId = resourceId(generateUuid());\n\n // Store content\n const storedRep = await repStore.store(input.content, {\n mediaType: input.format,\n language: input.language || undefined,\n rel: 'original',\n });\n\n // Validate creation method\n const validCreationMethods = Object.values(CREATION_METHODS) as string[];\n const validatedCreationMethod = input.creationMethod && validCreationMethods.includes(input.creationMethod)\n ? (input.creationMethod as CreationMethod)\n : CREATION_METHODS.API;\n\n // Emit resource.created event\n await eventStore.appendEvent({\n type: 'resource.created',\n resourceId: rId,\n userId,\n version: 1,\n payload: {\n name: input.name,\n format: input.format,\n contentChecksum: storedRep.checksum,\n contentByteSize: storedRep.byteSize,\n creationMethod: validatedCreationMethod,\n entityTypes: input.entityTypes || [],\n language: input.language || undefined,\n isDraft: false,\n generatedFrom: undefined,\n generationPrompt: undefined,\n },\n });\n\n // Build and return response\n const backendUrl = config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n const normalizedBase = backendUrl.endsWith('/') ? backendUrl.slice(0, -1) : backendUrl;\n\n const resourceMetadata: ResourceDescriptor = {\n '@context': 'https://schema.org/',\n '@id': `${normalizedBase}/resources/${rId}`,\n name: input.name,\n archived: false,\n entityTypes: input.entityTypes || [],\n creationMethod: validatedCreationMethod,\n dateCreated: new Date().toISOString(),\n representations: [\n {\n mediaType: storedRep.mediaType,\n checksum: storedRep.checksum,\n byteSize: storedRep.byteSize,\n rel: 'original',\n language: storedRep.language,\n },\n ],\n };\n\n return {\n resource: resourceMetadata,\n annotations: [],\n };\n }\n\n /**\n * Update resource metadata by computing diffs and emitting events\n * Handles: archived status changes, entity type additions/removals\n */\n static async updateResource(\n input: UpdateResourceInput,\n eventStore: EventStore\n ): Promise<void> {\n // Handle archived status change\n if (input.updatedArchived !== undefined && input.updatedArchived !== input.currentArchived) {\n await this.updateArchivedStatus(\n input.resourceId,\n input.userId,\n input.updatedArchived,\n eventStore\n );\n }\n\n // Handle entity type changes\n if (input.updatedEntityTypes && input.currentEntityTypes) {\n await this.updateEntityTypes(\n input.resourceId,\n input.userId,\n input.currentEntityTypes,\n input.updatedEntityTypes,\n eventStore\n );\n }\n }\n\n /**\n * Update archived status by emitting resource.archived or resource.unarchived event\n */\n private static async updateArchivedStatus(\n resourceId: ResourceId,\n userId: UserId,\n archived: boolean,\n eventStore: EventStore\n ): Promise<void> {\n if (archived) {\n await eventStore.appendEvent({\n type: 'resource.archived',\n resourceId,\n userId,\n version: 1,\n payload: {\n reason: undefined,\n },\n });\n } else {\n await eventStore.appendEvent({\n type: 'resource.unarchived',\n resourceId,\n userId,\n version: 1,\n payload: {},\n });\n }\n }\n\n /**\n * Update entity types by computing diff and emitting events for added/removed types\n */\n private static async updateEntityTypes(\n resourceId: ResourceId,\n userId: UserId,\n currentEntityTypes: string[],\n updatedEntityTypes: string[],\n eventStore: EventStore\n ): Promise<void> {\n const diff = this.computeEntityTypeDiff(currentEntityTypes, updatedEntityTypes);\n\n // Emit entitytag.added for new types\n for (const entityType of diff.added) {\n await eventStore.appendEvent({\n type: 'entitytag.added',\n resourceId,\n userId,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n\n // Emit entitytag.removed for removed types\n for (const entityType of diff.removed) {\n await eventStore.appendEvent({\n type: 'entitytag.removed',\n resourceId,\n userId,\n version: 1,\n payload: {\n entityType,\n },\n });\n }\n }\n\n /**\n * Compute diff between current and updated entity types\n * Returns arrays of added and removed entity types\n */\n private static computeEntityTypeDiff(\n current: string[],\n updated: string[]\n ): { added: string[]; removed: string[] } {\n const added = updated.filter(et => !current.includes(et));\n const removed = current.filter(et => !updated.includes(et));\n return { added, removed };\n }\n}\n","/**\n * Annotation Operations\n *\n * Business logic for annotation CRUD operations:\n * - Create annotations (ID generation, validation, event emission)\n * - Update annotation body (operations: add/remove/replace)\n * - Delete annotations (validation, event emission)\n *\n */\n\nimport type { EventStore } from '@semiont/event-sourcing';\nimport { generateAnnotationId } from '@semiont/event-sourcing';\nimport type { components } from '@semiont/core';\nimport { getTextPositionSelector, getTargetSource } from '@semiont/api-client';\nimport type {\n AnnotationAddedEvent,\n BodyOperation,\n EnvironmentConfig,\n ResourceId,\n UserId,\n Logger,\n} from '@semiont/core';\nimport { annotationId, uriToResourceId, uriToAnnotationId } from '@semiont/core';\nimport { AnnotationContext } from './annotation-context';\n\ntype Annotation = components['schemas']['Annotation'];\ntype CreateAnnotationRequest = components['schemas']['CreateAnnotationRequest'];\ntype UpdateAnnotationBodyRequest = components['schemas']['UpdateAnnotationBodyRequest'];\n\nexport interface CreateAnnotationResult {\n annotation: Annotation;\n}\n\nexport interface UpdateAnnotationBodyResult {\n annotation: Annotation;\n}\n\nexport class AnnotationOperations {\n /**\n * Create a new annotation\n */\n static async createAnnotation(\n request: CreateAnnotationRequest,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig\n ): Promise<CreateAnnotationResult> {\n // Generate annotation ID\n const backendUrl = config.services.backend?.publicURL;\n if (!backendUrl) {\n throw new Error('Backend publicURL not configured');\n }\n const newAnnotationId = generateAnnotationId(backendUrl);\n\n // Validate required fields\n const posSelector = getTextPositionSelector(request.target.selector);\n if (!posSelector) {\n throw new Error('TextPositionSelector required for creating annotations');\n }\n\n if (!request.motivation) {\n throw new Error('motivation is required');\n }\n\n // Build annotation object\n const annotation: Annotation = {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n id: newAnnotationId,\n motivation: request.motivation,\n target: request.target,\n body: request.body as Annotation['body'],\n created: new Date().toISOString(),\n modified: new Date().toISOString(),\n };\n\n // Emit annotation.added event\n const eventPayload: Omit<AnnotationAddedEvent, 'id' | 'timestamp'> = {\n type: 'annotation.added',\n resourceId: uriToResourceId(request.target.source),\n userId,\n version: 1,\n payload: {\n annotation: {\n '@context': annotation['@context'],\n 'type': annotation.type,\n id: annotation.id,\n motivation: annotation.motivation,\n target: annotation.target,\n body: annotation.body,\n modified: annotation.modified,\n },\n },\n };\n await eventStore.appendEvent(eventPayload);\n\n return { annotation };\n }\n\n /**\n * Update annotation body with operations (add/remove/replace)\n */\n static async updateAnnotationBody(\n id: string,\n request: UpdateAnnotationBodyRequest,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig\n ): Promise<UpdateAnnotationBodyResult> {\n // Get annotation from view storage\n const annotation = await AnnotationContext.getAnnotation(\n annotationId(id),\n uriToResourceId(request.resourceId) as ResourceId,\n config\n );\n\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Emit annotation.body.updated event\n await eventStore.appendEvent({\n type: 'annotation.body.updated',\n resourceId: uriToResourceId(getTargetSource(annotation.target)),\n userId,\n version: 1,\n payload: {\n annotationId: annotationId(id),\n operations: request.operations as BodyOperation[],\n },\n });\n\n // Apply operations optimistically for response\n const updatedBody = this.applyBodyOperations(annotation.body, request.operations);\n\n return {\n annotation: {\n ...annotation,\n body: updatedBody,\n },\n };\n }\n\n /**\n * Delete an annotation\n */\n static async deleteAnnotation(\n id: string,\n resourceIdUri: string,\n userId: UserId,\n eventStore: EventStore,\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<void> {\n const resourceId = uriToResourceId(resourceIdUri);\n\n // Verify annotation exists\n const projection = await AnnotationContext.getResourceAnnotations(resourceId, config);\n const annotation = projection.annotations.find((a: Annotation) => a.id === id);\n\n if (!annotation) {\n throw new Error('Annotation not found in resource');\n }\n\n // Emit annotation.removed event\n logger?.debug('Emitting annotation.removed event', { annotationId: id });\n const storedEvent = await eventStore.appendEvent({\n type: 'annotation.removed',\n resourceId,\n userId,\n version: 1,\n payload: {\n annotationId: uriToAnnotationId(id),\n },\n });\n logger?.debug('Event emitted', { sequenceNumber: storedEvent.metadata.sequenceNumber });\n }\n\n /**\n * Apply body operations (add/remove/replace) to annotation body\n */\n private static applyBodyOperations(\n body: Annotation['body'],\n operations: UpdateAnnotationBodyRequest['operations']\n ): Annotation['body'] {\n const bodyArray = Array.isArray(body) ? [...body] : [];\n\n for (const op of operations) {\n if (op.op === 'add') {\n // Add item (idempotent - don't add if already exists)\n const exists = bodyArray.some(item =>\n JSON.stringify(item) === JSON.stringify(op.item)\n );\n if (!exists) {\n bodyArray.push(op.item);\n }\n } else if (op.op === 'remove') {\n // Remove item\n const index = bodyArray.findIndex(item =>\n JSON.stringify(item) === JSON.stringify(op.item)\n );\n if (index !== -1) {\n bodyArray.splice(index, 1);\n }\n } else if (op.op === 'replace') {\n // Replace item\n const index = bodyArray.findIndex(item =>\n JSON.stringify(item) === JSON.stringify(op.oldItem)\n );\n if (index !== -1) {\n bodyArray[index] = op.newItem;\n }\n }\n }\n\n return bodyArray;\n }\n}\n","/**\n * Annotation Context\n *\n * Assembles annotation context from view storage and content store.\n * Provides methods for:\n * - Getting resource annotations\n * - Building LLM context for annotations\n * - Extracting annotation text context\n * - Generating AI summaries\n *\n * NOTE: This class contains static utility methods without logger access.\n * Console statements kept for debugging - consider adding logger parameter in future.\n */\n\nimport { getInferenceClient } from '@semiont/inference';\nimport { generateResourceSummary } from './generation/resource-generation';\nimport {\n getBodySource,\n getTargetSource,\n getTargetSelector,\n getResourceEntityTypes,\n getTextPositionSelector,\n getPrimaryRepresentation,\n decodeRepresentation,\n} from '@semiont/api-client';\nimport type { components, AnnotationUri, YieldContext } from '@semiont/core';\n\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport type {\n EnvironmentConfig,\n ResourceId,\n ResourceAnnotations,\n AnnotationId,\n AnnotationCategory,\n Logger,\n} from '@semiont/core';\nimport { resourceId as createResourceId, uriToResourceId } from '@semiont/core';\nimport { getEntityTypes } from '@semiont/ontology';\nimport { ResourceContext } from './resource-context';\n\ntype AnnotationLLMContextResponse = components['schemas']['AnnotationLLMContextResponse'];\ntype TextPositionSelector = components['schemas']['TextPositionSelector'];\ntype TextQuoteSelector = components['schemas']['TextQuoteSelector'];\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype AnnotationContextResponse = components['schemas']['AnnotationContextResponse'];\ntype ContextualSummaryResponse = components['schemas']['ContextualSummaryResponse'];\n\nexport interface BuildContextOptions {\n includeSourceContext?: boolean;\n includeTargetContext?: boolean;\n contextWindow?: number;\n}\n\ninterface AnnotationTextContext {\n before: string;\n selected: string;\n after: string;\n}\n\nexport class AnnotationContext {\n /**\n * Build LLM context for an annotation\n *\n * @param annotationUri - Full annotation URI (e.g., http://localhost:4000/annotations/abc123)\n * @param resourceId - Source resource ID\n * @param config - Application configuration\n * @param options - Context building options\n * @returns Rich context for LLM processing\n * @throws Error if annotation or resource not found\n */\n static async buildLLMContext(\n annotationUri: AnnotationUri,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n options: BuildContextOptions = {},\n logger?: Logger\n ): Promise<AnnotationLLMContextResponse> {\n const {\n includeSourceContext = true,\n includeTargetContext = true,\n contextWindow = 1000\n } = options;\n\n // Validate contextWindow range\n if (contextWindow < 100 || contextWindow > 5000) {\n throw new Error('contextWindow must be between 100 and 5000');\n }\n\n logger?.debug('Building LLM context', { annotationUri, resourceId });\n\n const basePath = config.services.filesystem!.path;\n logger?.debug('Filesystem basePath', { basePath });\n\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get source resource view\n logger?.debug('Getting view for resource', { resourceId });\n let sourceView;\n try {\n sourceView = await viewStorage.get(resourceId);\n logger?.debug('Retrieved view', { hasView: !!sourceView });\n\n if (!sourceView) {\n throw new Error('Source resource not found');\n }\n } catch (error) {\n logger?.error('Error getting view', { resourceId, error });\n throw error;\n }\n\n logger?.debug('Looking for annotation in resource', {\n annotationUri,\n resourceId,\n totalAnnotations: sourceView.annotations.annotations.length,\n firstFiveIds: sourceView.annotations.annotations.slice(0, 5).map((a: Annotation) => a.id)\n });\n\n // Find the annotation in the view (annotations have full URIs as their id)\n const annotation = sourceView.annotations.annotations.find((a: Annotation) => a.id === annotationUri);\n logger?.debug('Annotation search result', { found: !!annotation });\n\n if (!annotation) {\n throw new Error('Annotation not found in view');\n }\n\n const targetSource = getTargetSource(annotation.target);\n // Extract resource ID from the target source URI (format: http://host/resources/{id})\n const targetResourceId = targetSource.split('/').pop();\n logger?.debug('Validating target resource', { targetSource, expectedResourceId: resourceId, extractedId: targetResourceId });\n\n if (targetResourceId !== resourceId) {\n throw new Error(`Annotation target resource ID (${targetResourceId}) does not match expected resource ID (${resourceId})`);\n }\n\n const sourceDoc = sourceView.resource;\n\n // Get target resource if annotation is a reference (has resolved body source)\n const bodySource = getBodySource(annotation.body);\n\n // Extract target document from body source URI if present\n let targetDoc = null;\n if (bodySource) {\n // Inline extraction: \"http://localhost:4000/resources/abc123\" → \"abc123\"\n const parts = (bodySource as string).split('/');\n const lastPart = parts[parts.length - 1];\n if (!lastPart) {\n throw new Error(`Invalid body source URI: ${bodySource}`);\n }\n const targetResourceId = createResourceId(lastPart);\n const targetView = await viewStorage.get(targetResourceId);\n targetDoc = targetView?.resource || null;\n }\n\n // Build source context if requested\n let sourceContext;\n if (includeSourceContext) {\n const primaryRep = getPrimaryRepresentation(sourceDoc);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Source content not found');\n }\n const sourceContent = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentStr = decodeRepresentation(sourceContent, primaryRep.mediaType);\n\n const targetSelectorRaw = getTargetSelector(annotation.target);\n\n // Handle array of selectors - take the first one\n const targetSelector = Array.isArray(targetSelectorRaw) ? targetSelectorRaw[0] : targetSelectorRaw;\n\n logger?.debug('Target selector', { type: targetSelector?.type });\n\n if (!targetSelector) {\n logger?.warn('No target selector found');\n } else if (targetSelector.type === 'TextPositionSelector') {\n // TypeScript now knows this is TextPositionSelector with required start/end\n const selector = targetSelector as TextPositionSelector;\n const start = selector.start;\n const end = selector.end;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = contentStr.slice(start, end);\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n logger?.debug('Built source context using TextPositionSelector', { start, end });\n } else if (targetSelector.type === 'TextQuoteSelector') {\n // TypeScript now knows this is TextQuoteSelector with required exact\n const selector = targetSelector as TextQuoteSelector;\n const exact = selector.exact;\n const index = contentStr.indexOf(exact);\n\n if (index !== -1) {\n const start = index;\n const end = index + exact.length;\n\n const before = contentStr.slice(Math.max(0, start - contextWindow), start);\n const selected = exact;\n const after = contentStr.slice(end, Math.min(contentStr.length, end + contextWindow));\n\n sourceContext = { before, selected, after };\n logger?.debug('Built source context using TextQuoteSelector', { foundAt: index });\n } else {\n logger?.warn('TextQuoteSelector exact text not found in content', { exactPreview: exact.substring(0, 50) });\n }\n } else {\n logger?.warn('Unknown selector type', { type: (targetSelector as any).type });\n }\n }\n\n // Build target context if requested and available\n let targetContext;\n if (includeTargetContext && targetDoc) {\n const targetRep = getPrimaryRepresentation(targetDoc);\n if (targetRep?.checksum && targetRep?.mediaType) {\n const targetContent = await repStore.retrieve(targetRep.checksum, targetRep.mediaType);\n const contentStr = decodeRepresentation(targetContent, targetRep.mediaType);\n\n // Create inference client for this request (HTTP handler context)\n const client = await getInferenceClient(config, logger);\n\n targetContext = {\n content: contentStr.slice(0, contextWindow * 2),\n summary: await generateResourceSummary(targetDoc.name, contentStr, getResourceEntityTypes(targetDoc), client),\n };\n }\n }\n\n // TODO: Generate suggested resolution using AI\n const suggestedResolution = undefined;\n\n // Build YieldContext structure\n const generationContext: YieldContext | undefined = sourceContext ? {\n sourceContext: {\n before: sourceContext.before || '',\n selected: sourceContext.selected,\n after: sourceContext.after || '',\n },\n metadata: {\n resourceType: 'document',\n language: sourceDoc.language as string | undefined,\n entityTypes: getEntityTypes(annotation),\n },\n } : undefined;\n\n const response: AnnotationLLMContextResponse = {\n annotation,\n sourceResource: sourceDoc,\n targetResource: targetDoc,\n ...(generationContext ? { context: generationContext } : {}),\n ...(sourceContext ? { sourceContext } : {}), // Keep for backward compatibility\n ...(targetContext ? { targetContext } : {}),\n ...(suggestedResolution ? { suggestedResolution } : {}),\n };\n\n return response;\n }\n\n /**\n * Get resource annotations from view storage (fast path)\n * Throws if view missing\n */\n static async getResourceAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceAnnotations> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n const view = await viewStorage.get(resourceId);\n\n if (!view) {\n throw new Error(`Resource ${resourceId} not found in view storage`);\n }\n\n return view.annotations;\n }\n\n /**\n * Get all annotations\n * @returns Array of all annotation objects\n */\n static async getAllAnnotations(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n\n // Enrich resolved references with document names\n // NOTE: Future optimization - make this optional via query param if performance becomes an issue\n return await this.enrichResolvedReferences(annotations.annotations, config);\n }\n\n /**\n * Enrich reference annotations with resolved document names\n * Adds _resolvedDocumentName property to annotations that link to documents\n * @private\n */\n private static async enrichResolvedReferences(annotations: Annotation[], config: EnvironmentConfig): Promise<Annotation[]> {\n if (!config.services?.filesystem?.path) {\n return annotations;\n }\n\n // Extract unique resolved document URIs from reference annotations\n const resolvedUris = new Set<string>();\n for (const ann of annotations) {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.type === 'SpecificResource' && item.purpose === 'linking' && item.source) {\n resolvedUris.add(item.source);\n }\n }\n }\n }\n\n if (resolvedUris.size === 0) {\n return annotations;\n }\n\n // Batch fetch all resolved documents in parallel\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const metadataPromises = Array.from(resolvedUris).map(async (uri) => {\n const docId = uri.split('/resources/')[1];\n if (!docId) return null;\n\n try {\n const view = await viewStorage.get(docId as ResourceId);\n if (view?.resource?.name) {\n return {\n uri,\n metadata: {\n name: view.resource.name,\n mediaType: view.resource.mediaType as string | undefined\n }\n };\n }\n } catch (e) {\n // Document might not exist, skip\n }\n return null;\n });\n\n const results = await Promise.all(metadataPromises);\n const uriToMetadata = new Map<string, { name: string; mediaType?: string }>();\n for (const result of results) {\n if (result) {\n uriToMetadata.set(result.uri, result.metadata);\n }\n }\n\n // Add _resolvedDocumentName and _resolvedDocumentMediaType to annotations\n return annotations.map(ann => {\n if (ann.motivation === 'linking' && ann.body) {\n const body = Array.isArray(ann.body) ? ann.body : [ann.body];\n for (const item of body) {\n if (item.type === 'SpecificResource' && item.purpose === 'linking' && item.source) {\n const metadata = uriToMetadata.get(item.source);\n if (metadata) {\n return {\n ...ann,\n _resolvedDocumentName: metadata.name,\n _resolvedDocumentMediaType: metadata.mediaType\n } as Annotation;\n }\n }\n }\n }\n return ann;\n });\n }\n\n /**\n * Get resource stats (version info)\n * @returns Version and timestamp info for the annotations\n */\n static async getResourceStats(resourceId: ResourceId, config: EnvironmentConfig): Promise<{\n resourceId: ResourceId;\n version: number;\n updatedAt: string;\n }> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n return {\n resourceId: annotations.resourceId,\n version: annotations.version,\n updatedAt: annotations.updatedAt,\n };\n }\n\n /**\n * Check if resource exists in view storage\n */\n static async resourceExists(resourceId: ResourceId, config: EnvironmentConfig): Promise<boolean> {\n if (!config.services?.filesystem?.path) {\n throw new Error('Filesystem path not found in configuration');\n }\n const basePath = config.services.filesystem.path;\n const projectRoot = config._metadata?.projectRoot;\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n return await viewStorage.exists(resourceId);\n }\n\n /**\n * Get a single annotation by ID\n * O(1) lookup using resource ID to access view storage\n */\n static async getAnnotation(annotationId: AnnotationId, resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation | null> {\n const annotations = await this.getResourceAnnotations(resourceId, config);\n // Extract short ID from annotation's full URI for comparison\n return annotations.annotations.find((a: Annotation) => {\n const shortId = a.id.split('/').pop();\n return shortId === annotationId;\n }) || null;\n }\n\n /**\n * List annotations with optional filtering\n * @param filters - Optional filters like resourceId and type\n * @throws Error if resourceId not provided (cross-resource queries not supported in view storage)\n */\n static async listAnnotations(filters: { resourceId?: ResourceId; type?: AnnotationCategory } | undefined, config: EnvironmentConfig): Promise<Annotation[]> {\n if (!filters?.resourceId) {\n throw new Error('resourceId is required for annotation listing - cross-resource queries not supported in view storage');\n }\n\n // Use view storage directly\n return await this.getAllAnnotations(filters.resourceId, config);\n }\n\n /**\n * Get annotation context (selected text with surrounding context)\n */\n static async getAnnotationContext(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n contextBefore: number,\n contextAfter: number,\n config: EnvironmentConfig\n ): Promise<AnnotationContextResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource metadata from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract context based on annotation position\n const context = this.extractAnnotationContext(annotation, contentStr, contextBefore, contextAfter);\n\n return {\n annotation: annotation,\n context,\n resource: {\n '@context': resource['@context'],\n '@id': resource['@id'],\n name: resource.name,\n entityTypes: resource.entityTypes,\n representations: resource.representations,\n archived: resource.archived,\n creationMethod: resource.creationMethod,\n wasAttributedTo: resource.wasAttributedTo,\n dateCreated: resource.dateCreated,\n },\n };\n }\n\n /**\n * Generate AI summary of annotation in context\n */\n static async generateAnnotationSummary(\n annotationId: AnnotationId,\n resourceId: ResourceId,\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<ContextualSummaryResponse> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n // Get annotation from view storage\n const annotation = await this.getAnnotation(annotationId, resourceId, config);\n if (!annotation) {\n throw new Error('Annotation not found');\n }\n\n // Get resource from view storage\n const resource = await ResourceContext.getResourceMetadata(\n uriToResourceId(getTargetSource(annotation.target)),\n config\n );\n if (!resource) {\n throw new Error('Resource not found');\n }\n\n // Get content from representation store\n const contentStr = await this.getResourceContent(resource, repStore);\n\n // Extract annotation text with context (fixed 500 chars for summary)\n const contextSize = 500;\n const context = this.extractAnnotationContext(annotation, contentStr, contextSize, contextSize);\n\n // Extract entity types from annotation body\n const annotationEntityTypes = getEntityTypes(annotation);\n\n // Generate summary using LLM\n const summary = await this.generateSummary(resource, context, annotationEntityTypes, config, logger);\n\n return {\n summary,\n relevantFields: {\n resourceId: resource.id,\n resourceName: resource.name,\n entityTypes: annotationEntityTypes,\n },\n context: {\n before: context.before.substring(Math.max(0, context.before.length - 200)), // Last 200 chars\n selected: context.selected,\n after: context.after.substring(0, 200), // First 200 chars\n },\n };\n }\n\n /**\n * Get resource content as string\n */\n private static async getResourceContent(\n resource: ResourceDescriptor,\n repStore: FilesystemRepresentationStore\n ): Promise<string> {\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep?.checksum || !primaryRep?.mediaType) {\n throw new Error('Resource content not found');\n }\n const content = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(content, primaryRep.mediaType);\n }\n\n /**\n * Extract annotation context from resource content\n */\n private static extractAnnotationContext(\n annotation: Annotation,\n contentStr: string,\n contextBefore: number,\n contextAfter: number\n ): AnnotationTextContext {\n const targetSelector = getTargetSelector(annotation.target);\n const posSelector = targetSelector ? getTextPositionSelector(targetSelector) : null;\n if (!posSelector) {\n throw new Error('TextPositionSelector required for context');\n }\n\n const selStart = posSelector.start;\n const selEnd = posSelector.end;\n const start = Math.max(0, selStart - contextBefore);\n const end = Math.min(contentStr.length, selEnd + contextAfter);\n\n return {\n before: contentStr.substring(start, selStart),\n selected: contentStr.substring(selStart, selEnd),\n after: contentStr.substring(selEnd, end),\n };\n }\n\n /**\n * Generate LLM summary of annotation in context\n * Creates inference client per-request (HTTP handler context)\n */\n private static async generateSummary(\n resource: ResourceDescriptor,\n context: AnnotationTextContext,\n entityTypes: string[],\n config: EnvironmentConfig,\n logger?: Logger\n ): Promise<string> {\n const summaryPrompt = `Summarize this text in context:\n\nContext before: \"${context.before.substring(Math.max(0, context.before.length - 200))}\"\nSelected exact: \"${context.selected}\"\nContext after: \"${context.after.substring(0, 200)}\"\n\nResource: ${resource.name}\nEntity types: ${entityTypes.join(', ')}`;\n\n // Create client for this HTTP request\n const client = await getInferenceClient(config, logger);\n return await client.generateText(summaryPrompt, 500, 0.5);\n }\n}\n","/**\n * Resource Context\n *\n * Assembles resource context from view storage and content store\n * Does NOT touch the graph - graph queries go through GraphContext\n */\n\nimport { FilesystemViewStorage } from '@semiont/event-sourcing';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { components } from '@semiont/core';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface ListResourcesFilters {\n search?: string;\n archived?: boolean;\n}\n\nexport class ResourceContext {\n /**\n * Get resource metadata from view storage\n */\n static async getResourceMetadata(resourceId: ResourceId, config: EnvironmentConfig): Promise<ResourceDescriptor | null> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const view = await viewStorage.get(resourceId);\n if (!view) {\n return null;\n }\n\n return view.resource;\n }\n\n /**\n * List all resources by scanning view storage\n */\n static async listResources(filters: ListResourcesFilters | undefined, config: EnvironmentConfig): Promise<ResourceDescriptor[]> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n\n const viewStorage = new FilesystemViewStorage(basePath, projectRoot);\n\n const allViews = await viewStorage.getAll();\n const resources: ResourceDescriptor[] = [];\n\n for (const view of allViews) {\n const doc = view.resource;\n\n // Apply filters\n if (filters?.archived !== undefined && doc.archived !== filters.archived) {\n continue;\n }\n\n if (filters?.search) {\n const searchLower = filters.search.toLowerCase();\n if (!doc.name.toLowerCase().includes(searchLower)) {\n continue;\n }\n }\n\n resources.push(doc);\n }\n\n // Sort by creation date (newest first)\n resources.sort((a, b) => {\n const aTime = a.dateCreated ? new Date(a.dateCreated).getTime() : 0;\n const bTime = b.dateCreated ? new Date(b.dateCreated).getTime() : 0;\n return bTime - aTime;\n });\n\n return resources;\n }\n\n /**\n * Add content previews to resources (for search results)\n * Retrieves and decodes the first 200 characters of each resource's primary representation\n */\n static async addContentPreviews(\n resources: ResourceDescriptor[],\n config: EnvironmentConfig\n ): Promise<Array<ResourceDescriptor & { content: string }>> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n return await Promise.all(\n resources.map(async (doc) => {\n try {\n const primaryRep = getPrimaryRepresentation(doc);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n const contentPreview = decodeRepresentation(contentBuffer, primaryRep.mediaType).slice(0, 200);\n return { ...doc, content: contentPreview };\n }\n return { ...doc, content: '' };\n } catch {\n return { ...doc, content: '' };\n }\n })\n );\n }\n\n /**\n * Get full content for a resource\n * Retrieves and decodes the primary representation\n */\n static async getResourceContent(\n resource: ResourceDescriptor,\n config: EnvironmentConfig\n ): Promise<string | undefined> {\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (primaryRep?.checksum && primaryRep?.mediaType) {\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n return undefined;\n }\n}\n","/**\n * Graph Context\n *\n * Provides graph database operations for resources and annotations.\n * All methods require graph traversal - must use graph database.\n */\n\nimport { getGraphDatabase } from '@semiont/graph';\nimport { resourceIdToURI } from '@semiont/core';\nimport type {\n ResourceId,\n EnvironmentConfig,\n GraphConnection,\n GraphPath,\n} from '@semiont/core';\nimport type { components } from '@semiont/core';\nimport { getResourceId, getResourceEntityTypes } from '@semiont/api-client';\n\ntype Annotation = components['schemas']['Annotation'];\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\n\nexport interface GraphNode {\n id: string;\n type: string;\n label: string;\n metadata: { entityTypes: string[] };\n}\n\nexport interface GraphEdge {\n source: string;\n target: string;\n type: string;\n metadata: Record<string, unknown>;\n}\n\nexport interface GraphRepresentation {\n nodes: GraphNode[];\n edges: GraphEdge[];\n}\n\nexport class GraphContext {\n /**\n * Get all resources referencing this resource (backlinks)\n * Requires graph traversal - must use graph database\n */\n static async getBacklinks(resourceId: ResourceId, config: EnvironmentConfig): Promise<Annotation[]> {\n const graphDb = await getGraphDatabase(config);\n const resourceUri = resourceIdToURI(resourceId, config.services.backend!.publicURL);\n return await graphDb.getResourceReferencedBy(resourceUri);\n }\n\n /**\n * Find shortest path between two resources\n * Requires graph traversal - must use graph database\n */\n static async findPath(\n fromResourceId: ResourceId,\n toResourceId: ResourceId,\n config: EnvironmentConfig,\n maxDepth?: number\n ): Promise<GraphPath[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.findPath(fromResourceId, toResourceId, maxDepth);\n }\n\n /**\n * Get resource connections (graph edges)\n * Requires graph traversal - must use graph database\n */\n static async getResourceConnections(resourceId: ResourceId, config: EnvironmentConfig): Promise<GraphConnection[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.getResourceConnections(resourceId);\n }\n\n /**\n * Search resources by name (cross-resource query)\n * Requires full-text search - must use graph database\n */\n static async searchResources(query: string, config: EnvironmentConfig, limit?: number): Promise<ResourceDescriptor[]> {\n const graphDb = await getGraphDatabase(config);\n return await graphDb.searchResources(query, limit);\n }\n\n /**\n * Build graph representation with nodes and edges for a resource and its connections\n * Retrieves connections from graph and builds visualization-ready structure\n */\n static async buildGraphRepresentation(\n resourceId: ResourceId,\n maxRelated: number,\n config: EnvironmentConfig\n ): Promise<GraphRepresentation> {\n const graphDb = await getGraphDatabase(config);\n const publicURL = config.services.backend!.publicURL;\n const resourceUri = resourceIdToURI(resourceId, publicURL);\n\n // Get main resource\n const mainDoc = await graphDb.getResource(resourceUri);\n if (!mainDoc) {\n throw new Error('Resource not found');\n }\n\n // Get connections\n const connections = await graphDb.getResourceConnections(resourceId);\n const relatedDocs = connections.map(conn => conn.targetResource).slice(0, maxRelated - 1);\n\n // Build nodes\n const nodes = [\n {\n id: getResourceId(mainDoc),\n type: 'resource',\n label: mainDoc.name,\n metadata: { entityTypes: getResourceEntityTypes(mainDoc) },\n },\n ...relatedDocs.map(doc => ({\n id: getResourceId(doc),\n type: 'resource',\n label: doc.name,\n metadata: { entityTypes: getResourceEntityTypes(doc) },\n })),\n ].filter(node => node.id !== undefined) as GraphNode[];\n\n // Build edges\n const edges = connections\n .slice(0, maxRelated - 1)\n .map(conn => ({\n source: resourceId,\n target: getResourceId(conn.targetResource),\n type: conn.relationshipType || 'link',\n metadata: {},\n }))\n .filter(edge => edge.target !== undefined) as GraphEdge[];\n\n return { nodes, edges };\n }\n}\n","/**\n * LLM Context\n *\n * Builds comprehensive context for LLM processing of resources\n * Orchestrates: ResourceContext, GraphContext, AnnotationContext, and generation functions\n */\n\nimport { ResourceContext } from './resource-context';\nimport { GraphContext } from './graph-context';\nimport { AnnotationContext } from './annotation-context';\nimport { generateResourceSummary, generateReferenceSuggestions } from './generation/resource-generation';\nimport type { InferenceClient } from '@semiont/inference';\nimport { getResourceEntityTypes, getResourceId } from '@semiont/api-client';\nimport { resourceId as makeResourceId, type EnvironmentConfig, type ResourceId } from '@semiont/core';\nimport type { components } from '@semiont/core';\n\ntype ResourceDescriptor = components['schemas']['ResourceDescriptor'];\ntype ResourceLLMContextResponse = components['schemas']['ResourceLLMContextResponse'];\n\nexport interface LLMContextOptions {\n depth: number;\n maxResources: number;\n includeContent: boolean;\n includeSummary: boolean;\n}\n\nexport class LLMContext {\n /**\n * Get comprehensive LLM context for a resource\n * Includes: main resource, related resources, annotations, graph, content, summary, references\n */\n static async getResourceContext(\n resourceId: ResourceId,\n options: LLMContextOptions,\n config: EnvironmentConfig,\n inferenceClient: InferenceClient\n ): Promise<ResourceLLMContextResponse> {\n // Get main resource from view storage\n const mainDoc = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!mainDoc) {\n throw new Error('Resource not found');\n }\n\n // Get content for main resource\n const mainContent = options.includeContent\n ? await ResourceContext.getResourceContent(mainDoc, config)\n : undefined;\n\n // Get graph representation (includes related resources and connections)\n const graph = await GraphContext.buildGraphRepresentation(\n resourceId,\n options.maxResources,\n config\n );\n\n // Extract related resources from graph nodes (excluding main resource)\n const relatedDocs: ResourceDescriptor[] = [];\n const resourceIdStr = resourceId.toString();\n for (const node of graph.nodes) {\n if (node.id !== resourceIdStr) {\n const relatedDoc = await ResourceContext.getResourceMetadata(makeResourceId(node.id), config);\n if (relatedDoc) {\n relatedDocs.push(relatedDoc);\n }\n }\n }\n\n // Get content for related resources\n const relatedResourcesContent: Record<string, string> = {};\n if (options.includeContent) {\n await Promise.all(\n relatedDocs.map(async (doc) => {\n const docId = getResourceId(doc);\n if (!docId) return;\n const content = await ResourceContext.getResourceContent(doc, config);\n if (content) {\n relatedResourcesContent[docId] = content;\n }\n })\n );\n }\n\n // Get annotations from view storage\n const annotations = await AnnotationContext.getAllAnnotations(resourceId, config);\n\n // Generate summary if requested\n const summary = options.includeSummary && mainContent\n ? await generateResourceSummary(\n mainDoc.name,\n mainContent,\n getResourceEntityTypes(mainDoc),\n inferenceClient\n )\n : undefined;\n\n // Generate reference suggestions if we have content\n const suggestedReferences = mainContent\n ? await generateReferenceSuggestions(mainContent, inferenceClient)\n : undefined;\n\n // Build response\n return {\n mainResource: mainDoc,\n relatedResources: relatedDocs,\n annotations,\n graph,\n ...(mainContent ? { mainResourceContent: mainContent } : {}),\n ...(options.includeContent ? { relatedResourcesContent } : {}),\n ...(summary ? { summary } : {}),\n ...(suggestedReferences ? { suggestedReferences } : {}),\n };\n }\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Fetch resource metadata and content\n * 2. Build AI prompts using MotivationPrompts\n * 3. Call AI inference\n * 4. Parse and validate results using MotivationParsers\n *\n * This is the high-level API for AI-powered annotation detection.\n * Workers and other consumers should use these methods instead of\n * implementing detection logic directly.\n */\n\nimport { ResourceContext } from './resource-context';\nimport { FilesystemRepresentationStore } from '@semiont/content';\nimport { getPrimaryRepresentation, decodeRepresentation } from '@semiont/api-client';\nimport type { InferenceClient } from '@semiont/inference';\nimport { MotivationPrompts } from './detection/motivation-prompts';\nimport {\n MotivationParsers,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from './detection/motivation-parsers';\nimport { getTagSchema, getSchemaCategory } from '@semiont/ontology';\nimport type { EnvironmentConfig, ResourceId } from '@semiont/core';\n\nexport class AnnotationDetection {\n /**\n * Detect comments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for comment generation\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Array of validated comment matches\n */\n static async detectComments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<CommentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildCommentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 3000, // maxTokens: Higher than highlights/assessments due to comment text\n 0.4 // temperature: Slightly higher to allow creative context\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseComments(response, content);\n }\n\n /**\n * Detect highlights in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for highlight selection\n * @param density - Optional target number of highlights per 2000 words\n * @returns Array of validated highlight matches\n */\n static async detectHighlights(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n density?: number\n ): Promise<HighlightMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildHighlightPrompt(content, instructions, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 2000, // maxTokens: Lower than comments/assessments (no body text)\n 0.3 // temperature: Low for consistent importance judgments\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseHighlights(response, content);\n }\n\n /**\n * Detect assessments in a resource\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param instructions - Optional user instructions for assessment generation\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Array of validated assessment matches\n */\n static async detectAssessments(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number\n ): Promise<AssessmentMatch[]> {\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt\n const prompt = MotivationPrompts.buildAssessmentPrompt(content, instructions, tone, density);\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 3000, // maxTokens: Higher for assessment text\n 0.3 // temperature: Lower for analytical consistency\n );\n\n // 5. Parse and validate response\n return MotivationParsers.parseAssessments(response, content);\n }\n\n /**\n * Detect tags in a resource for a specific category\n *\n * @param resourceId - The resource to analyze\n * @param config - Environment configuration\n * @param client - Inference client for AI operations\n * @param schemaId - The tag schema identifier (e.g., \"irac\", \"imrad\")\n * @param category - The specific category to detect\n * @returns Array of validated tag matches\n */\n static async detectTags(\n resourceId: ResourceId,\n config: EnvironmentConfig,\n client: InferenceClient,\n schemaId: string,\n category: string\n ): Promise<TagMatch[]> {\n // Validate schema and category\n const schema = getTagSchema(schemaId);\n if (!schema) {\n throw new Error(`Invalid tag schema: ${schemaId}`);\n }\n\n const categoryInfo = getSchemaCategory(schemaId, category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schemaId}`);\n }\n\n // 1. Fetch resource metadata\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) {\n throw new Error(`Resource ${resourceId} not found`);\n }\n\n // 2. Load content from representation store (FULL content for structural analysis)\n const content = await this.loadResourceContent(resourceId, config);\n if (!content) {\n throw new Error(`Could not load content for resource ${resourceId}`);\n }\n\n // 3. Build prompt with schema and category information\n const prompt = MotivationPrompts.buildTagPrompt(\n content,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples\n );\n\n // 4. Call AI inference\n const response = await client.generateText(\n prompt,\n 4000, // maxTokens: Higher for full document analysis\n 0.2 // temperature: Lower for structural consistency\n );\n\n // 5. Parse response (without validation)\n const parsedTags = MotivationParsers.parseTags(response);\n\n // 6. Validate offsets and add category\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n\n /**\n * Load resource content from representation store\n * Helper method used by all detection methods\n *\n * @param resourceId - The resource ID to load\n * @param config - Environment configuration\n * @returns Resource content as string, or null if not available\n */\n private static async loadResourceContent(\n resourceId: ResourceId,\n config: EnvironmentConfig\n ): Promise<string | null> {\n const resource = await ResourceContext.getResourceMetadata(resourceId, config);\n if (!resource) return null;\n\n const primaryRep = getPrimaryRepresentation(resource);\n if (!primaryRep) return null;\n\n // Only process text content\n const baseMediaType = primaryRep.mediaType?.split(';')[0]?.trim() || '';\n if (baseMediaType !== 'text/plain' && baseMediaType !== 'text/markdown') {\n return null;\n }\n\n if (!primaryRep.checksum || !primaryRep.mediaType) return null;\n\n const basePath = config.services.filesystem!.path;\n const projectRoot = config._metadata?.projectRoot;\n const repStore = new FilesystemRepresentationStore({ basePath }, projectRoot);\n const contentBuffer = await repStore.retrieve(primaryRep.checksum, primaryRep.mediaType);\n return decodeRepresentation(contentBuffer, primaryRep.mediaType);\n }\n}\n","/**\n * Prompt builders for annotation detection motivations\n *\n * Provides static methods to build AI prompts for each Web Annotation motivation type.\n * Extracted from worker implementations to centralize prompt logic.\n */\n\nexport class MotivationPrompts {\n /**\n * Build a prompt for detecting comment-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param tone - Optional tone guidance (e.g., \"academic\", \"conversational\")\n * @param density - Optional target number of comments per 2000 words\n * @returns Formatted prompt string\n */\n static buildCommentPrompt(\n content: string,\n instructions?: string,\n tone?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const toneGuidance = tone ? ` Use a ${tone} tone.` : '';\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} comments per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Add comments to passages in this text following these instructions:\n\n${instructions}${toneGuidance}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of comments. Each comment must have:\n- \"exact\": the exact text passage being commented on (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"comment\": your comment following the instructions above\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"the quarterly review meeting\", \"start\": 142, \"end\": 169, \"prefix\": \"We need to schedule \", \"suffix\": \" for next month.\", \"comment\": \"Who will lead this? Should we invite the external auditors?\"}\n]`;\n } else {\n // No specific instructions - fall back to explanatory/educational mode\n const toneGuidance = tone\n ? `\\n\\nTone: Use a ${tone} style in your comments.`\n : '';\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} comments per 2000 words`\n : `\\n- Aim for 3-8 comments per 2000 words (not too sparse or dense)`;\n\n prompt = `Identify passages in this text that would benefit from explanatory comments.\nFor each passage, provide contextual information, clarification, or background.${toneGuidance}\n\nGuidelines:\n- Select passages that reference technical terms, historical figures, complex concepts, or unclear references\n- Provide comments that ADD VALUE beyond restating the text\n- Focus on explanation, background, or connections to other ideas\n- Avoid obvious or trivial comments\n- Keep comments concise (1-3 sentences typically)${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of comments. Each comment should have:\n- \"exact\": the exact text passage being commented on (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"comment\": your explanatory comment (1-3 sentences, provide context/background/clarification)\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"Ouranos\", \"start\": 52, \"end\": 59, \"prefix\": \"In the beginning, \", \"suffix\": \" ruled the universe\", \"comment\": \"Ouranos (also spelled Uranus) is the primordial Greek deity personifying the sky. In Hesiod's Theogony, he is the son and husband of Gaia (Earth) and father of the Titans.\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting highlight-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param density - Optional target number of highlights per 2000 words\n * @returns Formatted prompt string\n */\n static buildHighlightPrompt(\n content: string,\n instructions?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} highlights per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Identify passages in this text to highlight following these instructions:\n\n${instructions}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of highlights. Each highlight must have:\n- \"exact\": the exact text passage to highlight (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"revenue grew 45% year-over-year\", \"start\": 142, \"end\": 174, \"prefix\": \"In Q3 2024, \", \"suffix\": \", exceeding all forecasts.\"}\n]`;\n } else {\n // No specific instructions - fall back to importance/salience mode\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} highlights per 2000 words`\n : `\\n- Aim for 3-8 highlights per 2000 words (be selective)`;\n\n prompt = `Identify passages in this text that merit highlighting for their importance or salience.\nFocus on content that readers should notice and remember.\n\nGuidelines:\n- Highlight key claims, findings, or conclusions\n- Highlight important definitions, terminology, or concepts\n- Highlight notable quotes or particularly striking statements\n- Highlight critical decisions, action items, or turning points\n- Select passages that are SIGNIFICANT, not just interesting\n- Avoid trivial or obvious content${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of highlights. Each highlight should have:\n- \"exact\": the exact text passage to highlight (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"we will discontinue support for legacy systems by March 2025\", \"start\": 52, \"end\": 113, \"prefix\": \"After careful consideration, \", \"suffix\": \". This decision affects\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting assessment-worthy passages\n *\n * @param content - The text content to analyze (will be truncated to 8000 chars)\n * @param instructions - Optional user-provided instructions\n * @param tone - Optional tone guidance (e.g., \"critical\", \"supportive\")\n * @param density - Optional target number of assessments per 2000 words\n * @returns Formatted prompt string\n */\n static buildAssessmentPrompt(\n content: string,\n instructions?: string,\n tone?: string,\n density?: number\n ): string {\n let prompt: string;\n\n if (instructions) {\n // User provided specific instructions - minimal prompt, let instructions drive behavior\n const toneGuidance = tone ? ` Use a ${tone} tone.` : '';\n const densityGuidance = density\n ? `\\n\\nAim for approximately ${density} assessments per 2000 words of text.`\n : ''; // Let user instructions determine density\n\n prompt = `Assess passages in this text following these instructions:\n\n${instructions}${toneGuidance}${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of assessments. Each assessment must have:\n- \"exact\": the exact text passage being assessed (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"assessment\": your assessment following the instructions above\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample:\n[\n {\"exact\": \"the quarterly revenue target\", \"start\": 142, \"end\": 169, \"prefix\": \"We established \", \"suffix\": \" for Q4 2024.\", \"assessment\": \"This target seems ambitious given market conditions. Consider revising based on recent trends.\"}\n]`;\n } else {\n // No specific instructions - fall back to analytical/evaluation mode\n const toneGuidance = tone\n ? `\\n\\nTone: Use a ${tone} style in your assessments.`\n : '';\n const densityGuidance = density\n ? `\\n- Aim for approximately ${density} assessments per 2000 words`\n : `\\n- Aim for 2-6 assessments per 2000 words (focus on key passages)`;\n\n prompt = `Identify passages in this text that merit critical assessment or evaluation.\nFor each passage, provide analysis of its validity, strength, or implications.${toneGuidance}\n\nGuidelines:\n- Select passages containing claims, arguments, conclusions, or assertions\n- Assess evidence quality, logical soundness, or practical implications\n- Provide assessments that ADD INSIGHT beyond restating the text\n- Focus on passages where evaluation would help readers form judgments\n- Keep assessments concise yet substantive (1-3 sentences typically)${densityGuidance}\n\nText to analyze:\n---\n${content.substring(0, 8000)}\n---\n\nReturn a JSON array of assessments. Each assessment should have:\n- \"exact\": the exact text passage being assessed (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n- \"assessment\": your analytical assessment (1-3 sentences, evaluate validity/strength/implications)\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"AI will replace most jobs by 2030\", \"start\": 52, \"end\": 89, \"prefix\": \"Many experts predict that \", \"suffix\": \", fundamentally reshaping\", \"assessment\": \"This claim lacks nuance and supporting evidence. Employment patterns historically show job transformation rather than wholesale replacement. The timeline appears speculative without specific sector analysis.\"}\n]`;\n }\n\n return prompt;\n }\n\n /**\n * Build a prompt for detecting structural tags\n *\n * @param content - The full text content to analyze (NOT truncated for structural analysis)\n * @param category - The specific category to detect\n * @param schemaName - Human-readable schema name\n * @param schemaDescription - Schema description\n * @param schemaDomain - Schema domain\n * @param categoryDescription - Category description\n * @param categoryExamples - Example questions/guidance for this category\n * @returns Formatted prompt string\n */\n static buildTagPrompt(\n content: string,\n category: string,\n schemaName: string,\n schemaDescription: string,\n schemaDomain: string,\n categoryDescription: string,\n categoryExamples: string[]\n ): string {\n // Build prompt with schema context and category-specific guidance\n const prompt = `You are analyzing a text using the ${schemaName} framework.\n\nSchema: ${schemaDescription}\nDomain: ${schemaDomain}\n\nYour task: Identify passages that serve the structural role of \"${category}\".\n\nCategory: ${category}\nDescription: ${categoryDescription}\nKey questions:\n${categoryExamples.map(ex => `- ${ex}`).join('\\n')}\n\nGuidelines:\n- Focus on STRUCTURAL FUNCTION, not semantic content\n- A passage serves the \"${category}\" role if it performs this function in the document's structure\n- Look for passages that explicitly fulfill this role\n- Passages can be sentences, paragraphs, or sections\n- Aim for precision - only tag passages that clearly serve this structural role\n- Typical documents have 1-5 instances of each category (some may have 0)\n\nText to analyze:\n---\n${content}\n---\n\nReturn a JSON array of tags. Each tag should have:\n- \"exact\": the exact text passage (quoted verbatim from source)\n- \"start\": character offset where the passage starts\n- \"end\": character offset where the passage ends\n- \"prefix\": up to 32 characters of text immediately before the passage\n- \"suffix\": up to 32 characters of text immediately after the passage\n\nReturn ONLY a valid JSON array, no additional text or explanation.\n\nExample format:\n[\n {\"exact\": \"What duty did the defendant owe?\", \"start\": 142, \"end\": 175, \"prefix\": \"The central question is: \", \"suffix\": \" This question must be\"},\n {\"exact\": \"In tort law, a duty of care is established when...\", \"start\": 412, \"end\": 520, \"prefix\": \"Legal framework:\\\\n\", \"suffix\": \"\\\\n\\\\nApplying this standard\"}\n]`;\n\n return prompt;\n }\n}\n","/**\n * Response parsers for annotation detection motivations\n *\n * Provides static methods to parse and validate AI responses for each motivation type.\n * Includes offset validation and correction logic.\n * Extracted from worker implementations to centralize parsing logic.\n *\n * NOTE: These are static utility methods without logger access.\n * Console statements kept for debugging - consider adding logger parameter in future.\n */\n\nimport { validateAndCorrectOffsets } from '@semiont/api-client';\n\n/**\n * Represents a detected comment with validated position\n */\nexport interface CommentMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n comment: string;\n}\n\n/**\n * Represents a detected highlight with validated position\n */\nexport interface HighlightMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * Represents a detected assessment with validated position\n */\nexport interface AssessmentMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n assessment: string;\n}\n\n/**\n * Represents a detected tag with validated position\n */\nexport interface TagMatch {\n exact: string;\n start: number;\n end: number;\n prefix?: string;\n suffix?: string;\n category: string;\n}\n\nexport class MotivationParsers {\n /**\n * Parse and validate AI response for comment detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated comment matches\n */\n static parseComments(response: string, content: string): CommentMatch[] {\n try {\n // Clean up markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const parsed = JSON.parse(cleaned);\n\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Comment response is not an array');\n return [];\n }\n\n // Validate and filter\n const valid = parsed.filter((c: any) =>\n c &&\n typeof c.exact === 'string' &&\n typeof c.start === 'number' &&\n typeof c.end === 'number' &&\n typeof c.comment === 'string' &&\n c.comment.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid comments from ${parsed.length} total`);\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedComments: CommentMatch[] = [];\n\n for (const comment of valid) {\n try {\n const validated = validateAndCorrectOffsets(content, comment.start, comment.end, comment.exact);\n validatedComments.push({\n ...comment,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid comment \"${comment.exact}\":`, error);\n // Skip this comment - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedComments;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI comment response:', error);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for highlight detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated highlight matches\n */\n static parseHighlights(response: string, content: string): HighlightMatch[] {\n try {\n // Clean up response - remove markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```json') || cleaned.startsWith('```')) {\n cleaned = cleaned.slice(cleaned.indexOf('\\n') + 1);\n const endIndex = cleaned.lastIndexOf('```');\n if (endIndex !== -1) {\n cleaned = cleaned.slice(0, endIndex);\n }\n }\n\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Highlight response was not an array');\n return [];\n }\n\n // Validate and filter results\n const highlights = parsed.filter((h: any) =>\n h && typeof h.exact === 'string' &&\n typeof h.start === 'number' &&\n typeof h.end === 'number'\n );\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedHighlights: HighlightMatch[] = [];\n\n for (const highlight of highlights) {\n try {\n const validated = validateAndCorrectOffsets(content, highlight.start, highlight.end, highlight.exact);\n validatedHighlights.push({\n ...highlight,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid highlight \"${highlight.exact}\":`, error);\n // Skip this highlight - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedHighlights;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI highlight response:', error);\n console.error('Raw response:', response);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for assessment detection\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @param content - Original content to validate offsets against\n * @returns Array of validated assessment matches\n */\n static parseAssessments(response: string, content: string): AssessmentMatch[] {\n try {\n // Clean up response - remove markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```json') || cleaned.startsWith('```')) {\n cleaned = cleaned.slice(cleaned.indexOf('\\n') + 1);\n const endIndex = cleaned.lastIndexOf('```');\n if (endIndex !== -1) {\n cleaned = cleaned.slice(0, endIndex);\n }\n }\n\n const parsed = JSON.parse(cleaned);\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Assessment response was not an array');\n return [];\n }\n\n // Validate and filter results\n const assessments = parsed.filter((a: any) =>\n a && typeof a.exact === 'string' &&\n typeof a.start === 'number' &&\n typeof a.end === 'number' &&\n typeof a.assessment === 'string'\n );\n\n // Validate and correct AI's offsets, then extract proper context\n // AI sometimes returns offsets that don't match the actual text position\n const validatedAssessments: AssessmentMatch[] = [];\n\n for (const assessment of assessments) {\n try {\n const validated = validateAndCorrectOffsets(content, assessment.start, assessment.end, assessment.exact);\n validatedAssessments.push({\n ...assessment,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid assessment \"${assessment.exact}\":`, error);\n // Skip this assessment - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedAssessments;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI assessment response:', error);\n console.error('Raw response:', response);\n return [];\n }\n }\n\n /**\n * Parse and validate AI response for tag detection\n * Note: Does NOT validate offsets - caller must do that with content\n *\n * @param response - Raw AI response string (may include markdown code fences)\n * @returns Array of tag matches (offsets not yet validated)\n */\n static parseTags(response: string): Omit<TagMatch, 'category'>[] {\n try {\n // Clean up markdown code fences if present\n let cleaned = response.trim();\n if (cleaned.startsWith('```')) {\n cleaned = cleaned.replace(/^```(?:json)?\\n?/, '').replace(/\\n?```$/, '');\n }\n\n const parsed = JSON.parse(cleaned);\n\n if (!Array.isArray(parsed)) {\n console.warn('[MotivationParsers] Tag response is not an array');\n return [];\n }\n\n // Validate and filter\n const valid = parsed.filter((t: any) =>\n t &&\n typeof t.exact === 'string' &&\n typeof t.start === 'number' &&\n typeof t.end === 'number' &&\n t.exact.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid tags from ${parsed.length} total`);\n\n return valid;\n } catch (error) {\n console.error('[MotivationParsers] Failed to parse AI tag response:', error);\n return [];\n }\n }\n\n /**\n * Validate tag offsets against content and add category\n * Helper for tag detection after initial parsing\n *\n * @param tags - Parsed tags without validated offsets\n * @param content - Original content to validate against\n * @param category - Category to assign to validated tags\n * @returns Array of validated tag matches\n */\n static validateTagOffsets(\n tags: Omit<TagMatch, 'category'>[],\n content: string,\n category: string\n ): TagMatch[] {\n const validatedTags: TagMatch[] = [];\n\n for (const tag of tags) {\n try {\n const validated = validateAndCorrectOffsets(content, tag.start, tag.end, tag.exact);\n validatedTags.push({\n ...tag,\n category,\n start: validated.start,\n end: validated.end,\n prefix: validated.prefix,\n suffix: validated.suffix\n });\n } catch (error) {\n console.warn(`[MotivationParsers] Skipping invalid tag for category \"${category}\":`, error);\n // Skip this tag - AI hallucinated text that doesn't exist\n }\n }\n\n return validatedTags;\n }\n}\n","// @semiont/make-meaning - Making meaning from resources\n// Transforms raw resources into meaningful, interconnected knowledge\n\n// Service (primary export)\nexport { startMakeMeaning } from './service';\nexport type { MakeMeaningService } from './service';\n\n// Bootstrap\nexport { bootstrapEntityTypes, resetBootstrap } from './bootstrap/entity-types';\n\n// Views\nexport { readEntityTypesProjection } from './views/entity-types-reader';\n\n// Graph Consumer\nexport { GraphDBConsumer } from './graph/consumer';\n\n// Resource operations\nexport { ResourceOperations } from './resource-operations';\nexport type { UpdateResourceInput, CreateResourceInput } from './resource-operations';\n\n// Annotation operations\nexport { AnnotationOperations } from './annotation-operations';\nexport type { CreateAnnotationResult, UpdateAnnotationBodyResult } from './annotation-operations';\n\n// Context assembly exports\nexport { ResourceContext } from './resource-context';\nexport type { ListResourcesFilters } from './resource-context';\nexport { AnnotationContext } from './annotation-context';\nexport type { BuildContextOptions } from './annotation-context';\nexport { GraphContext } from './graph-context';\nexport type { GraphNode, GraphEdge, GraphRepresentation } from './graph-context';\nexport { LLMContext } from './llm-context';\nexport type { LLMContextOptions } from './llm-context';\n\n// Detection exports\nexport { AnnotationDetection } from './annotation-assistance';\nexport { MotivationPrompts } from './detection/motivation-prompts';\nexport { MotivationParsers } from './detection/motivation-parsers';\nexport type {\n CommentMatch,\n HighlightMatch,\n AssessmentMatch,\n TagMatch,\n} from './detection/motivation-parsers';\nexport { extractEntities } from './detection/entity-extractor';\nexport type { ExtractedEntity } from './detection/entity-extractor';\n\n// Generation exports\nexport {\n generateResourceFromTopic,\n generateResourceSummary,\n generateReferenceSuggestions,\n} from './generation/resource-generation';\n\n// Job workers (exported for direct instantiation if needed)\nexport { CommentAnnotationWorker } from './jobs/comment-annotation-worker';\nexport { HighlightAnnotationWorker } from './jobs/highlight-annotation-worker';\nexport { AssessmentAnnotationWorker } from './jobs/assessment-annotation-worker';\nexport { TagAnnotationWorker } from './jobs/tag-annotation-worker';\nexport { ReferenceAnnotationWorker } from './jobs/reference-annotation-worker';\nexport { GenerationWorker } from './jobs/generation-worker';\n\n// Reasoning exports (future)\n// export { ResourceReasoning } from './resource-reasoning';\n\n// ID generation\nexport { generateUuid } from './id-generation';\n\n// Placeholder for initial build\nexport const PACKAGE_NAME = '@semiont/make-meaning';\nexport const VERSION = '0.1.0';\n"],"mappings":";AAYA,YAAYA,WAAU;AACtB,SAAS,gBAAgB;AACzB,SAAS,oBAAoB,4BAA6C;AAC1E,SAAS,iCAAAC,sCAA+D;AAGxE,SAAS,0BAAgD;AACzD,SAAS,wBAA4C;;;ACVrD,SAAS,iBAAiB;AAG1B,SAAqB,4BAA4B;AACjD,SAAS,uBAAiC;AAE1C,SAAS,0BAA0B,sBAAsB,iCAAiC;;;ACU1F,eAAsB,gBACpB,OACA,aACA,QACA,+BAAwC,OACxC,QAC4B;AAG5B,QAAM,yBAAyB,YAAY,IAAI,QAAM;AACnD,QAAI,OAAO,OAAO,UAAU;AAC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AQ;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAUA,aAAqB,oBACnBA,aACAC,SACwB;AACxB,UAAM,WAAW,MAAM,gBAAgB,oBAAoBD,aAAYC,OAAM;AAC7E,QAAI,CAAC,SAAU,QAAO;AAEtB,UAAM,aAAaC,0BAAyB,QAAQ;AACpD,QAAI,CAAC,WAAY,QAAO;AAGxB,UAAM,gBAAgB,WAAW,WAAW,MAAM,GAAG,EAAE,CAAC,GAAG,KAAK,KAAK;AACrE,QAAI,kBAAkB,gBAAgB,kBAAkB,iBAAiB;AACvE,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,WAAW,YAAY,CAAC,WAAW,UAAW,QAAO;AAE1D,UAAM,WAAWD,QAAO,SAAS,WAAY;AAC7C,UAAM,cAAcA,QAAO,WAAW;AACtC,UAAM,WAAW,IAAIE,+BAA8B,EAAE,SAAS,GAAG,WAAW;AAC5E,UAAM,gBAAgB,MAAM,SAAS,SAAS,WAAW,UAAU,WAAW,SAAS;AACvF,WAAOC,sBAAqB,eAAe,WAAW,SAAS;AAAA,EACjE;AACF;;;AG/LO,IAAM,eAAe;AACrB,IAAM,UAAU;","names":["path","FilesystemRepresentationStore","config","JobWorker","FilesystemRepresentationStore","response","JobWorker","config","FilesystemRepresentationStore","FilesystemViewStorage","JobWorker","generateAnnotationId","resourceIdToURI","JobWorker","config","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","annotationId","resourceUri","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","resourceUri","annotationId","JobWorker","generateAnnotationId","resourceIdToURI","userId","JobWorker","config","resourceId","resourceUri","annotationId","d","b","UnsubscriptionErrorImpl","Subscription","empty","Subscriber","SafeSubscriber","Observable","observable","resolve","ObjectUnsubscribedErrorImpl","SubjectSubscription","SubjectSubscriber","Subject","observable","AnonymousSubject","GroupByOperator","GroupBySubscriber","GroupDurationSubscriber","GroupedObservable","InnerRefCountSubscription","MapOperator","MapSubscriber","iterator","observable","iterator","SimpleInnerSubscriber","SimpleOuterSubscriber","MergeMapOperator","MergeMapSubscriber","config","resourceUri","annotationUri","resourceId","userId","config","config","FilesystemRepresentationStore","fs","path","config","CREATION_METHODS","resourceId","userId","config","resourceId","CREATION_METHODS","generateAnnotationId","getTextPositionSelector","getTargetSource","annotationId","uriToResourceId","getInferenceClient","getTargetSelector","getPrimaryRepresentation","decodeRepresentation","FilesystemRepresentationStore","FilesystemViewStorage","getEntityTypes","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","resourceId","config","annotationUri","resourceId","config","FilesystemViewStorage","FilesystemRepresentationStore","targetResourceId","getPrimaryRepresentation","decodeRepresentation","getTargetSelector","getInferenceClient","getEntityTypes","annotationId","userId","config","generateAnnotationId","getTextPositionSelector","uriToResourceId","annotationId","getTargetSource","resourceId","getGraphDatabase","resourceIdToURI","getResourceEntityTypes","resourceId","config","resourceUri","getResourceEntityTypes","getResourceId","makeResourceId","resourceId","config","FilesystemRepresentationStore","getPrimaryRepresentation","decodeRepresentation","validateAndCorrectOffsets","getTagSchema","resourceId","config","getPrimaryRepresentation","FilesystemRepresentationStore","decodeRepresentation"]}