@semiont/jobs 0.6.7 → 0.6.9

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/job-queue-interface.ts","../src/will-retry.ts","../src/checkpoint-merge.ts","../src/fs-job-queue.ts","../src/jetstream-job-queue.ts","../src/types.ts","../src/workers/inference-call.ts","../src/failure-class.ts","../src/workers/detection/chunk-size-controller.ts","../src/workers/detection/detection-chunking.ts","../src/workers/detection/motivation-prompts.ts","../src/workers/detection/anchor-audit.ts","../src/workers/detection/motivation-parsers.ts","../src/workers/annotation-detection.ts","../src/workers/detection/entity-extractor.ts","../src/workers/generation/resource-generation.ts","../src/workers/generation/typst-compiler.ts","../src/workers/generation/citation-resolver.ts","../src/workers/detection/bounded-concurrency.ts","../src/processors.ts","../src/worker-runtime.ts"],"names":["fs","toJobId","PROGRESS_WRITE_MIN_INTERVAL_MS","StructuredReadError","isObject","isString","getLocaleEnglishName","estimateTokens","response","join","reconcileSelector","generated","citations"],"mappings":";;;;;;;;;;;;;;;AAgFO,IAAM,eAAA,GAAkB,CAAC,YAAY;AAgBrC,IAAM,yBAAA,GAA4B,EAAA,GAAK,EAAA,GAAK,EAAA,GAAK;AAGjD,IAAM,8BAAA,GAAiC,KAAK,EAAA,GAAK;;;AC7EjD,SAAS,cAAA,CACd,UACA,YAAA,EACS;AACT,EAAA,OAAO,YAAA,KAAiB,eAAA,IAAmB,QAAA,CAAS,UAAA,GAAa,QAAA,CAAS,UAAA;AAC5E;;;ACHO,SAAS,gBAAA,CACd,QAAA,EACA,QAAA,EACA,SAAA,EAC4B;AAC5B,EAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,SAAS,CAAA;AAC9B,EAAA,MAAM,SAAqC,EAAC;AAC5C,EAAA,KAAA,MAAW,CAAC,IAAA,EAAM,MAAM,CAAA,IAAK,MAAA,CAAO,QAAQ,EAAE,GAAG,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IAAM,eAAA,GAA+C;AAAA,EAC1D,GAAG,iBAAiB,yBAAyB,CAAA;AAAA,EAC7C,GAAG;AACL","file":"index.js","sourcesContent":["import type { AnyJob } from './types';\nimport type { EventMap, JobId, UnitCursor } from '@semiont/core';\n\nexport interface JobQueue {\n initialize(): Promise<void>;\n destroy(): void;\n createJob(job: AnyJob): Promise<void>;\n getJob(jobId: JobId): Promise<AnyJob | null>;\n /**\n * Atomically claim the NEXT pending job matching one of `types` — the ONE\n * transition that makes this a queue rather than a state store\n * (JOB-QUEUE-DRIVER P0; reshaped claim-by-TYPE in P2, while every worker\n * is still ours). pending → running, `startedAt` stamped, progress empty.\n * An announcement is a WAKE-UP, not a reservation: the claimed job may\n * differ from any announced one, no ordering among matching pending jobs\n * is promised, and an empty `types` accepts any type. Simultaneous claims\n * admit one winner PER pending job; a claim that finds nothing is\n * DECLINED (`none-available`), never an error.\n */\n claimNextJob(types: string[]): Promise<{ job: AnyJob } | { declined: 'none-available' }>;\n /** Move a running job to `complete`. Returns false if the job isn't running. */\n completeJob(jobId: JobId, result: Record<string, unknown>): Promise<boolean>;\n /**\n * Move a running job back to `pending` (retry, re-announced) while\n * `retryCount < maxRetries`, else to `failed`. Returns what happened,\n * or null if the job isn't running. `completedUnits` — the units the\n * failing attempt fully emitted — are unioned into the record's\n * checkpoint (ABANDONED-INFERENCE P2) so a retry skips them. A\n * `failureClass` of 'deterministic' goes straight to `failed` with any\n * budget remaining — a second identical attempt cannot succeed (P3).\n */\n failJob(jobId: JobId, error: string, completedUnits?: string[], failureClass?: 'transient' | 'deterministic', unitCursors?: Record<string, UnitCursor>): Promise<'retried' | 'failed' | null>;\n /**\n * Persist a running job's completed-unit checkpoint AT unit completion —\n * not only when a job fails (JOB-RESTART-SAFETY P2). `failJob` carries the\n * checkpoint on a clean failure, but a worker that DIES (crash/OOM/kill)\n * never emits `job:fail`, so its finished units would be lost and the\n * janitor's recovery would redo them. This writes them into the running\n * file's metadata as each unit lands, unioned with any existing\n * checkpoint, so recovery resumes rather than restarts. Unthrottled (a\n * unit completion must never be dropped); a no-op for non-running jobs.\n *\n * `unitCursors` is the finer grain `completedUnits` cannot express\n * (CHUNK-GRAIN-RESUME P2): how far an UNFINISHED unit got, so a job that\n * dies mid-unit resumes there instead of at the top. It is written per\n * committed chunk, not per unit.\n *\n * **The two merge differently, and the difference is the contract.**\n * `completedUnits` is a set, so a union converges under concurrent snapshots\n * — a set only grows. A cursor converges only if the merge is **monotone per\n * unit**: a stale snapshot must never move one backward. `next` and `size`\n * move TOGETHER as one observation; taking `size` from one snapshot and\n * `next` from another would describe a chunk that never existed. A unit that\n * reaches `completedUnits` drops its cursor, so \"in progress with a cursor\"\n * and \"complete\" stay structurally exclusive rather than by convention.\n *\n * The rule belongs here rather than to any one driver because it is what\n * makes a cursor safe to merge at all.\n */\n checkpointUnits(jobId: JobId, completedUnits: string[], unitCursors?: Record<string, UnitCursor>): Promise<void>;\n /** Write progress into a running job's file (throttled, best-effort). */\n recordProgress(jobId: JobId, progress: Record<string, unknown>): Promise<void>;\n /**\n * Cancel all pending jobs in a category — 'generation' is the\n * `generation` type; 'annotation' is every `*-annotation` type.\n * Running jobs are left to finish. Returns the number cancelled.\n */\n cancelPendingJobs(category: 'annotation' | 'generation'): Promise<number>;\n cancelJob(jobId: JobId): Promise<boolean>;\n getStats(): Promise<{ pending: number; running: number; complete: number; failed: number; cancelled: number }>;\n}\n\n/**\n * Every bus channel a queue DRIVER emits, maintained beside the interface\n * both drivers implement and censused against their sources\n * (queue-emits-census.test.ts). The gateway's signal bridge forwards these\n * from its local bus onto the plane — a queue announcement that stays on\n * the raw bus reaches no worker under a remote driver (the job:queued\n * starvation, 2026-09-15).\n */\nexport const JOB_QUEUE_EMITS = ['job:queued'] as const satisfies readonly (keyof EventMap)[];\n\n/**\n * How long a job's record survives after it reaches a terminal state\n * (complete/failed/cancelled), and how often a driver enforces that.\n *\n * ONE pair for every driver. The window is a CONTRACT fact — a caller that\n * reads a finished job's result gets the same day whichever backing store the\n * stack runs — and the cadence is what turns the window from an aspiration\n * into a promise. Restated per driver the two numbers drift, and the drift is\n * invisible until someone compares two deployments.\n *\n * The METHOD that enforces retention is not on the interface and cannot be:\n * it is an unlink in one driver and a stream purge in another. The NUMBER is\n * here because it is the same number.\n */\nexport const TERMINAL_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;\n\n/** How often a driver sweeps for records past `TERMINAL_JOB_RETENTION_MS`. */\nexport const TERMINAL_JOB_SWEEP_INTERVAL_MS = 60 * 60 * 1000;\n","import type { JobMetadata } from './types';\n\n/**\n * Will this failure be re-queued for another attempt?\n *\n * ONE decision site, deliberately (JOB-RESTART-SAFETY P5). Two places need\n * the answer and they must never disagree:\n *\n * - `FsJobQueue.failJob` acts on it — re-queue or write the terminal record;\n * - the worker reports it on `job:fail` as `willRetry`, so a client's\n * job-watch stream knows whether the failure it just saw is the end.\n *\n * A second copy of this predicate would be the classic N-places-decide-one-\n * thing bug: the client would end a stream the queue then revived, or hold a\n * stream open on a job nobody will run again. The worker reads the budget off\n * the record it claimed, and `retryCount` only changes inside `failJob`, so\n * the two evaluations see the same numbers.\n *\n * A known-deterministic failure skips the budget outright — the same request\n * cannot succeed on a second attempt, so a retry is guaranteed waste at full\n * price. Unclassified failures are treated as transient.\n */\nexport function willRetryAfter(\n metadata: Pick<JobMetadata, 'retryCount' | 'maxRetries'>,\n failureClass?: 'transient' | 'deterministic',\n): boolean {\n return failureClass !== 'deterministic' && metadata.retryCount < metadata.maxRetries;\n}\n","import type { UnitCursor } from '@semiont/core';\n\n/**\n * Merge per-unit cursors monotonically (CHUNK-GRAIN-RESUME P2).\n *\n * `completedUnits` is a set, so unioning it converges under concurrent\n * snapshots for free — a set only grows. A cursor has no such property: two\n * checkpoints can be in flight at once and the OLDER one can land last, so a\n * last-writer-wins would drag the resume position backward and the retry would\n * re-pay for chunks it already committed. Keeping the furthest `next` per unit\n * is what makes the merge order-independent.\n *\n * `next` and `size` move together because they are ONE observation of one\n * chunk. Taking the furthest `next` from one snapshot and the `size` from\n * another would describe a chunk that was never cut.\n *\n * A unit in `completed` has no cursor at all: \"in progress, here\" and\n * \"finished\" are then structurally exclusive rather than a rule each reader has\n * to remember, and a stale snapshot cannot resurrect a finished unit's cursor.\n *\n * ONE module, shared by every driver (JOB-QUEUE-DRIVER P0): the interface\n * states this rule, and two copies of it would be two chances to disagree\n * about the one property that makes a cursor safe to merge at all.\n */\nexport function mergeUnitCursors(\n existing: Record<string, UnitCursor> | undefined,\n incoming: Record<string, UnitCursor> | undefined,\n completed: string[],\n): Record<string, UnitCursor> {\n const done = new Set(completed);\n const merged: Record<string, UnitCursor> = {};\n for (const [unit, cursor] of Object.entries({ ...existing })) {\n if (!done.has(unit)) merged[unit] = cursor;\n }\n for (const [unit, cursor] of Object.entries({ ...incoming })) {\n if (done.has(unit)) continue;\n const held = merged[unit];\n if (!held || cursor.next > held.next) merged[unit] = cursor;\n }\n return merged;\n}\n","/**\n * Job Queue Manager\n *\n * Filesystem-based job queue with atomic operations.\n * Jobs are stored in directories by status; status transitions are\n * atomic delete + write across directories.\n */\n\nimport { promises as fs } from 'fs';\nimport * as path from 'path';\nimport type { AnyJob, JobStatus, JobQueryFilters, CancelledJob, CompleteJob, FailedJob, PendingJob, RunningJob } from './types';\nimport type { SemiontState } from '@semiont/core/node';\nimport { jobId as toJobId, type JobId, type Logger, type EventBus, type UnitCursor } from '@semiont/core';\nimport { TERMINAL_JOB_RETENTION_MS, TERMINAL_JOB_SWEEP_INTERVAL_MS, type JobQueue } from './job-queue-interface';\nimport { willRetryAfter } from './will-retry';\nimport { mergeUnitCursors } from './checkpoint-merge';\n\n/**\n * The periodic tick: stale running jobs are checked for recovery, and\n * pending jobs are re-announced on `job:queued`.\n *\n * The re-announce is INSURANCE, not dispatch. A worker pulls the queue at\n * every moment it becomes idle — start, settle, a matching wake-up,\n * reconnect — so the announcement in `createJob` is a wake-up with no\n * memory, and a job created while every worker was busy is claimed at the\n * next settle with no help from this timer. What the timer covers is the\n * one case pull cannot: a wake-up LOST in transit to an idle worker, which\n * has nothing to settle and so nothing to pull on. On a healthy stack the\n * re-announce never acts. A duplicate announcement is harmless: a claim is\n * by type, atomic in the queue, and an idle worker that hears one simply\n * asks and is told nothing is pending.\n */\nconst REANNOUNCE_INTERVAL_MS = 30_000;\n\n/**\n * A running job whose file hasn't been touched for this long is\n * presumed orphaned by a dead worker and fed through the retry-or-fail\n * path. Progress writes (`recordProgress`) refresh the file's mtime,\n * so this is a heartbeat timeout, not a job-duration limit — but a\n * worker that emits no progress for the whole window will be falsely\n * recovered, so it stays deliberately generous.\n */\nconst STALE_RUNNING_MS = 30 * 60_000;\n\n/** Minimum spacing between progress writes per job — workers can be chatty. */\nconst PROGRESS_WRITE_MIN_INTERVAL_MS = 5_000;\n\nexport class FsJobQueue implements JobQueue {\n private jobsDir: string;\n private logger: Logger;\n private reannounceTimer: ReturnType<typeof setInterval> | null = null;\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n /** Per-job timestamp of the last progress write, for throttling. */\n private lastProgressWrite = new Map<string, number>();\n\n constructor(\n /** `SemiontState` and not `SemiontProject`: the queue reads ONE path,\n * and the gateway that owns it mounts no KB tree (SINGLE-KB-MOUNT P5). */\n state: SemiontState,\n logger: Logger,\n private eventBus?: EventBus\n ) {\n this.jobsDir = state.jobsDir;\n this.logger = logger;\n }\n\n /**\n * Initialize job queue directories, announce any pending backlog,\n * and start the re-announce interval. Idempotent.\n */\n async initialize(): Promise<void> {\n const statuses: JobStatus[] = ['pending', 'running', 'complete', 'failed', 'cancelled'];\n\n for (const status of statuses) {\n const dir = path.join(this.jobsDir, status);\n await fs.mkdir(dir, { recursive: true });\n }\n\n if (this.eventBus && !this.reannounceTimer) {\n // Jobs left pending across a restart are announced right away — a\n // wake-up for any worker already parked and connected…\n await this.announcePendingJobs();\n // …then the tick: recovery of jobs orphaned by a dead worker, and the\n // lost-wake-up insurance the header describes.\n this.reannounceTimer = setInterval(() => {\n this.announcePendingJobs().catch((error) => {\n this.logger.warn('Pending-job re-announce failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n this.recoverStaleRunningJobs().catch((error) => {\n this.logger.warn('Stale-running recovery failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }, REANNOUNCE_INTERVAL_MS);\n // Don't let the interval keep the process alive on shutdown.\n this.reannounceTimer.unref?.();\n }\n\n if (!this.cleanupTimer) {\n this.cleanupTimer = setInterval(() => {\n this.cleanupOldJobs(TERMINAL_JOB_RETENTION_MS).catch((error) => {\n this.logger.warn('Job retention cleanup failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }, TERMINAL_JOB_SWEEP_INTERVAL_MS);\n this.cleanupTimer.unref?.();\n }\n\n this.logger.info('Job queue initialized');\n }\n\n /**\n * Stop the re-announce and retention intervals\n */\n destroy(): void {\n if (this.reannounceTimer) {\n clearInterval(this.reannounceTimer);\n this.reannounceTimer = null;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n }\n\n /**\n * Emit `job:queued` for a pending job, if an EventBus is wired and\n * the job carries a `resourceId` (every current job type does).\n */\n private announce(job: AnyJob): void {\n if (this.eventBus && 'params' in job && 'resourceId' in job.params) {\n this.eventBus.emit('job:queued', {\n jobId: job.metadata.id,\n jobType: job.metadata.type,\n resourceId: job.params.resourceId,\n userId: job.metadata.userId,\n });\n }\n }\n\n /**\n * Announce every job currently in `pending/`. Files that vanish or\n * fail to parse mid-scan (claimed, cancelled, partially written)\n * are skipped — they're either gone for a good reason or picked up\n * on the next tick.\n */\n private async announcePendingJobs(): Promise<void> {\n const pendingDir = path.join(this.jobsDir, 'pending');\n let files: string[];\n try {\n files = await fs.readdir(pendingDir);\n } catch {\n return;\n }\n files.sort();\n for (const file of files) {\n try {\n const content = await fs.readFile(path.join(pendingDir, file), 'utf-8');\n this.announce(JSON.parse(content) as AnyJob);\n } catch {\n // Skip unreadable files\n }\n }\n }\n\n /**\n * Create a new job\n */\n async createJob(job: AnyJob): Promise<void> {\n const jobPath = this.getJobPath(job.metadata.id, job.status);\n await fs.writeFile(jobPath, JSON.stringify(job, null, 2), 'utf-8');\n this.logger.info('Job created', { jobId: job.metadata.id, status: job.status });\n\n if (job.status === 'pending') {\n this.announce(job);\n }\n }\n\n /**\n * Get a job by ID (searches all status directories)\n */\n async getJob(jobId: JobId): Promise<AnyJob | null> {\n const statuses: JobStatus[] = ['pending', 'running', 'complete', 'failed', 'cancelled'];\n\n for (const status of statuses) {\n const jobPath = this.getJobPath(jobId, status);\n try {\n const content = await fs.readFile(jobPath, 'utf-8');\n return JSON.parse(content) as AnyJob;\n } catch (error) {\n // File doesn't exist in this status directory, try next\n continue;\n }\n }\n\n return null;\n }\n\n /**\n * Serializes claims. This driver's atomicity is single-process by design,\n * but `claimJob`'s contract must hold even against interleaved awaits in\n * that one process — a read-check-write with await points in it can admit\n * two winners without this chain (the TOCTOU the operation exists to kill).\n */\n private claimChain: Promise<unknown> = Promise.resolve();\n\n async claimNextJob(types: string[]): Promise<{ job: AnyJob } | { declined: 'none-available' }> {\n const claim = this.claimChain.then(() => this.doClaimNext(types));\n // A failed claim must not wedge every later one.\n this.claimChain = claim.catch(() => undefined);\n return claim;\n }\n\n private async doClaimNext(types: string[]): Promise<{ job: AnyJob } | { declined: 'none-available' }> {\n const pending = await this.listJobs({ status: 'pending', limit: Number.MAX_SAFE_INTEGER });\n const match = pending.find((j) => types.length === 0 || types.includes(j.metadata.type));\n if (!match) return { declined: 'none-available' };\n\n // Progress starts empty: a just-claimed job has reported nothing yet.\n // The typed progress shapes describe REPORTS, and the first report\n // arrives from the worker via recordProgress.\n const running: RunningJob<any, any> = {\n status: 'running',\n metadata: match.metadata,\n params: match.params,\n startedAt: new Date().toISOString(),\n progress: {},\n };\n await this.transition(running, 'pending');\n return { job: running };\n }\n\n /**\n * Update a job (atomic: delete old, write new)\n */\n /**\n * Cross-status move (or in-place rewrite): delete old slot, write new.\n * Private — the interface exposes named transitions only (JOB-QUEUE-DRIVER\n * P0); a generic public patch is trivial on files and impossible on an\n * in-flight message, so no driver may offer one. Re-entering `pending`\n * announces, which is how failJob's retry reaches a listening worker.\n */\n private async transition(job: AnyJob, oldStatus?: JobStatus): Promise<void> {\n // If oldStatus provided, delete from old location\n if (oldStatus && oldStatus !== job.status) {\n const oldPath = this.getJobPath(job.metadata.id, oldStatus);\n try {\n await fs.unlink(oldPath);\n } catch (error) {\n // Ignore if file doesn't exist\n }\n }\n\n // Write to new location\n const newPath = this.getJobPath(job.metadata.id, job.status);\n await fs.writeFile(newPath, JSON.stringify(job, null, 2), 'utf-8');\n\n if (oldStatus && oldStatus !== job.status) {\n this.logger.info('Job moved', { jobId: job.metadata.id, oldStatus, newStatus: job.status });\n // Re-entering pending (e.g. a retry) is a fresh announcement.\n if (job.status === 'pending') {\n this.announce(job);\n }\n } else {\n this.logger.info('Job updated', { jobId: job.metadata.id, status: job.status });\n }\n }\n\n /**\n * Move a running job to `complete`. Returns false (and changes\n * nothing) if the job is missing or not running — which also makes\n * duplicate `job:complete` events harmless.\n */\n async completeJob(jobId: JobId, result: Record<string, unknown>): Promise<boolean> {\n const job = await this.getJob(jobId);\n if (!job || job.status !== 'running') {\n return false;\n }\n\n this.lastProgressWrite.delete(jobId);\n const completed: CompleteJob<any, any> = {\n status: 'complete',\n metadata: job.metadata,\n params: job.params,\n startedAt: job.startedAt,\n completedAt: new Date().toISOString(),\n result,\n };\n await this.transition(completed, 'running');\n return true;\n }\n\n /**\n * Retry-or-fail a running job. While `retryCount < maxRetries` the\n * job goes back to `pending` with the count bumped (and is\n * re-announced); after that it lands in `failed` with the error.\n * Returns null (and changes nothing) if the job isn't running.\n */\n async failJob(jobId: JobId, error: string, completedUnits?: string[], failureClass?: 'transient' | 'deterministic', unitCursors?: Record<string, UnitCursor>): Promise<'retried' | 'failed' | null> {\n const job = await this.getJob(jobId);\n if (!job || job.status !== 'running') {\n return null;\n }\n\n this.lastProgressWrite.delete(jobId);\n\n // Checkpointed resume (ABANDONED-INFERENCE P2): union this attempt's\n // completed units with earlier attempts' — attempt 3 must keep what\n // attempt 1 finished. Stored in metadata so the spread below (and in\n // every later rebuild) carries it forward; the terminal failed record\n // keeps it too, so the waste of a discarded run stays visible (D3).\n const checkpoint = [...new Set([...(job.metadata.completedUnits ?? []), ...(completedUnits ?? [])])];\n // The mid-unit half of the same checkpoint (CHUNK-GRAIN-RESUME P2), merged\n // by the same monotone rule the durable per-chunk writes use — `failJob`\n // and `checkpointUnits` race on the same record, and whichever lands last\n // must not drag a cursor back.\n const cursors = mergeUnitCursors(job.metadata.unitCursors, unitCursors, checkpoint);\n const { unitCursors: superseded, ...base } = job.metadata;\n void superseded;\n const metadata = {\n ...base,\n ...(checkpoint.length > 0 ? { completedUnits: checkpoint } : {}),\n ...(Object.keys(cursors).length > 0 ? { unitCursors: cursors } : {}),\n };\n\n // A known-deterministic failure skips the budget outright: the same\n // request cannot succeed on a second attempt, so a retry is guaranteed\n // waste at full price (ABANDONED-INFERENCE P3, A4). Unclassified and\n // transient failures retry as before.\n if (willRetryAfter(job.metadata, failureClass)) {\n const retried: PendingJob<any> = {\n status: 'pending',\n metadata: { ...metadata, retryCount: job.metadata.retryCount + 1 },\n params: job.params,\n };\n await this.transition(retried, 'running');\n return 'retried';\n }\n\n if (failureClass === 'deterministic' && job.metadata.retryCount < job.metadata.maxRetries) {\n this.logger.info('Job failed without retry — deterministic failure', { jobId, error });\n }\n\n const failed: FailedJob<any> = {\n status: 'failed',\n metadata,\n params: job.params,\n startedAt: job.startedAt,\n completedAt: new Date().toISOString(),\n error,\n };\n await this.transition(failed, 'running');\n return 'failed';\n }\n\n /**\n * Persist a running job's completed-unit checkpoint at unit completion\n * (JOB-RESTART-SAFETY P2). `failJob` writes this checkpoint on a clean\n * failure, but a worker that dies without emitting `job:fail` would lose\n * its finished units — so the janitor's recovery (which re-queues with\n * whatever `metadata.completedUnits` the running file holds) would redo\n * them. Writing it HERE, as each unit lands, makes a crash lose at most\n * the in-flight unit. Unioned with any existing checkpoint, unthrottled\n * (a unit completion is rare and must never be dropped), a no-op for\n * non-running jobs. Written directly, like `recordProgress`, so it also\n * refreshes the mtime heartbeat.\n */\n async checkpointUnits(jobId: JobId, completedUnits: string[], unitCursors?: Record<string, UnitCursor>): Promise<void> {\n const job = await this.getJob(jobId);\n if (!job || job.status !== 'running') {\n return;\n }\n const merged = [...new Set([...(job.metadata.completedUnits ?? []), ...completedUnits])];\n const cursors = mergeUnitCursors(job.metadata.unitCursors, unitCursors, merged);\n // The prior value is destructured OUT rather than spread over: omitting a\n // key from a spread leaves the old one in place, so the last unit to finish\n // would keep a cursor pointing into work that is done.\n const { unitCursors: superseded, ...metadata } = job.metadata;\n void superseded;\n const updated: RunningJob<any, any> = {\n ...job,\n metadata: {\n ...metadata,\n completedUnits: merged,\n // Absent rather than `{}`: an empty object would assert that units were\n // tracked and none had progress, a different claim from a job that\n // never reported a cursor at all.\n ...(Object.keys(cursors).length > 0 ? { unitCursors: cursors } : {}),\n },\n };\n await fs.writeFile(this.getJobPath(jobId, 'running'), JSON.stringify(updated, null, 2), 'utf-8');\n }\n\n /**\n * Write progress into a running job's file. Throttled per job, and\n * a no-op for jobs that aren't running. Beyond surfacing live\n * progress to `job:status-requested`, each write refreshes the\n * file's mtime — the heartbeat `recoverStaleRunningJobs` watches.\n */\n async recordProgress(jobId: JobId, progress: Record<string, unknown>): Promise<void> {\n const now = Date.now();\n const lastWrite = this.lastProgressWrite.get(jobId) ?? 0;\n if (now - lastWrite < PROGRESS_WRITE_MIN_INTERVAL_MS) {\n return;\n }\n this.lastProgressWrite.set(jobId, now);\n\n const job = await this.getJob(jobId);\n if (!job || job.status !== 'running') {\n this.lastProgressWrite.delete(jobId);\n return;\n }\n\n // Written directly (not via updateJob) so chatty progress doesn't\n // flood the info log.\n const updated: RunningJob<any, any> = { ...job, progress };\n await fs.writeFile(this.getJobPath(jobId, 'running'), JSON.stringify(updated, null, 2), 'utf-8');\n }\n\n /**\n * List jobs with filters\n */\n async listJobs(filters: JobQueryFilters = {}): Promise<AnyJob[]> {\n const jobs: AnyJob[] = [];\n\n // Determine which status directories to scan\n const statuses: JobStatus[] = filters.status\n ? [filters.status]\n : ['pending', 'running', 'complete', 'failed', 'cancelled'];\n\n for (const status of statuses) {\n const statusDir = path.join(this.jobsDir, status);\n\n try {\n const files = await fs.readdir(statusDir);\n\n for (const file of files) {\n const jobPath = path.join(statusDir, file);\n const content = await fs.readFile(jobPath, 'utf-8');\n const job = JSON.parse(content) as AnyJob;\n\n // Apply filters\n if (filters.type && job.metadata.type !== filters.type) continue;\n if (filters.userId && job.metadata.userId !== filters.userId) continue;\n\n jobs.push(job);\n }\n } catch (error) {\n // Directory might not exist yet\n continue;\n }\n }\n\n // Sort by created descending (newest first)\n jobs.sort((a, b) => new Date(b.metadata.created).getTime() - new Date(a.metadata.created).getTime());\n\n // Apply pagination\n const offset = filters.offset || 0;\n const limit = filters.limit || 100;\n\n return jobs.slice(offset, offset + limit);\n }\n\n /**\n * Cancel a job\n */\n async cancelJob(jobId: JobId): Promise<boolean> {\n const job = await this.getJob(jobId);\n\n if (!job) {\n return false;\n }\n\n // Can only cancel pending or running jobs\n if (job.status !== 'pending' && job.status !== 'running') {\n return false;\n }\n\n const oldStatus = job.status;\n\n // Create cancelled job with proper structure\n const cancelledJob: CancelledJob<any> = {\n status: 'cancelled',\n metadata: job.metadata,\n params: job.status === 'pending' ? job.params : job.params,\n startedAt: job.status === 'running' ? job.startedAt : undefined,\n completedAt: new Date().toISOString(),\n };\n\n await this.transition(cancelledJob, oldStatus);\n return true;\n }\n\n /**\n * Cancel all pending jobs in a category — the granularity of the\n * `job:cancel-requested` UI signal. Running jobs are left to finish:\n * interrupting a worker mid-inference would need a worker-side kill\n * channel that doesn't exist.\n */\n async cancelPendingJobs(category: 'annotation' | 'generation'): Promise<number> {\n const matches = category === 'generation'\n ? (type: string) => type === 'generation'\n : (type: string) => type.endsWith('-annotation');\n\n const pending = await this.listJobs({ status: 'pending', limit: Number.MAX_SAFE_INTEGER });\n let cancelled = 0;\n for (const job of pending) {\n if (!matches(job.metadata.type)) continue;\n if (await this.cancelJob(job.metadata.id)) {\n cancelled++;\n }\n }\n\n if (cancelled > 0) {\n this.logger.info('Cancelled pending jobs', { category, cancelled });\n }\n return cancelled;\n }\n\n /**\n * Recover running jobs orphaned by a dead worker: any `running/`\n * file whose mtime is older than the stale window is fed through\n * the same retry-or-fail path as `job:fail`. Progress writes\n * refresh the mtime, so a live worker is never recovered out from\n * under itself as long as it reports within the window.\n */\n async recoverStaleRunningJobs(): Promise<number> {\n const runningDir = path.join(this.jobsDir, 'running');\n let files: string[];\n try {\n files = await fs.readdir(runningDir);\n } catch {\n return 0;\n }\n\n const now = Date.now();\n let recovered = 0;\n for (const file of files) {\n if (!file.endsWith('.json')) continue;\n try {\n const stat = await fs.stat(path.join(runningDir, file));\n if (now - stat.mtimeMs < STALE_RUNNING_MS) continue;\n\n const staleId = toJobId(file.slice(0, -'.json'.length));\n const outcome = await this.failJob(\n staleId,\n `worker presumed dead — no progress within ${STALE_RUNNING_MS / 60_000} minutes`,\n );\n if (outcome) {\n this.logger.warn('Recovered stale running job', { jobId: staleId, outcome });\n recovered++;\n }\n } catch {\n // File vanished mid-scan (job finished) — nothing to recover\n }\n }\n return recovered;\n }\n\n /**\n * Delete terminal jobs whose `completedAt` is older than `retentionMs`.\n * The window is a parameter with no default: the ONE value the queue runs\n * on is `TERMINAL_JOB_RETENTION_MS`, and a default here would be a second\n * copy of it that nobody notices going stale.\n */\n async cleanupOldJobs(retentionMs: number): Promise<number> {\n const cutoffTime = Date.now() - retentionMs;\n let deletedCount = 0;\n\n const cleanupStatuses: JobStatus[] = ['complete', 'failed', 'cancelled'];\n\n for (const status of cleanupStatuses) {\n const statusDir = path.join(this.jobsDir, status);\n\n try {\n const files = await fs.readdir(statusDir);\n\n for (const file of files) {\n const jobPath = path.join(statusDir, file);\n const content = await fs.readFile(jobPath, 'utf-8');\n const job = JSON.parse(content) as AnyJob;\n\n if (job.status === 'complete' || job.status === 'failed' || job.status === 'cancelled') {\n const completedTime = new Date(job.completedAt).getTime();\n\n if (completedTime < cutoffTime) {\n await fs.unlink(jobPath);\n deletedCount++;\n }\n }\n }\n } catch (error) {\n this.logger.error('Error cleaning up jobs', { status, error: error instanceof Error ? error.message : String(error) });\n }\n }\n\n if (deletedCount > 0) {\n this.logger.info('Jobs cleaned up', { deletedCount });\n }\n\n return deletedCount;\n }\n\n /**\n * Get job file path\n */\n private getJobPath(jobId: JobId, status: JobStatus): string {\n return path.join(this.jobsDir, status, `${jobId}.json`);\n }\n\n /**\n * Get statistics about the queue\n */\n async getStats(): Promise<{\n pending: number;\n running: number;\n complete: number;\n failed: number;\n cancelled: number;\n }> {\n const stats = {\n pending: 0,\n running: 0,\n complete: 0,\n failed: 0,\n cancelled: 0\n };\n\n const statuses: JobStatus[] = ['pending', 'running', 'complete', 'failed', 'cancelled'];\n\n for (const status of statuses) {\n const statusDir = path.join(this.jobsDir, status);\n\n try {\n const files = await fs.readdir(statusDir);\n stats[status] = files.length;\n } catch (error) {\n // Directory might not exist yet\n stats[status] = 0;\n }\n }\n\n return stats;\n }\n}\n","/**\n * JetStreamJobQueue — the JetStream driver behind the `JobQueue` interface\n * (JOB-QUEUE-DRIVER P1, topology ruling M: broker-mediated — the queue's own\n * process holds the broker connection and the leases; workers never touch the\n * broker. That process was the gateway; it is the dispatcher now.)\n *\n * Two primitives, one authority each:\n *\n * - **KV bucket `jobs`** is the AUTHORITATIVE operational state: one entry\n * per job (`{ job, lastProgressAt }`), every transition a revision-CAS —\n * which is what makes `claimJob` atomic: simultaneous claims race on one\n * revision and exactly one update wins. It holds LIVE jobs plus a day of\n * concluded ones, not a history: `pruneTerminalJobs` is the retention the\n * fs driver's janitor holds, and without it every scan over the bucket\n * — `getStats` is one, on the metrics interval — grows forever.\n * - **Stream `JOBS`** (subjects `jobs.<category>.<type>`, work-queue\n * retention) is the DELIVERY vehicle and redelivery timer. A delivered\n * message is the lease this process holds for a job; `working()`\n * heartbeats extend it, and a dispatcher that dies stops heartbeating, so\n * `AckWait` redelivers the job to a live instance — dispatcher-death\n * recovery, protocol-native.\n *\n * Worker-death recovery is NOT AckWait's job under the mediated topology\n * (the dispatcher holding the lease is alive; the worker vanished): it is the\n * `lastProgressAt` sweep (`recoverStaleRunningJobs`), the same contract the\n * fs driver's mtime janitor implemented. The redelivery handler checks KV\n * state, so the two recovery paths can never double-apply.\n *\n * Battery ownership (JOB-QUEUE-DRIVER P0): the retry decision belongs to\n * `will-retry.ts` — `max_deliver` is unlimited and a deterministic failure\n * is `term()`ed, so the backend's retry engine never becomes a second\n * authority. The cursor merge belongs to `checkpoint-merge.ts`, shared with\n * every driver.\n *\n * The boundary is the point: no NATS type, subject string, or delivery\n * handle escapes this file.\n */\n\nimport { connect, NatsError, RetentionPolicy, AckPolicy, DeliverPolicy, nanos } from 'nats';\nimport type { NatsConnection, JetStreamClient, JetStreamManager, JsMsg, KV, ConsumerMessages } from 'nats';\nimport type { AnyJob, PendingJob, RunningJob, FailedJob, CompleteJob, CancelledJob } from './types';\nimport { jobId as toJobId, JOBS_STREAM_SUBJECTS, JOBS_SUBJECT_ROOT, type JobId, type Logger, type EventBus, type UnitCursor } from '@semiont/core';\nimport { TERMINAL_JOB_RETENTION_MS, TERMINAL_JOB_SWEEP_INTERVAL_MS, type JobQueue } from './job-queue-interface';\nimport { willRetryAfter } from './will-retry';\nimport { mergeUnitCursors } from './checkpoint-merge';\n\nconst STREAM = 'JOBS';\n// The durable consumer keeps its original name: it is a WIRE name on every\n// deployed broker, and renaming it would orphan the consumer and its leases.\n// The process that holds it is the dispatcher.\nconst CONSUMER = 'gateway-claims';\nconst BUCKET = 'jobs';\n/**\n * The bucket's own backing stream and per-key subject (the NATS KV layout\n * every client shares). The retention sweep purges a concluded job at the\n * STREAM rather than through `KV.purge`, because a KV delete or purge is a\n * TOMBSTONE: it strips the value and leaves a marker message on the key's\n * subject forever. That is the same unbounded growth the sweep exists to\n * end, a thousand times cheaper — and nothing watches this bucket, so the\n * marker has no reader to notify. A stream purge by subject leaves nothing.\n *\n * Restating two wire strings is what this file is FOR (no NATS subject\n * escapes it), and they are gated rather than trusted: the retention test\n * asserts the bucket's message count, so a name that stops matching fails\n * there instead of silently purging nothing.\n */\nconst BUCKET_STREAM = `KV_${BUCKET}`;\nconst bucketSubject = (key: string) => `$KV.${BUCKET}.${key}`;\n\n/** Minimum spacing between progress writes per job — workers can be chatty. */\nconst PROGRESS_WRITE_MIN_INTERVAL_MS = 5_000;\n\n/** Bounded CAS retries: past this, something is systemically wrong. */\nconst MAX_CAS_ATTEMPTS = 20;\n\nconst enc = new TextEncoder();\nconst dec = new TextDecoder();\n\n/** The KV record: the job plus the liveness fact the sweep reads. */\ninterface JobEnvelope {\n job: AnyJob;\n lastProgressAt: string;\n}\n\nexport interface JetStreamJobQueueOptions {\n /** NATS server address(es), e.g. \"192.168.64.42:4222\". */\n servers: string | string[];\n /**\n * Broker credentials (INTER-COMPONENT-ACCESS P3). The same broker the signal\n * plane connects to, so the same pair. Absent means an unauthenticated\n * broker — which is what every deployment had before this, and means anyone\n * who can reach NATS can read and write the job stream.\n */\n user?: string;\n pass?: string;\n /** Worker presumed dead after this long without progress (default 30 min). */\n staleRunningMs?: number;\n /** Lease redelivery window when THIS process stops heartbeating (default 30 s). */\n ackWaitMs?: number;\n /** Re-announce + worker-death-sweep cadence (default 30 s; tests shrink it). */\n tickMs?: number;\n /** Reconnect on connection loss (default true; tests turn it off). */\n reconnect?: boolean;\n}\n\nfunction categoryOf(type: string): 'annotation' | 'generation' {\n return type === 'generation' ? 'generation' : 'annotation';\n}\n\nfunction subjectFor(job: AnyJob): string {\n return `${JOBS_SUBJECT_ROOT}.${categoryOf(job.metadata.type)}.${job.metadata.type}`;\n}\n\nexport class JetStreamJobQueue implements JobQueue {\n private nc!: NatsConnection;\n private js!: JetStreamClient;\n private jsm!: JetStreamManager;\n private kv!: KV;\n private iter: ConsumerMessages | null = null;\n /** Delivered messages this process holds — the lease, keyed by jobId,\n * with the job's type so a by-type claim can walk them without a read. */\n private readonly held = new Map<string, { m: JsMsg; type: string }>();\n private heartbeat: ReturnType<typeof setInterval> | null = null;\n private reconciling = false;\n private tick: ReturnType<typeof setInterval> | null = null;\n private ticking = false;\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n private readonly lastProgressWrite = new Map<string, number>();\n private readonly staleRunningMs: number;\n private readonly ackWaitMs: number;\n private readonly tickMs: number;\n\n constructor(\n private readonly options: JetStreamJobQueueOptions,\n private readonly logger: Logger,\n private readonly eventBus?: EventBus,\n ) {\n this.staleRunningMs = options.staleRunningMs ?? 30 * 60_000;\n this.ackWaitMs = options.ackWaitMs ?? 30_000;\n this.tickMs = options.tickMs ?? 30_000;\n }\n\n async initialize(): Promise<void> {\n this.nc = await connect({\n servers: this.options.servers,\n // The same broker as the signal plane, so the same credentials. Connect\n // options rather than a URL: this address is logged on every reconnect.\n ...(this.options.user === undefined ? {} : { user: this.options.user }),\n ...(this.options.pass === undefined ? {} : { pass: this.options.pass }),\n reconnect: this.options.reconnect ?? true,\n // For as long as the broker is unreachable: a manual broker restart is\n // the recovery, and the library's ten attempts (~20 s) closed the\n // signal plane's connection for good in its first live outage.\n maxReconnectAttempts: -1,\n timeout: 10_000,\n });\n this.watchConnection();\n this.js = this.nc.jetstream();\n this.jsm = await this.nc.jetstreamManager();\n this.kv = await this.js.views.kv(BUCKET);\n\n try {\n await this.jsm.streams.info(STREAM);\n } catch {\n await this.jsm.streams.add({\n name: STREAM,\n subjects: [...JOBS_STREAM_SUBJECTS],\n retention: RetentionPolicy.Workqueue,\n });\n }\n try {\n await this.jsm.consumers.info(STREAM, CONSUMER);\n } catch {\n await this.jsm.consumers.add(STREAM, {\n durable_name: CONSUMER,\n ack_policy: AckPolicy.Explicit,\n deliver_policy: DeliverPolicy.All,\n ack_wait: nanos(this.ackWaitMs),\n // ONE retry authority: will-retry.ts decides; the stream never\n // gives up a message on its own count.\n max_deliver: -1,\n });\n }\n\n const consumer = await this.js.consumers.get(STREAM, CONSUMER);\n this.iter = await consumer.consume({\n callback: (m) => {\n void this.onDelivery(m).catch((error) => {\n this.logger.warn('Job delivery handling failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n },\n });\n\n // The lease heartbeat doubles as RECONCILIATION (the multi-instance\n // lease-settle pin): a held delivery whose job concluded on ANOTHER\n // instance — its claim lost the CAS race, or a redelivery landed here\n // after a dispatcher death — can only be settled by the holder, because\n // nobody else has the delivery to ack. Terminal in KV → ack and drop;\n // otherwise the lease extends. While this process is alive its leases\n // never expire; when it dies they redeliver after ackWait — that IS the\n // dispatcher-death recovery path.\n this.heartbeat = setInterval(() => {\n if (this.reconciling) return;\n this.reconciling = true;\n void this.reconcileHeld()\n .catch((error) => {\n this.logger.warn('Held-lease reconciliation failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .finally(() => {\n this.reconciling = false;\n });\n }, Math.max(250, Math.floor(this.ackWaitMs / 4)));\n this.heartbeat.unref?.();\n\n // The queue's periodic tick, mirroring the fs driver's internal janitor:\n // (a) RE-ANNOUNCE held pending deliveries — INSURANCE, not dispatch. A\n // worker pulls at every idle moment (start, settle, wake-up,\n // reconnect), so a job created while it was busy is claimed at the\n // settle without this tick. What this covers is a wake-up LOST in\n // transit to an idle worker, which has nothing to settle and so\n // nothing to pull on. On a healthy stack it never acts;\n // (b) SWEEP for worker death (`recoverStaleRunningJobs`) — `AckWait`\n // covers a dead GATEWAY; only this sweep covers a dead WORKER, and\n // rows do not sweep themselves (JOB-RESTART-SAFETY P7).\n this.tick = setInterval(() => {\n if (this.ticking) return;\n this.ticking = true;\n void (async () => {\n for (const [id, held] of [...this.held]) {\n const envelope = await this.read(toJobId(id));\n if (envelope?.job.status === 'pending') this.announce(envelope.job);\n void held;\n }\n await this.recoverStaleRunningJobs();\n })()\n .catch((error) => {\n this.logger.warn('Job-queue tick failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n })\n .finally(() => {\n this.ticking = false;\n });\n }, this.tickMs);\n this.tick.unref?.();\n\n // Retention, on its own slower clock — the fs driver's second janitor,\n // restored (`cleanupTimer` there, hourly, the same window). It is not\n // folded into the tick above because the two answer to different costs:\n // the tick must run at claim latency, a retention sweep purging a day-old\n // record is indifferent to a minute either way, and running it 120 times\n // an hour would spend a full bucket scan to find nothing 119 times.\n this.cleanupTimer = setInterval(() => {\n this.pruneTerminalJobs(TERMINAL_JOB_RETENTION_MS).catch((error) => {\n this.logger.warn('Job retention cleanup failed', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }, TERMINAL_JOB_SWEEP_INTERVAL_MS);\n this.cleanupTimer.unref?.();\n }\n\n /** An outage is never silent: one line down, one line back, one line if the client gives up. */\n private watchConnection(): void {\n const servers = this.options.servers;\n void (async () => {\n for await (const status of this.nc.status()) {\n if (status.type === 'disconnect') {\n this.logger.warn('[jobs BROKER-DOWN] NATS connection lost; queue operations fail until reconnect', { servers });\n } else if (status.type === 'reconnect') {\n this.logger.info('[jobs BROKER-RECONNECTED] NATS connection restored', { servers });\n }\n }\n })();\n // Unreachable is retried forever; refused is not. Two identical refusals\n // in a row end the client's reconnect loop whatever the attempt budget\n // says, and a broker that came back with other credentials is exactly\n // that. destroy() closes without an error.\n void this.nc.closed().then((err) => {\n if (!err) return;\n this.logger.error('[jobs BROKER-CLOSED] NATS connection closed; the client will not reconnect', {\n servers,\n reason: err instanceof NatsError ? err.code : err.message,\n });\n });\n }\n\n destroy(): void {\n this.iter?.stop();\n this.iter = null;\n if (this.heartbeat) clearInterval(this.heartbeat);\n this.heartbeat = null;\n if (this.tick) clearInterval(this.tick);\n this.tick = null;\n if (this.cleanupTimer) clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n this.held.clear();\n void this.nc?.close();\n }\n\n /**\n * A delivery is a job arriving at this dispatcher. What it means depends on\n * the job's authoritative (KV) state:\n * - pending → hold the lease, announce for a worker to claim;\n * - running → hold silently (a claim raced ahead of the delivery, or a\n * redelivery reached a fresh instance after a dispatcher death);\n * - terminal → the work already concluded elsewhere; consume the message;\n * - unknown → not ours to run; terminate it.\n */\n private async onDelivery(m: JsMsg): Promise<void> {\n let id: string;\n try {\n id = (JSON.parse(dec.decode(m.data)) as { jobId: string }).jobId;\n } catch {\n m.term();\n return;\n }\n const envelope = await this.read(toJobId(id));\n if (!envelope) {\n m.term();\n return;\n }\n switch (envelope.job.status) {\n case 'pending':\n this.held.set(id, { m, type: envelope.job.metadata.type });\n this.announce(envelope.job);\n break;\n case 'running':\n this.held.set(id, { m, type: envelope.job.metadata.type });\n break;\n default:\n m.ack();\n this.held.delete(id);\n }\n }\n\n /** Same wire shape as the fs driver: only jobs with a resourceId announce. */\n private announce(job: AnyJob): void {\n if (this.eventBus && 'params' in job && 'resourceId' in (job.params as Record<string, unknown>)) {\n this.eventBus.emit('job:queued', {\n jobId: job.metadata.id,\n jobType: job.metadata.type,\n resourceId: (job.params as { resourceId: unknown }).resourceId as never,\n userId: job.metadata.userId,\n });\n }\n }\n\n private async read(jobIdArg: JobId): Promise<{ job: AnyJob; lastProgressAt: string; revision: number } | null> {\n const entry = await this.kv.get(jobIdArg as string);\n if (!entry || entry.operation !== 'PUT') return null;\n const envelope = JSON.parse(dec.decode(entry.value)) as JobEnvelope;\n return { ...envelope, revision: entry.revision };\n }\n\n private async write(jobIdArg: JobId, envelope: JobEnvelope, revision?: number): Promise<number> {\n const payload = enc.encode(JSON.stringify(envelope));\n if (revision === undefined) return this.kv.put(jobIdArg as string, payload);\n return this.kv.update(jobIdArg as string, payload, revision);\n }\n\n /**\n * Read-transform-CAS with bounded retries: the transform sees the current\n * job and returns the replacement (or null to stop). Every state\n * transition goes through here, which is what makes each one atomic.\n */\n private async cas<T>(\n jobIdArg: JobId,\n transform: (job: AnyJob, lastProgressAt: string) => { envelope: JobEnvelope; result: T } | { result: T } | null,\n onMissing: T,\n ): Promise<T> {\n for (let attempt = 0; attempt < MAX_CAS_ATTEMPTS; attempt++) {\n const current = await this.read(jobIdArg);\n if (!current) return onMissing;\n const out = transform(current.job, current.lastProgressAt);\n if (out === null) return onMissing;\n if (!('envelope' in out)) return out.result;\n try {\n await this.write(jobIdArg, out.envelope, current.revision);\n return out.result;\n } catch {\n // Revision conflict — someone else transitioned first; re-read.\n }\n }\n throw new Error(`Job ${jobIdArg} transition failed after ${MAX_CAS_ATTEMPTS} CAS attempts`);\n }\n\n async createJob(job: AnyJob): Promise<void> {\n const now = new Date().toISOString();\n await this.kv.create(job.metadata.id as string, enc.encode(JSON.stringify({ job, lastProgressAt: now } satisfies JobEnvelope)));\n // Only pending jobs need delivery — the stream is the claim vehicle,\n // not the record (KV is).\n if (job.status === 'pending') {\n await this.js.publish(subjectFor(job), enc.encode(JSON.stringify({ jobId: job.metadata.id })));\n }\n }\n\n async getJob(jobIdArg: JobId): Promise<AnyJob | null> {\n const envelope = await this.read(jobIdArg);\n return envelope?.job ?? null;\n }\n\n async claimNextJob(types: string[]): Promise<{ job: AnyJob } | { declined: 'none-available' }> {\n const matches = (t: string) => types.length === 0 || types.includes(t);\n // Lease-aligned fast path (topology memo, mechanic 1): deliveries this\n // dispatcher already holds — the claim lands where the worker is connected.\n for (const [id, held] of [...this.held]) {\n if (!matches(held.type)) continue;\n const won = await this.tryClaim(toJobId(id));\n if (won) return won;\n }\n // Fallback: pending state whose delivery has not reached us — yet (a\n // claim racing ahead of its delivery) or ever (another dispatcher holds\n // it; KV is the authority, and that holder's reconcile settles the\n // stale lease once this claim concludes the job).\n for (const key of await this.allKeys()) {\n const envelope = await this.read(toJobId(key));\n if (!envelope || envelope.job.status !== 'pending' || !matches(envelope.job.metadata.type)) continue;\n const won = await this.tryClaim(toJobId(key));\n if (won) return won;\n }\n return { declined: 'none-available' };\n }\n\n /** CAS one pending job to running; null when someone else won it. */\n private async tryClaim(jobIdArg: JobId): Promise<{ job: AnyJob } | null> {\n return this.cas<{ job: AnyJob } | null>(\n jobIdArg,\n (job) => {\n if (job.status !== 'pending') return { result: null };\n const running: RunningJob<any, any> = {\n status: 'running',\n metadata: job.metadata,\n params: job.params,\n startedAt: new Date().toISOString(),\n progress: {},\n };\n return {\n envelope: { job: running, lastProgressAt: new Date().toISOString() },\n result: { job: running as AnyJob },\n };\n },\n null,\n );\n }\n\n async completeJob(jobIdArg: JobId, result: Record<string, unknown>): Promise<boolean> {\n const moved = await this.cas<boolean>(\n jobIdArg,\n (job) => {\n if (job.status !== 'running') return { result: false };\n const completed: CompleteJob<any, any> = {\n status: 'complete',\n metadata: job.metadata,\n params: job.params,\n startedAt: job.startedAt,\n completedAt: new Date().toISOString(),\n result,\n };\n return { envelope: { job: completed, lastProgressAt: new Date().toISOString() }, result: true };\n },\n false,\n );\n if (moved) this.settleLease(jobIdArg, 'ack');\n return moved;\n }\n\n async failJob(\n jobIdArg: JobId,\n error: string,\n completedUnits?: string[],\n failureClass?: 'transient' | 'deterministic',\n unitCursors?: Record<string, UnitCursor>,\n ): Promise<'retried' | 'failed' | null> {\n const outcome = await this.cas<'retried' | 'failed' | null>(\n jobIdArg,\n (job) => {\n if (job.status !== 'running') return { result: null };\n const units = [...new Set([...(job.metadata.completedUnits ?? []), ...(completedUnits ?? [])])];\n const cursors = mergeUnitCursors(job.metadata.unitCursors, unitCursors, units);\n const metadata = {\n ...job.metadata,\n ...(units.length > 0 ? { completedUnits: units } : {}),\n ...(Object.keys(cursors).length > 0 ? { unitCursors: cursors } : {}),\n };\n if ('unitCursors' in metadata && Object.keys(cursors).length === 0) delete (metadata as { unitCursors?: unknown }).unitCursors;\n\n if (willRetryAfter(job.metadata, failureClass)) {\n const retried: PendingJob<any> = {\n status: 'pending',\n metadata: { ...metadata, retryCount: job.metadata.retryCount + 1 },\n params: job.params,\n };\n return { envelope: { job: retried, lastProgressAt: new Date().toISOString() }, result: 'retried' as const };\n }\n const failed: FailedJob<any> = {\n status: 'failed',\n metadata,\n params: job.params,\n startedAt: job.startedAt,\n completedAt: new Date().toISOString(),\n error,\n };\n return { envelope: { job: failed, lastProgressAt: new Date().toISOString() }, result: 'failed' as const };\n },\n null,\n );\n\n if (outcome === 'retried') {\n // The nak'd (or republished) delivery arrives as a fresh pending job\n // and re-announces — retry IS redelivery under this driver.\n const held = this.held.get(jobIdArg as string);\n if (held) {\n this.held.delete(jobIdArg as string);\n held.m.nak();\n } else {\n const envelope = await this.read(jobIdArg);\n if (envelope) await this.js.publish(subjectFor(envelope.job), enc.encode(JSON.stringify({ jobId: jobIdArg })));\n }\n } else if (outcome === 'failed') {\n // Deterministic or exhausted: the message must never redeliver.\n this.settleLease(jobIdArg, 'term');\n }\n return outcome;\n }\n\n async checkpointUnits(jobIdArg: JobId, completedUnits: string[], unitCursors?: Record<string, UnitCursor>): Promise<void> {\n await this.cas<void>(\n jobIdArg,\n (job) => {\n if (job.status !== 'running') return { result: undefined };\n const units = [...new Set([...(job.metadata.completedUnits ?? []), ...completedUnits])];\n const cursors = mergeUnitCursors(job.metadata.unitCursors, unitCursors, units);\n const metadata = { ...job.metadata, completedUnits: units } as typeof job.metadata;\n if (Object.keys(cursors).length > 0) metadata.unitCursors = cursors;\n else delete (metadata as { unitCursors?: unknown }).unitCursors;\n const updated = { ...job, metadata } as AnyJob;\n // A checkpoint is progress — it refreshes the liveness clock.\n return { envelope: { job: updated, lastProgressAt: new Date().toISOString() }, result: undefined };\n },\n undefined,\n );\n }\n\n async recordProgress(jobIdArg: JobId, progress: Record<string, unknown>): Promise<void> {\n const last = this.lastProgressWrite.get(jobIdArg as string) ?? 0;\n if (Date.now() - last < PROGRESS_WRITE_MIN_INTERVAL_MS) return;\n this.lastProgressWrite.set(jobIdArg as string, Date.now());\n\n this.held.get(jobIdArg as string)?.m.working();\n await this.cas<void>(\n jobIdArg,\n (job) => {\n if (job.status !== 'running') return { result: undefined };\n const updated: RunningJob<any, any> = {\n status: 'running',\n metadata: job.metadata,\n params: job.params,\n startedAt: job.startedAt,\n progress,\n };\n return { envelope: { job: updated, lastProgressAt: new Date().toISOString() }, result: undefined };\n },\n undefined,\n );\n }\n\n async cancelPendingJobs(category: 'annotation' | 'generation'): Promise<number> {\n const matches = category === 'generation'\n ? (type: string) => type === 'generation'\n : (type: string) => type.endsWith('-annotation');\n\n let cancelled = 0;\n for (const key of await this.allKeys()) {\n const envelope = await this.read(toJobId(key));\n if (!envelope || envelope.job.status !== 'pending' || !matches(envelope.job.metadata.type)) continue;\n const done = await this.cas<boolean>(\n toJobId(key),\n (job) => {\n if (job.status !== 'pending' || !matches(job.metadata.type)) return { result: false };\n const record: CancelledJob<any> = {\n status: 'cancelled',\n metadata: job.metadata,\n params: job.params,\n startedAt: undefined,\n completedAt: new Date().toISOString(),\n };\n return { envelope: { job: record, lastProgressAt: new Date().toISOString() }, result: true };\n },\n false,\n );\n if (done) {\n cancelled++;\n this.settleLease(toJobId(key), 'term');\n }\n }\n // Undelivered messages for the category die with the state change.\n await this.jsm.streams.purge(STREAM, { filter: `${JOBS_SUBJECT_ROOT}.${category}.>` });\n return cancelled;\n }\n\n async cancelJob(jobIdArg: JobId): Promise<boolean> {\n const done = await this.cas<boolean>(\n jobIdArg,\n (job) => {\n if (job.status !== 'pending' && job.status !== 'running') return { result: false };\n const record: CancelledJob<any> = {\n status: 'cancelled',\n metadata: job.metadata,\n params: job.params,\n startedAt: job.status === 'running' ? job.startedAt : undefined,\n completedAt: new Date().toISOString(),\n };\n return { envelope: { job: record, lastProgressAt: new Date().toISOString() }, result: true };\n },\n false,\n );\n if (done) this.settleLease(jobIdArg, 'term');\n return done;\n }\n\n /**\n * Counts by status. The three terminal counts are the RETENTION WINDOW, not\n * lifetime totals — `pruneTerminalJobs` drops a record a day after it\n * concluded — so they answer \"recently finished\", never \"finished ever\".\n */\n async getStats(): Promise<{ pending: number; running: number; complete: number; failed: number; cancelled: number }> {\n const stats = { pending: 0, running: 0, complete: 0, failed: 0, cancelled: 0 };\n for (const key of await this.allKeys()) {\n const envelope = await this.read(toJobId(key));\n if (envelope) stats[envelope.job.status]++;\n }\n return stats;\n }\n\n /**\n * Worker-death recovery: the same contract the fs driver's mtime janitor\n * implemented — a running job with no progress inside the stale window is\n * retried or failed, checkpoint intact. Gateway-death recovery never comes\n * through here; that is AckWait redelivery.\n */\n async recoverStaleRunningJobs(): Promise<number> {\n const now = Date.now();\n let recovered = 0;\n for (const key of await this.allKeys()) {\n const envelope = await this.read(toJobId(key));\n if (!envelope || envelope.job.status !== 'running') continue;\n if (now - Date.parse(envelope.lastProgressAt) < this.staleRunningMs) continue;\n const outcome = await this.failJob(\n toJobId(key),\n `worker presumed dead — no progress within ${this.staleRunningMs / 60_000} minutes`,\n );\n if (outcome) {\n this.logger.warn('Recovered stale running job', { jobId: key, outcome });\n recovered++;\n }\n }\n return recovered;\n }\n\n /**\n * Terminal-job retention: the fs driver's hourly janitor, in this driver's\n * terms. Without it the bucket keeps every job it has ever seen, and\n * `getStats` — an OTel observable gauge, so a full bucket scan every metric\n * interval — pays for all of them forever. Measured on a live stack\n * 2026-09-24: 139 concluded records re-read every 30 seconds by a knowledge\n * base that had done very little work.\n *\n * A SWEEP AND NOT A BUCKET TTL, deliberately. `ttl` on `views.kv()` is a\n * BUCKET limit — the backing stream's `max_age` — so it expires every key\n * by age, not the terminal ones by status: a pending job nobody claimed for\n * a day, a running job whose worker went quiet, both evaporate alongside\n * the finished ones. That is not a slower version of this bug, it is a\n * worse one. This bucket is the AUTHORITATIVE record: with the entry gone\n * `read` returns null, every CAS falls through to its `onMissing`, and the\n * next delivery for that job is `term()`ed as unknown — the job disappears\n * with no failure and no trace. The rule retention needs to express is\n * about STATUS, and status is exactly what a bucket-wide clock cannot see.\n * (A per-message TTL set at the terminal write would express it, but that\n * is nats-server 2.11 plus a client that exposes it; nats.js 2.x does not.)\n *\n * Terminal is absorbing — no transition leaves `complete`/`failed`/\n * `cancelled` — so a record this sweep reads as expired cannot come back to\n * life under it, and the lease was settled at the transition that made it\n * terminal.\n */\n async pruneTerminalJobs(retentionMs: number): Promise<number> {\n const cutoff = Date.now() - retentionMs;\n let pruned = 0;\n for (const key of await this.allKeys()) {\n const envelope = await this.read(toJobId(key));\n if (!envelope) continue;\n const { job } = envelope;\n if (job.status !== 'complete' && job.status !== 'failed' && job.status !== 'cancelled') continue;\n if (Date.parse(job.completedAt) >= cutoff) continue;\n await this.jsm.streams.purge(BUCKET_STREAM, { filter: bucketSubject(key) });\n // The progress throttle outlives nothing: its entry is keyed by a job\n // that no longer exists.\n this.lastProgressWrite.delete(key);\n pruned++;\n }\n if (pruned > 0) {\n this.logger.info('Jobs cleaned up', { deletedCount: pruned });\n }\n return pruned;\n }\n\n /** The heartbeat body — extend live leases, settle concluded ones. */\n private async reconcileHeld(): Promise<void> {\n for (const [id, held] of [...this.held]) {\n const envelope = await this.read(toJobId(id));\n const status = envelope?.job.status;\n if (!envelope || status === 'complete' || status === 'failed' || status === 'cancelled') {\n this.held.delete(id);\n held.m.ack();\n } else {\n held.m.working();\n }\n }\n }\n\n /**\n * Materialize the KV key list BEFORE touching any entry: interleaving\n * `get`/`update` with an open `keys()` iterator on the same connection\n * makes the iterator drop entries (measured: the second pending job\n * vanished from every sweep until this was split into two passes).\n */\n private async allKeys(): Promise<string[]> {\n const keys: string[] = [];\n for await (const key of await this.kv.keys()) keys.push(key);\n return keys;\n }\n\n /** Conclude this process's lease on a job, if it holds one. */\n private settleLease(jobIdArg: JobId, how: 'ack' | 'term'): void {\n const held = this.held.get(jobIdArg as string);\n if (!held) return;\n this.held.delete(jobIdArg as string);\n if (how === 'ack') held.m.ack();\n else held.m.term();\n }\n}\n","/**\n * Job Queue Type Definitions - Discriminated Union Design\n *\n * Jobs represent async work that can be queued, processed, and monitored.\n * Uses TypeScript discriminated unions to enforce valid state transitions.\n *\n * Design principles:\n * - Each job status has specific valid fields\n * - Type narrowing works automatically via status discriminant\n * - No optional fields that may or may not exist\n * - State machine is explicit and type-safe\n */\n\nimport type { JobId, EntityType, ResourceId, UserId, GenerationJobParams, TagSchema, UnitCursor } from '@semiont/core';\nimport type { JobReferenceAnnotationResult, JobHighlightAnnotationResult, JobCommentAnnotationResult, JobAssessmentAnnotationResult, JobTagAnnotationResult } from '@semiont/core';\n\nexport type JobType = 'reference-annotation' | 'generation' | 'highlight-annotation' | 'assessment-annotation' | 'comment-annotation' | 'tag-annotation';\nexport type JobStatus = 'pending' | 'running' | 'complete' | 'failed' | 'cancelled';\n\n// ============================================================================\n// Core Metadata and Parameters\n// ============================================================================\n\n/**\n * Job metadata - common to all states\n */\nexport interface JobMetadata {\n id: JobId;\n type: JobType;\n /**\n * Who requested the job: the verified DID the gateway stamped on the\n * `job:create`, and the ONLY identity a job carries. The dispatcher\n * records it as the requester on `job:assigned`, which is what lets a\n * write citing this job be attributed — so nothing else about the\n * requester needs to travel with the job, or be trusted from it.\n */\n userId: UserId;\n created: string;\n retryCount: number;\n maxRetries: number;\n /**\n * Checkpointed resume (ABANDONED-INFERENCE P2, HD1): the entity-type\n * units whose annotations were fully emitted by earlier failed\n * attempts. Written only by `failJob`, unioned across attempts — and\n * because `failJob` rebuilds the retried record by spreading metadata,\n * the checkpoint survives every subsequent rebuild for free. A retried\n * claim skips these units, so completed work is neither redone nor\n * duplicated.\n */\n completedUnits?: string[];\n /**\n * The finer grain `completedUnits` cannot express (CHUNK-GRAIN-RESUME P2):\n * how far each UNFINISHED unit got, keyed by unit. Written per committed\n * chunk, so a job that dies mid-unit resumes there rather than at the top —\n * which for a one-unit job (every motivation job, and the 1958 document's\n * single `Person` type) is the difference between resuming and restarting.\n *\n * A unit here is in progress, never complete; the two sets are disjoint by\n * construction in `checkpointUnits`. Merged monotonically per unit, never\n * unioned — see `mergeUnitCursors`.\n */\n unitCursors?: Record<string, UnitCursor>;\n}\n\n/**\n * Locale conventions for detection/generation params.\n *\n * Two independent locales flow through these jobs:\n *\n * - `language` — *annotation body* locale. The BCP-47 tag the LLM should\n * write generated body text in (comment text, assessment text, generated\n * resource content, tag category label). Sourced from the user's UI\n * locale. Stamped onto the W3C `TextualBody.language` field.\n *\n * - `sourceLanguage` — *source resource* locale. The BCP-47 tag of the\n * content being analyzed. Sourced from `ResourceDescriptor` (carried as\n * `Representation.language` on the primary representation). Used in\n * prompts so the LLM analyzes non-English source correctly even when\n * the user's UI locale differs.\n *\n * Examples: a German user analyzing an English document → `language='de'`,\n * `sourceLanguage='en'`. An English user detecting entities in a French\n * document → `language='en'` (unused for entity references), `sourceLanguage='fr'`.\n */\n\n/**\n * Detection job parameters\n */\nexport interface DetectionParams {\n resourceId: ResourceId;\n entityTypes: EntityType[];\n includeDescriptiveReferences?: boolean;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n}\n\n\n/**\n * Highlight detection job parameters\n */\nexport interface HighlightDetectionParams {\n resourceId: ResourceId;\n instructions?: string;\n density?: number;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n}\n\n/**\n * Assessment detection job parameters\n */\nexport interface AssessmentDetectionParams {\n resourceId: ResourceId;\n instructions?: string;\n tone?: 'analytical' | 'critical' | 'balanced' | 'constructive';\n density?: number;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n}\n\n/**\n * Comment detection job parameters\n */\nexport interface CommentDetectionParams {\n resourceId: ResourceId;\n instructions?: string;\n tone?: 'scholarly' | 'explanatory' | 'conversational' | 'technical';\n density?: number;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n}\n\n/**\n * Tag detection job parameters.\n *\n * Carries the *full* `TagSchema` (not just an id). The dispatcher resolves\n * the caller-supplied `schemaId` against the per-KB tag-schema projection\n * at job-creation time and embeds the resolved schema here, keeping the\n * worker independent of the registry.\n */\nexport interface TagDetectionParams {\n resourceId: ResourceId;\n schema: TagSchema;\n categories: string[];\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n}\n\n// ============================================================================\n// Progress and Result Types\n// ============================================================================\n\n/**\n * Detection job progress\n */\nexport interface DetectionProgress {\n totalEntityTypes: number;\n processedEntityTypes: number;\n entitiesFound: number;\n entitiesEmitted: number;\n}\n\n\n/**\n * Generation job progress\n */\nexport interface YieldProgress {\n /** The two real generation transitions — LLM call running, then persisting. */\n stage: 'generating' | 'creating';\n percentage: number;\n message?: string;\n}\n\n/**\n * Generation job result\n */\nexport interface GenerationResult {\n kind: 'generation';\n resourceId: ResourceId;\n resourceName: string;\n /** True when the model stopped at the maxTokens ceiling — the artifact is cut off, not complete (GENERATE-FROM-RESOURCE D6). */\n truncated: boolean;\n}\n\n/**\n * Highlight detection job progress\n */\nexport interface HighlightDetectionProgress {\n stage: 'analyzing' | 'creating';\n percentage: number;\n message?: string;\n}\n\n\n/**\n * Assessment detection job progress\n */\nexport interface AssessmentDetectionProgress {\n stage: 'analyzing' | 'creating';\n percentage: number;\n message?: string;\n}\n\n\n/**\n * Comment detection job progress\n */\nexport interface CommentDetectionProgress {\n stage: 'analyzing' | 'creating';\n percentage: number;\n message?: string;\n}\n\n\n/**\n * Tag detection job progress\n */\nexport interface TagDetectionProgress {\n stage: 'analyzing' | 'creating';\n percentage: number;\n currentCategory?: string;\n processedCategories: number;\n totalCategories: number;\n message?: string;\n}\n\n\n// ============================================================================\n// Generic Job State Types\n// ============================================================================\n\n/**\n * Pending job - just created, waiting to be picked up\n */\nexport interface PendingJob<P> {\n status: 'pending';\n metadata: JobMetadata;\n params: P;\n}\n\n/**\n * Running job - actively being processed\n */\nexport interface RunningJob<P, PG> {\n status: 'running';\n metadata: JobMetadata;\n params: P;\n startedAt: string;\n progress: PG;\n}\n\n/**\n * Complete job - successfully finished\n */\nexport interface CompleteJob<P, R> {\n status: 'complete';\n metadata: JobMetadata;\n params: P;\n startedAt: string;\n completedAt: string;\n result: R;\n}\n\n/**\n * Failed job - encountered an error\n */\nexport interface FailedJob<P> {\n status: 'failed';\n metadata: JobMetadata;\n params: P;\n startedAt?: string;\n completedAt: string;\n error: string;\n}\n\n/**\n * Cancelled job - stopped by user\n */\nexport interface CancelledJob<P> {\n status: 'cancelled';\n metadata: JobMetadata;\n params: P;\n startedAt?: string;\n completedAt: string;\n}\n\n/**\n * Generic job - discriminated union of all states\n */\nexport type Job<P, PG, R> =\n | PendingJob<P>\n | RunningJob<P, PG>\n | CompleteJob<P, R>\n | FailedJob<P>\n | CancelledJob<P>;\n\n// ============================================================================\n// Concrete Job Types\n// ============================================================================\n\nexport type DetectionJob = Job<DetectionParams, DetectionProgress, JobReferenceAnnotationResult>;\nexport type GenerationJob = Job<GenerationJobParams, YieldProgress, GenerationResult>;\nexport type HighlightDetectionJob = Job<HighlightDetectionParams, HighlightDetectionProgress, JobHighlightAnnotationResult>;\nexport type AssessmentDetectionJob = Job<AssessmentDetectionParams, AssessmentDetectionProgress, JobAssessmentAnnotationResult>;\nexport type CommentDetectionJob = Job<CommentDetectionParams, CommentDetectionProgress, JobCommentAnnotationResult>;\nexport type TagDetectionJob = Job<TagDetectionParams, TagDetectionProgress, JobTagAnnotationResult>;\n\n/**\n * Discriminated union of all job types\n */\nexport type AnyJob = DetectionJob | GenerationJob | HighlightDetectionJob | AssessmentDetectionJob | CommentDetectionJob | TagDetectionJob;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\nconst JOB_TYPES: ReadonlySet<string> = new Set<JobType>([\n 'reference-annotation',\n 'generation',\n 'highlight-annotation',\n 'assessment-annotation',\n 'comment-annotation',\n 'tag-annotation',\n]);\n\n/**\n * Narrow a job type arriving off the bus, where it is only `string`.\n *\n * Worth checking rather than asserting: `jobType` is a required, enumerated\n * field on every job lifecycle command, so an unrecognized value produces a\n * payload the gateway will reject — better caught at the worker with a clear\n * error than as an opaque emit failure.\n */\nexport function isJobType(value: string): value is JobType {\n return JOB_TYPES.has(value);\n}\n\n/**\n * Narrow bus-delivered job params to the shape a processor expects.\n *\n * Job params cross the bus as `Record<string, unknown>`. Every params type in\n * this file requires exactly one field — `resourceId` — with the rest\n * optional, so that is what gets verified; absent optionals are legitimately\n * absent, not a validation failure. Callers pass the params type for the job\n * they have already branched on.\n */\nexport function asJobParams<T extends { resourceId: ResourceId }>(\n params: Record<string, unknown>,\n): T {\n if (typeof params.resourceId !== 'string') {\n throw new Error('Job params are missing a resourceId');\n }\n return params as unknown as T;\n}\n\n// Generation params are deliberately NOT covered: generation is the one job\n// that does not read a source resource (it mints one), so it requires no\n// `resourceId` and there is nothing to verify.\n\nexport function isPendingJob(job: AnyJob): job is PendingJob<any> {\n return job.status === 'pending';\n}\n\nexport function isRunningJob(job: AnyJob): job is RunningJob<any, any> {\n return job.status === 'running';\n}\n\nexport function isCompleteJob(job: AnyJob): job is CompleteJob<any, any> {\n return job.status === 'complete';\n}\n\nexport function isFailedJob(job: AnyJob): job is FailedJob<any> {\n return job.status === 'failed';\n}\n\nexport function isCancelledJob(job: AnyJob): job is CancelledJob<any> {\n return job.status === 'cancelled';\n}\n\n// ============================================================================\n// Job Query Types\n// ============================================================================\n\nexport interface JobQueryFilters {\n status?: JobStatus;\n type?: JobType;\n userId?: UserId;\n limit?: number;\n offset?: number;\n}\n\n","/**\n * Bounded inference calls — WORKER-LIVENESS.md P2 (G1: prevention).\n *\n * The claim loop's only unbounded await is the model call: bus\n * operations gained transport timeouts in 0.5.6, the inference HTTP\n * request did not. One request that never settles used to wedge the\n * worker forever — the adapter ignores announcements while\n * `isProcessing`, so a single stuck call silenced the whole agent.\n * Bounding the call converts that silent hang into an ordinary job\n * failure that flows through the existing `job:fail` path (and the\n * gateway's retry budget — a timeout is transient-shaped, so retrying\n * is correct) and frees the claim loop.\n *\n * This is a timeout AND a cancellation (ABANDONED-INFERENCE P1): on expiry\n * the bound aborts the underlying request through the `InferenceClient`\n * signal, so the transport — and, on the Anthropic path, the SDK's internal\n * retry loop — is torn down rather than left running as a billed zombie\n * (P0 caught one completing 24–34 minutes after its job was gone). The\n * timeout stays as the last line either way, exactly as before; the abort is\n * the addition, not the replacement (D1). The eventual settlement of the\n * aborted promise is still swallowed so it cannot surface as an unhandled\n * rejection.\n */\n\nimport type { ElementSchema, InferenceClient, InferenceResponse, StructuredResponse } from '@semiont/inference';\nimport type { Logger } from '@semiont/core';\nimport { withSpan } from '@semiont/observability';\n\n/**\n * Generous single-call bound. Slow local models on large prompts run\n * minutes, not tens of minutes; the stall watchdog (P3) sits above\n * this at 15 minutes, and the gateway's dead-worker janitor above\n * that at 30. Fixed by design — no env knob.\n */\nexport const INFERENCE_TIMEOUT_MS = 10 * 60_000;\n\n/**\n * The bound's own rejection, typed so classification (ABANDONED-INFERENCE\n * P3) never string-matches our own error message. A timeout says nothing\n * about the request — it classifies transient.\n */\nexport class InferenceTimeoutError extends Error {\n override readonly name = 'InferenceTimeoutError';\n}\n\n/**\n * How often an in-flight call reports that it is still alive\n * (DETECTION-HEARTBEAT D2).\n *\n * Detection's other liveness signal — the chunk-boundary heartbeat — emits\n * `N − 1` events for `N` chunks, which is ZERO for the single-chunk case that\n * every realistic document falls into (the derived input budget is ~935 K\n * tokens). A 7-minute call then emits nothing at all, and the client's\n * *inter-emission* timeout (`mark-state-unit`, 180 s) kills a perfectly\n * healthy job.\n *\n * Sized against that consumer: 15 s gives ~12 beats of margin inside the\n * 180 s window. Fixed by design, like the bound above — no env knob.\n */\nexport const INFERENCE_HEARTBEAT_MS = 15_000;\n\n/**\n * Called while a provider call is still in flight. Liveness only — the\n * caller repeats its current stage rather than inventing an advancing\n * percentage (D3): nothing here knows how far a single model call has got.\n */\nexport type InferenceHeartbeat = () => void;\n\n/**\n * One span per provider call. Before this, a 411-second detection job was a\n * SINGLE span with no children on a fully instrumented stack — it was not\n * possible to tell extraction from inference from telemetry, which is what\n * made the sibling silent-empty bug expensive to find. Attributes stay to\n * what is known before the answer arrives; token counts are recorded by\n * `recordInferenceUsage` in the client.\n */\nfunction spanned<T>(client: InferenceClient, kind: string, maxTokens: number, work: () => Promise<T>): Promise<T> {\n return withSpan(`inference:${kind}`, work, {\n attrs: {\n 'inference.provider': client.type,\n 'inference.model': client.modelId,\n 'inference.max_tokens': maxTokens,\n },\n });\n}\n\nasync function withTimeout<T>(\n work: (signal: AbortSignal) => Promise<T>,\n meta: { provider: string; model: string; label: string },\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<T> {\n const controller = new AbortController();\n let timer!: ReturnType<typeof setTimeout>;\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // True cancellation: tear the request down at the transport so it\n // cannot keep running (and billing) against a job that no longer\n // exists — and name the abort in the log, because an invisible\n // abandonment is what let a zombie burn 24+ minutes unrecorded (D3).\n logger?.warn('Aborting in-flight inference call at the timeout bound', {\n provider: meta.provider,\n model: meta.model,\n label: meta.label,\n boundMs: INFERENCE_TIMEOUT_MS,\n });\n controller.abort();\n reject(new InferenceTimeoutError(\n `Inference call timed out after ${INFERENCE_TIMEOUT_MS / 60_000} minutes (${meta.label}) — failing the job to keep the claim loop live`,\n ));\n }, INFERENCE_TIMEOUT_MS);\n timer.unref?.();\n });\n\n // One timer at one site covers every provider call, present and future —\n // putting it in the detection loops instead would re-couple liveness to\n // detection's own structure, which is the coupling this exists to undo.\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n if (onHeartbeat) {\n heartbeat = setInterval(() => {\n try {\n onHeartbeat();\n } catch {\n // A failing progress emit must never take down the inference call\n // it is merely reporting on.\n }\n }, INFERENCE_HEARTBEAT_MS);\n heartbeat.unref?.();\n }\n\n const pending = work(controller.signal);\n try {\n return await Promise.race([pending, timedOut]);\n } catch (err) {\n // The aborted call settles promptly now (AbortError from the transport)\n // rather than minutes later — but its rejection still lands after the\n // race is lost, so it is still swallowed here to keep it from surfacing\n // as an unhandled one and killing the process.\n pending.catch(() => {});\n throw err;\n } finally {\n clearTimeout(timer);\n // Cleared with the timeout, in the same finally: a leaked interval would\n // beat forever on a completed job.\n if (heartbeat) clearInterval(heartbeat);\n }\n}\n\nexport function boundedGenerateWithMetadata(\n client: InferenceClient,\n prompt: string,\n maxTokens: number,\n temperature: number,\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<InferenceResponse> {\n return spanned(client, 'text', maxTokens, () => withTimeout(\n (signal) => client.generateTextWithMetadata(prompt, maxTokens, temperature, signal),\n { provider: client.type, model: client.modelId, label: `${client.type}:${client.modelId}` },\n onHeartbeat,\n logger,\n ));\n}\n\nexport function boundedGenerateStructured<T>(\n client: InferenceClient,\n prompt: string,\n maxTokens: number,\n temperature: number,\n elementSchema: ElementSchema,\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<StructuredResponse<T>> {\n return spanned(client, 'structured', maxTokens, () => withTimeout(\n (signal) => client.generateStructured<T>(prompt, maxTokens, temperature, elementSchema, signal),\n { provider: client.type, model: client.modelId, label: `${client.type}:${client.modelId}` },\n onHeartbeat,\n logger,\n ));\n}\n","/**\n * Failure classification — ABANDONED-INFERENCE P3 (A4, HD2).\n *\n * A retried deterministic failure always costs exactly double: the second\n * attempt of the same request cannot succeed. HD2's ruling is one-sided —\n * only KNOWN-deterministic failures skip the retry budget; everything\n * unrecognized stays retryable (`undefined`), because mis-classifying a\n * transient failure as deterministic silently halves reliability, while the\n * reverse merely costs one wasted attempt (today's behavior).\n *\n * Classification happens HERE, in the worker, where errors are still typed —\n * at the gateway's `job:fail` handler the failure is already a flattened\n * string, and message-regex classification is the drift this module exists\n * to avoid. The class rides the `job:fail` payload; `failJob` consumes it.\n */\n\nimport { isNumber, isObject, isString, RETRY_RULES, type components } from '@semiont/core';\nimport { StructuredReadError } from '@semiont/inference';\nimport { InferenceTimeoutError } from './workers/inference-call';\n\n/** Derived from the spec, not restated: the wire owns this vocabulary\n * (`FailureClass.json`, referenced by job:fail and job:failed alike). */\nexport type FailureClass = components['schemas']['FailureClass'];\n\n/**\n * Marker for failures WE know cannot succeed on a second identical attempt —\n * thrown at the sites that judge the work itself rather than the transport:\n * response truncation despite the derived budget, a media type with nothing\n * to extract. Throw it instead of `Error` wherever that knowledge exists.\n */\nexport class DeterministicJobError extends Error {\n // Typed string, not the literal: subclasses (YieldCollapseError) carry\n // their own name — classification is instanceof, never name-matching.\n override readonly name: string = 'DeterministicJobError';\n}\n\n/**\n * The taxonomy, and its provider coupling — THE part that will drift:\n *\n * - `@anthropic-ai/sdk` errors carry a numeric `status`, and WHICH statuses are\n * worth another attempt is not decided here: it is `RETRY_RULES.job`\n * (RETRY-CLASSIFICATION P2). This file used to restate the same three\n * conditions, which made it a second opinion on a question core already\n * answered — and the census that found it showed that where a bare list and a\n * reasoned rule disagree, the list wins silently. The rule carries the\n * reasoning; this file carries the ONE thing the rule cannot know: that\n * anything else at or above 400 is a rejected request, and re-sending it\n * unchanged is guaranteed waste → deterministic.\n * - Aborts (`APIUserAbortError` from the SDK, `AbortError` from fetch/mock)\n * are our own bound or shutdown tearing the transport down — nothing was\n * judged → transient.\n * - Ollama surfaces plain `Error`s (no status) and network failures as\n * `TypeError: fetch failed`; the SDK's `MessageStream terminated` is a\n * dropped connection. All land `undefined` → retryable, the safe default.\n * - `@semiont/inference`'s `StructuredReadError` carries the stop reason\n * because the cause classifies differently: `max_tokens` is truncation of\n * an over-demanded answer — the adapter throws before the caller's\n * `assertNotTruncated` can see the stop reason, so the classification\n * must happen on the typed error itself (measured live 2026-09-02) —\n * while any other reason is model misbehavior a retry may fix.\n */\nexport function classifyFailure(error: unknown): FailureClass | undefined {\n if (error instanceof DeterministicJobError) return 'deterministic';\n if (error instanceof InferenceTimeoutError) return 'transient';\n if (error instanceof StructuredReadError && error.stopReason === 'max_tokens') return 'deterministic';\n // A `StructuredReadError` with any OTHER stop reason falls through to\n // `undefined` — retryable, and DECIDED rather than defaulted\n // (RETRY-CLASSIFICATION P2, 2026-09-12).\n //\n // It only reaches here having exhausted `MAX_SUBDIVISION_DEPTH`, so\n // `subdividable()` has already argued the opposite: at\n // `DETECTION_TEMPERATURE` 0 the identical call returns the identical failure.\n // That argument was decisive while chunk boundaries were fixed up front. It is\n // not any more — CHUNK-GRAIN-RESUME HD2 (option C) seeds a resumed unit's size\n // from the checkpoint and then takes one shrink step, so the retry re-cuts the\n // poison piece at a DIFFERENT size and can genuinely come out differently. The\n // price of being wrong fell with it: one chunk, not the whole prefix.\n //\n // It stays `undefined` rather than becoming `'transient'` on purpose. The wire\n // vocabulary has two values, and this is neither: it is not weather, it is\n // \"retryable because the next attempt reads different input\". Claiming\n // `transient` would assert an environmental cause nobody established, and\n // absent already means exactly what is true — unrecognised, so retryable.\n if (!isObject(error)) return undefined;\n\n const name = isString(error.name) ? error.name : '';\n if (name === 'DeterministicJobError') return 'deterministic';\n if (name === 'APIUserAbortError' || name === 'AbortError') return 'transient';\n\n const status = isNumber(error.status) ? error.status : undefined;\n if (status !== undefined) {\n if (RETRY_RULES.job.retryable({ status })) return 'transient';\n if (status >= 400) return 'deterministic';\n }\n\n return undefined;\n}\n","/**\n * Adaptive chunk sizing (DETECTION-QUALITY-THROUGHPUT P2) — the sizing RULE.\n *\n * `deriveDetectionBudget` picks ONE input size for every document from provider\n * limits alone. It cannot see the document, so it is sized for a worst-case\n * dense one (input = half the output budget) — and a sparse document then pays\n * that pessimism as many tiny, overhead-dominated calls. This adjusts the chunk\n * size AS THE UNIT RUNS, from what each call actually produced, so a document\n * that turns out sparse grows into bigger chunks and a dense stretch pulls back.\n *\n * It steers ONE number: how full of the output budget each chunk came in. That\n * is the whole model, and it is enough because both hard failures are already\n * caught downstream by `callChunkSubdividing` — a chunk that truncates is\n * halved-and-retried, a chunk that outruns the guillotine times out and is\n * halved-and-retried. So the sizer does not model truncation or duration; it\n * only keeps chunks in a band that uses the budget well, and the net below it\n * forgives an overshoot. `bounds.ceiling` is therefore the WINDOW fit, not either\n * derived input size: on a shared window both of those come back at exactly the\n * density guess this function exists to replace, leaving nothing to grow into. That safety net is why this is a step rule and not a\n * control loop (user direction, 2026-09-04: keep it simple).\n *\n * \"Maximize, don't predict\": the only thing that grows a chunk is a MEASURED\n * under-use of the budget. No document statistic, no a-priori density model\n * (#1121's ban). Re-evaluated every chunk, so it tracks a gradient (sparse\n * intro → dense index) rather than betting the run on the first sample.\n *\n * Pure and feedback-only — unit-testable in isolation. The loop that applies it is\n * `runAdaptiveChunks` in `detection-chunking.ts`, which both detection paths drive:\n * `extractEntities` (reference) and `detectInChunks` (highlight, comment, assessment,\n * tag). It cuts chunk N+1 only after chunk N has reported, which is the only ordering\n * in which this function's output can reach anything.\n */\n\n/** What one chunk's call produced — the minimum the sizer needs. Duration and\n * input are NOT here: the guillotine and truncation are the hard bounds, both\n * backstopped by subdivision, so utilization is the only signal that sizing\n * acts on. (P1 telemetry records the fuller picture separately.) */\nexport interface CallOutcome {\n /** Provider-reported output tokens for the chunk, ABSENT when the provider\n * reported none.\n *\n * Absent is not zero. `usage` is optional on the inference interface and both\n * real clients emit it conditionally, so a run against a provider that stays\n * silent would read as \"this chunk produced nothing\", i.e. 0%% of the budget,\n * i.e. grow — every chunk, to the ceiling, on no evidence whatsoever. That is\n * the precise inverse of \"maximize, don't predict\". Unmeasured holds. */\n outputTokens?: number;\n /** The chunk hit a size-shaped bound (truncation or the guillotine), even if\n * subdivision then recovered it. Forces a shrink regardless of the count —\n * the signal that the last size was too big for this stretch. */\n truncated: boolean;\n}\n\n/** Provider-DERIVED sizing bounds for one job — not tuning, not policy. From\n * `deriveDetectionBudget` and the model's window; recomputed per job, never\n * user-facing. */\nexport interface SizingBounds {\n /** Smallest useful input chunk (tokens) — the overlap-derived floor. */\n floor: number;\n /** Largest input chunk (tokens) — the window-fit safety cap; never exceeded. */\n ceiling: number;\n /** The output budget one call is given. Utilization is measured against it. */\n outputBudget: number;\n}\n\n/**\n * The tuning knobs — the numbers that decide how aggressively chunk size chases\n * measured output usage. Grouped and named deliberately, because these are\n * POLICY, not derivation, and the likely future is that they become\n * user/admin-tunable, perhaps per inference provider (a fast, cheap model\n * tolerates more aggressive growth than a slow, dear one).\n *\n * That future changes where a `ChunkSizingPolicy` comes FROM — provider config,\n * a settings surface — not the sizing function, which already takes it as a\n * value, nor the caller's shape. There is exactly ONE today, the default below.\n * No config system, no env var, no per-provider map yet: just a single named\n * home, so when the need is real there is one obvious thing to make configurable\n * and one obvious place to select it (the caller holds the `InferenceClient`,\n * hence the provider).\n */\nexport interface ChunkSizingPolicy {\n /** Below this fraction of the output budget, the chunk left room — grow. */\n growBelow: number;\n /** Above this fraction, the chunk is near the edge — ease off before it\n * truncates and costs a subdivision retry. */\n shrinkAbove: number;\n /** Geometric step when growing (>1). Geometric so a genuinely sparse document\n * reaches its ceiling in a few steps and a bad step costs one correction. */\n growFactor: number;\n /** Geometric step when easing off (<1). Also the response to a truncation. */\n shrinkFactor: number;\n}\n\n/** The one policy in effect today. Coarse on purpose — subdivision forgives a\n * wrong guess — and every value is a candidate for the tunable surface above. */\nexport const DEFAULT_CHUNK_SIZING_POLICY: ChunkSizingPolicy = {\n growBelow: 0.5,\n shrinkAbove: 0.8,\n growFactor: 1.5,\n shrinkFactor: 0.7,\n};\n\nfunction clamp(value: number, lo: number, hi: number): number {\n return Math.max(lo, Math.min(hi, value));\n}\n\n/**\n * Propose the next chunk's input size from what the last chunk produced.\n *\n * A truncated chunk, or one whose output filled more than `shrinkAbove` of the\n * budget, eases the next chunk down; one that used less than `growBelow` grows\n * it; in between — or with nothing measured at all — hold. Always clamped to `[floor, ceiling]`. That is the whole\n * rule — the hard bounds are subdivision's job, not this function's.\n */\nexport function nextChunkSize(\n outcome: CallOutcome,\n current: number,\n bounds: SizingBounds,\n policy: ChunkSizingPolicy = DEFAULT_CHUNK_SIZING_POLICY,\n): number {\n const grow = () => clamp(Math.floor(current * policy.growFactor), bounds.floor, bounds.ceiling);\n const shrink = () => clamp(Math.floor(current * policy.shrinkFactor), bounds.floor, bounds.ceiling);\n const hold = () => clamp(current, bounds.floor, bounds.ceiling);\n\n if (outcome.truncated) return shrink();\n // No measurement, no move. A truncation above is evidence even without a\n // count; an absent count on its own is not.\n if (outcome.outputTokens === undefined) return hold();\n // A zero/absent budget cannot inform utilization; hold rather than divide by\n // zero or grow blindly.\n if (bounds.outputBudget <= 0) return hold();\n\n const utilization = outcome.outputTokens / bounds.outputBudget;\n if (utilization < policy.growBelow) return grow();\n if (utilization > policy.shrinkAbove) return shrink();\n return hold();\n}\n","/**\n * Detection budget derivation — pure window arithmetic over the inference\n * provider's published limits. No hand-tuned chunk constants, no density or\n * yield modeling: document content never enters this arithmetic. The guard\n * for the pathological tail (a chunk whose annotation JSON still overflows\n * the output budget) is `assertNotTruncated` below — invoked per chunk by\n * the callers on every response, not a prediction here.\n *\n * Provider shapes (see `@semiont/inference` interface.ts):\n * - Shared window (Ollama): the provider publishes\n * `maxOutputTokens === contextTokens` — prompt and response share one\n * `num_ctx`. What remains after the prompt scaffold is split\n * input:output = 1:2 (annotation JSON echoes each span plus a fixed\n * key/context envelope, so output needs the larger share). The 1:2 ratio\n * is the plan's one allocation policy — doc-independent, tuned only on\n * live evidence.\n * - Separate ceilings (Anthropic): output takes its full ceiling (duration-\n * capped below), and input follows the same 1:2 allocation — never more\n * than half the output budget. Input does NOT get \"the rest of the\n * window\": measured 2026-09-02, a window-sized chunk of entity-dense text\n * demands more output than any budget holds, so the model grinds toward\n * max_tokens for minutes (killed at the call bound as a \"stall\") or\n * collapses to the degenerate []. Large documents chunk; that is the fix,\n * not a cost.\n */\n\nimport { chunkText, cutChunk, type ChunkingConfig, type Logger, type UnitCursor } from '@semiont/core';\nimport { StructuredReadError, type InferenceLimits, type TokenUsage } from '@semiont/inference';\nimport { recordDetectionCall } from '@semiont/observability';\nimport { DeterministicJobError } from '../../failure-class';\nimport { INFERENCE_TIMEOUT_MS, InferenceTimeoutError } from '../inference-call';\nimport { nextChunkSize, type CallOutcome, type SizingBounds } from './chunk-size-controller';\n\n/**\n * A `max_tokens` stop reason means the model's JSON was cut off mid-stream.\n * Structured output serializes whatever was generated, so that still yields\n * a syntactically-valid but incomplete array — it would parse cleanly and\n * silently under-report. Fail the job loudly instead. With derived budgets\n * this fires only on pathological annotation density.\n *\n * ONE decider for every detection path (entity extraction and the four\n * motivations) — the classification must not diverge between them: same\n * input truncates the same way, so a retry is guaranteed waste and the\n * throw carries the deterministic class (ABANDONED-INFERENCE P3, A4).\n */\nexport function assertNotTruncated(response: { stopReason: string }, label: string, at: number, totalChars: number, outputBudget: number): void {\n if (response.stopReason === 'max_tokens') {\n throw new DeterministicJobError(`${label} response truncated (max_tokens) at character ${at} of ${totalChars} despite the derived output budget of ${outputBudget} tokens — failing the job rather than under-reporting annotations.`);\n }\n}\n\n/**\n * `reconcileSelector` disambiguates a span with up to 64 chars of prefix and\n * 64 of suffix (the annotation-selector schema). Overlap must let a span\n * sitting at a chunk boundary carry that context — plus a span allowance of\n * the same order — into the adjacent chunk. Schema-derived, not tuned.\n */\nconst SELECTOR_CONTEXT_CHARS = 64;\nconst OVERLAP_CHARS =\n SELECTOR_CONTEXT_CHARS + // prefix\n SELECTOR_CONTEXT_CHARS + // suffix\n 2 * SELECTOR_CONTEXT_CHARS; // span allowance\n/** ~4 chars/token — the same heuristic `estimateTokens`/`chunkText` use. */\nconst OVERLAP_TOKENS = Math.ceil(OVERLAP_CHARS / 4);\n\n/**\n * One temperature for every detection call. Detection copies spans verbatim\n * against a closed type vocabulary — a fidelity task, so determinism is the\n * right default (reproducible re-runs). Measured equal to hotter settings\n * on yield and consistency at production call sizes.\n */\nexport const DETECTION_TEMPERATURE = 0;\n\n/**\n * Assumed worst-case output rate for providers that publish none\n * (OLLAMA-DETECTION-TESTING P3b, from F9). Rate-silent providers (Ollama —\n * local hardware, rate unknowable a priori) previously got NO duration bound:\n * capacity-sizing handed a 262K-window model a ~174K-token output budget, and\n * a repetition loop then burned the full 10-minute guillotine as TRANSIENT —\n * retried identically. Under a duration-shaped cap the same loop dies in\n * minutes as max_tokens → deterministic → subdividable: the useful failure.\n *\n * 30 tok/s. P2 measured 36–90 tok/s across three local model families\n * (qwen3.5:9b ~36, gemma4:26b ~50, gemma4:e2b ~90), and the half-bound rule\n * in the cap below means real rates down to 15 tok/s still finish inside the\n * guillotine — anything slower is wedged, not working, which is exactly what\n * the guillotine is for. A conservative floor, deliberately NOT per-model:\n * F8 showed per-model thresholds chase noise. Owned policy constant, same\n * status as the 1:2 split and DETECTION_TEMPERATURE.\n */\nexport const ASSUMED_OUTPUT_TOKENS_PER_HOUR = 108_000;\n\n/**\n * The count-verifier band (OLLAMA-DETECTION-TESTING P3c, user-ratified\n * 2026-09-05): an extraction that found fewer than 1/BAND of the mentions a\n * cheap count call reports is flagged as silent yield collapse (F7). The band\n * is LOAD-BEARING at 2: F12 measured the same model flipping between\n * entity-like and mention-like enumeration on the same corpus, and that\n * legitimate judgment spread must fit INSIDE the band — probe evidence (n=6)\n * put every healthy ratio at 0.68–0.88 and every collapse at 0.18–0.41.\n */\nexport const YIELD_COLLAPSE_BAND = 2;\n\n/**\n * The silent-yield-collapse verdict (F7): a schema-clean, done-reason-clean\n * extraction that found a fraction of what a cheap count call says is present.\n * Extends DeterministicJobError because the collapse is MEASURED deterministic\n * — bit-identical across retries and across budget regimes — so a retry is\n * guaranteed waste; the classification and the size-floored subdivision\n * descent both follow from the base class. It diverges from truncation at the\n * size floor: NO re-roll (a same-size re-roll provably returns the identical\n * collapse), and — ruled 2026-09-05 after P4 attempt 1, amending the original\n * fail-the-job invariant — the floor ACCEPTS the flagged piece's `salvage`\n * loudly rather than failing the unit: one hostile ~530-char stretch had\n * discarded ~20 chunks of good extraction, and at floor sizes the count's\n * evidence sits far below anything the probe validated. The warning and the\n * 'collapsed' telemetry rows are the durable record; re-detection heals.\n */\n/** A floor-accepted piece's evidence: what extraction found against what a\n * count call reported, over a piece of this size. Facts only — never a\n * judgment against an expected yield. */\nexport interface UnderReportedPiece {\n found: number;\n counted: number;\n pieceChars: number;\n}\n\nexport class YieldCollapseError extends DeterministicJobError {\n override readonly name = 'YieldCollapseError';\n /** What the flagged extraction DID find — every span write-time-verified,\n * so discarding it at the floor would add loss on top of the under-report.\n * Carried on the error because the flag site cannot know whether descent\n * remains possible; the floor is the subdivider's knowledge. The verdict\n * rides beside it so an acceptance can report evidence, not a message\n * string. */\n constructor(message: string, readonly salvage: unknown[], readonly verdict: UnderReportedPiece) {\n super(message);\n }\n}\n\nexport interface DetectionBudget {\n /** The chunk size a run OPENS at (tokens), plus the overlap every cut keeps.\n * Opening, not fixed: `runAdaptiveChunks` moves the size within `bounds` as\n * the document reports what it actually costs. */\n chunking: ChunkingConfig;\n /** Pass as `maxTokens` on every per-chunk inference call. */\n outputBudget: number;\n /** How far the sizer may move the chunk size, in either direction. Derived\n * from the same provider arithmetic — never tuning. */\n bounds: SizingBounds;\n}\n\n/**\n * Derive the per-call input/output token budgets for a detection job from the\n * provider's actual limits and the measured prompt scaffold.\n *\n * @param limits - the provider's published ceilings (`client.limits()`)\n * @param scaffoldTokens - tokens of the prompt template around the content,\n * measured from the actually-built template (e.g. `estimateTokens(build(''))`)\n * @param typesPerCall - how many entity types (or equivalent span families)\n * ONE call asks for: output demand scales with it, so the allocation\n * divides by it. The per-type loop passes 1; a future multi-type batch\n * passes its batch size.\n * @throws when the window is too small to hold the scaffold plus a useful\n * chunk — fail-loud, same family as the truncation and window guards.\n */\nexport function deriveDetectionBudget(\n limits: InferenceLimits,\n scaffoldTokens: number,\n typesPerCall: number,\n): DetectionBudget {\n const { contextTokens, maxOutputTokens } = limits;\n const available = contextTokens - scaffoldTokens;\n\n let inputBudget: number;\n let outputBudget: number;\n\n if (maxOutputTokens >= contextTokens) {\n // Shared window: 1:2 input:output split of what the scaffold leaves.\n inputBudget = Math.floor(available / 3);\n outputBudget = available - inputBudget;\n } else {\n outputBudget = maxOutputTokens;\n inputBudget = contextTokens - outputBudget - scaffoldTokens;\n if (inputBudget <= 0) {\n // Degenerate separate-ceilings shape (output ceiling nearly fills the\n // window): fall back to the shared split rather than starving input.\n inputBudget = Math.floor(available / 3);\n outputBudget = available - inputBudget;\n }\n }\n\n // Duration floor (ABANDONED-INFERENCE P4 HD3; universalized by\n // OLLAMA-DETECTION-TESTING P3b): cap each call's output at what the\n // provider's worst-case rate finishes inside our own inference bound — a\n // call projected past the 10-minute guillotine is planned-to-fail — and\n // scale input by the same factor, so the input:output ratio (and with it\n // the per-chunk truncation risk profile) is exactly the capacity\n // solution's. Capacity says what CAN fit in one call; this says what\n // SHOULD. EVERY provider gets the bound: the published rate when there is\n // one, the conservative assumed floor when there is not — a rate-silent\n // provider with no bound turned repetition loops into hour-long transient\n // burns (F9; see ASSUMED_OUTPUT_TOKENS_PER_HOUR). It is a floor on chunk\n // count, never a raise (a tighter capacity budget is left alone). Side\n // effect worth knowing: on Anthropic this lands every detection call at\n // or under the SDK's non-streaming threshold — off the MessageStream path\n // the original `terminated` failure arrived on.\n const outputTokensPerHour = limits.outputTokensPerHour ?? ASSUMED_OUTPUT_TOKENS_PER_HOUR;\n {\n // Half the bound, not all of it: at the full bound the slowest\n // legitimate full-budget generation lands exactly on the guillotine.\n // At half, the guillotine fires only on calls at least 2× slower than\n // the provider's own worst-case model — wedged, not working.\n const durationSafeOutput = Math.floor(outputTokensPerHour * (INFERENCE_TIMEOUT_MS / 2) / 3_600_000);\n if (outputBudget > durationSafeOutput) {\n inputBudget = Math.floor(inputBudget * (durationSafeOutput / outputBudget));\n outputBudget = durationSafeOutput;\n }\n }\n\n // The 1:2 allocation policy, applied to every provider shape (the shared\n // split satisfies it by construction; separate ceilings did not). Output\n // must hold an annotation echo of every span in the chunk plus its\n // key/context envelope, so a chunk larger than half the output budget is\n // a call whose honest answer cannot fit — the failure measured live on\n // 2026-09-02 (silent multi-minute grinds to max_tokens, degenerate []).\n // The demand is PER TYPE ASKED FOR, so a K-type call divides the input\n // share by K. Still no density modeling: same one policy, content never\n // enters.\n // The window fit: the largest input that still leaves the WHOLE output budget\n // room beside it. This is the sizer's ceiling, and it is the only hard bound\n // on input there is — the two derivations above are not.\n //\n // The 1:2 rule below is a GUESS about how much output a chunk will demand,\n // and on a shared window it is baked into the 1:3 split as well, which is why\n // the ceiling cannot be read off either of them (both come back at exactly\n // the guess, leaving no room to grow into on precisely the self-hosted\n // providers the live gate runs). The duration bound is real but bounds\n // GENERATION, so it belongs to `outputBudget`; it reaches input only through\n // the same ratio guess. `nextChunkSize` exists to replace that guess with\n // measurement, so the guess opens the run and the window caps it.\n const capacityInput = contextTokens - scaffoldTokens - outputBudget;\n\n inputBudget = Math.min(inputBudget, Math.floor(outputBudget / (2 * typesPerCall)));\n\n if (inputBudget <= OVERLAP_TOKENS) {\n throw new Error(\n `Inference window too small for detection: context ${contextTokens} tokens minus scaffold ${scaffoldTokens} leaves an input budget of ${inputBudget} (need > ${OVERLAP_TOKENS}). Use a model with a larger context window or reduce the prompt scaffold.`,\n );\n }\n\n return {\n chunking: { chunkSize: inputBudget, overlap: OVERLAP_TOKENS },\n outputBudget,\n bounds: {\n // Two overlaps: at the floor a chunk is still half text it has not seen\n // before, so the cursor keeps making progress rather than re-reading its\n // own tail. Clamped under the opening size, because a cramped window can\n // derive an opening below even that — and a floor above the opening would\n // clamp every proposal upward, silently reversing the sizer.\n floor: Math.min(inputBudget, 2 * OVERLAP_TOKENS),\n // Never below the opening: a degenerate window can make the fit\n // arithmetic smaller than the size already chosen, and a ceiling under\n // the opening would clamp every proposal DOWN on the first call.\n ceiling: Math.max(inputBudget, capacityInput),\n outputBudget,\n },\n };\n}\n\n/** One chunk handed out by `runAdaptiveChunks`, with the cursor either side of\n * it. `at`/`next` over `totalChars` is exact progress — and, once\n * CHUNK-GRAIN-RESUME lands, the checkpoint identity a variable boundary forces\n * (an ordinal cannot name a chunk whose size is decided while the job runs). */\n/**\n * The half of a `UnitCursor` the DETECTION layer can honestly report: where the\n * walk stands and how it is cutting. The tallies belong to the processor, which\n * owns unit identity and unit counts — this loop counts chunks, not annotations,\n * and a zero it invented would be indistinguishable from a real one.\n */\nexport type ChunkCursor = Pick<UnitCursor, 'next' | 'size'>;\n\nexport interface AdaptiveChunk {\n piece: string;\n /** The token size this piece was cut at. Hand it to `callChunkSubdividing`:\n * a descent halves from the size that actually failed, not from the size the\n * run opened at, which adaptivity has long since left behind. */\n size: number;\n /** Characters consumed BEFORE this chunk — the in-flight liveness position. */\n at: number;\n /** Characters consumed once this chunk completes — the boundary position. */\n next: number;\n /** The document's length. */\n totalChars: number;\n}\n\n/**\n * Walk a document in chunks whose size is decided by the chunks before them.\n *\n * `chunkText` fixes every boundary up front from provider limits alone, which\n * is why the sizing rule could exist for a week and change nothing: a\n * measurement taken on chunk N had nowhere to land. Here chunk N+1 is cut only\n * after chunk N has reported, so the run opens at the static density guess and\n * then moves — a sparse document climbing toward the window's real capacity\n * (fewer, bigger calls), a dense one easing off before it pays a subdivision.\n *\n * `onChunk` returns what the chunk cost. It is awaited, so the caller's own\n * durability (committing the chunk's annotations) still gates the next cut, and\n * a throw stops the walk where it stands rather than advancing past unprocessed\n * text.\n *\n * `resume` restarts a unit an earlier attempt left partway (CHUNK-GRAIN-RESUME\n * P3) — the checkpoint P2 made durable, spent. Both halves of it matter and they\n * are spent differently: the position is taken as given, while the size is\n * seeded and then stepped ONCE, as if the last outcome had been a failure. It\n * was: the job died. Opening at the budget instead would throw away the\n * calibration the dead attempt paid for over its earlier chunks, and seeding\n * unchanged would re-cut the identical piece — which at `DETECTION_TEMPERATURE`\n * 0 returns the identical answer, failure included (HD2, option C).\n */\nexport async function runAdaptiveChunks(\n text: string,\n budget: DetectionBudget,\n onChunk: (chunk: AdaptiveChunk) => Promise<CallOutcome>,\n resume?: UnitCursor,\n): Promise<void> {\n let at = resume?.next ?? 0;\n let size = resume\n ? nextChunkSize({ truncated: true }, resume.size, budget.bounds)\n : budget.chunking.chunkSize;\n\n while (at < text.length) {\n const { piece, next } = cutChunk(text, at, { chunkSize: size, overlap: budget.chunking.overlap });\n const outcome = await onChunk({ piece, size, at, next, totalChars: text.length });\n at = next;\n size = nextChunkSize(outcome, size, budget.bounds);\n }\n}\n\n/**\n * Depth cap for TIMEOUTS only: a call still timing out on a quarter-sized\n * chunk is not a size problem, and timeouts classify transient — the\n * job-level retry is their second chance. Truncations descend by size\n * instead (see `callChunkSubdividing`).\n */\nexport const MAX_SUBDIVISION_DEPTH = 2;\n\n/** The failures a smaller chunk can plausibly fix. An unreadable response\n * that stopped naturally is model misbehavior, not size. */\n/** The F3 shape: unreadable output whose stop reason is UNKNOWN (done_reason\n * absent). Held not-subdividable through P3a for lack of evidence; the live\n * gate then reproduced it twice on real text (2026-09-03 at ~21K chars, P4\n * attempt 2 at ~4.5K, mid-descent, adjacent to max_tokens truncations that\n * healed by subdividing) and measured the retry-at-same-size alternative as a\n * deterministic 34 s burn. Size-shaped on the evidence — descends like\n * truncation, but with no floor re-roll (near-deterministic, nothing salvaged)\n * and unchanged retryable classification (a genuinely broken server still\n * deserves its budget). */\nfunction unknownUnreadable(error: unknown): boolean {\n return error instanceof StructuredReadError && error.stopReason === 'unknown';\n}\n\n/**\n * The model FINISHED and still emitted unparseable JSON — not cut off, not\n * stopped for an unknown reason. Subdividable, but DEPTH-capped rather than\n * size-floored, and the two halves of that are separately earned:\n *\n * Subdividable, because one of these killed a 26-minute attempt at chunk 25 of\n * 49 while the preceding 24 chunks parsed cleanly on the same prompt and model\n * — so the malformation was content-triggered drift, which changing the input\n * can fix. A same-size retry cannot: DETECTION_TEMPERATURE is 0, so the\n * identical call returns the identical response (the same reason a collapse\n * verdict gets no re-roll).\n *\n * Depth-capped rather than size-floored, because if the drift is instead\n * systematic — the model answering this prompt shape wrongly everywhere — every\n * extra level re-reads the same content for the same verdict. Measured, the two\n * settings often coincide (the descent aborts at the first failing sub-piece\n * instead of exploring siblings, so cost is linear in depth, not geometric),\n * and where they differ the cap is the cheaper wrong answer. Timeouts are\n * capped on the same reasoning.\n */\nfunction unreadableDespiteFinishing(error: unknown): boolean {\n return error instanceof StructuredReadError && error.stopReason === 'end_turn';\n}\n\nfunction subdividable(error: unknown): boolean {\n return error instanceof InferenceTimeoutError || truncation(error)\n || unknownUnreadable(error) || unreadableDespiteFinishing(error);\n}\n\n/** Truncation in either surface: parsed-but-flagged (`assertNotTruncated`'s\n * `DeterministicJobError`) or cut off mid-JSON (`StructuredReadError` with\n * `max_tokens`). */\nfunction truncation(error: unknown): boolean {\n return (\n error instanceof DeterministicJobError ||\n (error instanceof StructuredReadError && error.stopReason === 'max_tokens')\n );\n}\n\n/**\n * Run one chunk's inference call, subdividing IN PLACE when it fails in a\n * way a smaller chunk can fix — instead of burning the whole attempt to\n * come back at the same size. Sub-pieces re-use the caller's overlap, so\n * spans straddling a split are caught twice and fall to the downstream\n * span-keyed dedupe. On a failure subdivision cannot fix, the ORIGINAL\n * error propagates so classification sees what actually happened.\n */\n/** What `callChunkSubdividing` produced AND what it cost — the second half is\n * what `runAdaptiveChunks` sizes the next chunk from. Accumulated across the\n * whole descent, because the caller's own `call` closure sees one piece at a\n * time and cannot know a subdivision happened at all. */\nexport interface SubdividedCall<T> {\n items: T[];\n outcome: CallOutcome;\n}\n\nexport interface ChunkCallResult<T> {\n items: T[];\n /** The provider's own token counts, when it reported any. Never estimated. */\n usage?: TokenUsage;\n /** The count-verifier's expectation for this piece, when one was priced. */\n counted?: number;\n}\n\n/** Which shape of failure this was — they demand opposite responses, so the\n * history must tell them apart: truncation descends by size, a timeout fails\n * fast, anything else is not size-shaped at all. */\nfunction outcomeOf(error: unknown): 'truncated' | 'timeout' | 'collapsed' | 'error' {\n // Collapse before truncation: it IS a DeterministicJobError (so the\n // truncation check would swallow it), but in the history the two are\n // different facts — one is output overflow, the other silent under-report.\n if (error instanceof YieldCollapseError) return 'collapsed';\n if (truncation(error)) return 'truncated';\n if (error instanceof InferenceTimeoutError) return 'timeout';\n return 'error';\n}\n\nexport async function callChunkSubdividing<T>(\n label: string,\n chunk: string,\n chunking: ChunkingConfig,\n call: (piece: string) => Promise<ChunkCallResult<T>>,\n logger?: Logger,\n /** A floor-accepted piece's evidence, as it is accepted. Only the floor\n * reports: a collapse healed by descent is telemetry, not result. */\n onUnderReport?: (verdict: UnderReportedPiece) => void,\n /** Each ACCEPTED piece's count-verifier expectation — successes, floor\n * re-rolls, floor-accepted salvage. A flagged piece that descends reports\n * nothing: its children's counts replace it, or the same text is priced\n * twice. */\n onCounted?: (counted: number) => void,\n): Promise<SubdividedCall<T>> {\n // The chunk's cost, summed over however many calls its descent takes. Both\n // are recorded where EVERY call passes, so a subdivision cannot hide from\n // them.\n let outputTokens = 0;\n let sizeShaped = false;\n // A descent's calls must ALL report usage for the sum to mean anything: a\n // partial sum under-counts, and under-counting biases toward growth — the\n // one direction that costs a truncation to discover was wrong.\n let callsMade = 0;\n let callsMeasured = 0;\n // One telemetry record per model call, successes AND failures\n // (DETECTION-QUALITY-THROUGHPUT P1). This is the only place `depth` and\n // `reroll` exist, so it is the only place a complete record can be written.\n async function recorded(piece: string, depth: number, reroll: boolean): Promise<ChunkCallResult<T>> {\n const start = performance.now();\n try {\n const result = await call(piece);\n callsMade += 1;\n if (result.usage) {\n callsMeasured += 1;\n outputTokens += result.usage.outputTokens;\n }\n recordDetectionCall({\n label, pieceChars: piece.length, durationMs: performance.now() - start,\n items: result.items.length, depth, reroll, outcome: 'success',\n ...(result.usage ? { inputTokens: result.usage.inputTokens, outputTokens: result.usage.outputTokens } : {}),\n });\n // A success is always accepted — only failures subdivide.\n if (result.counted !== undefined) onCounted?.(result.counted);\n return result;\n } catch (error) {\n // A failed call still cost its input and its wall time — the descent's\n // price is invisible without it.\n recordDetectionCall({\n label, pieceChars: piece.length, durationMs: performance.now() - start,\n items: 0, depth, reroll, outcome: outcomeOf(error),\n });\n throw error;\n }\n }\n\n async function attempt(piece: string, chunkSize: number, depth: number): Promise<T[]> {\n try {\n return (await recorded(piece, depth, false)).items;\n } catch (error) {\n if (!subdividable(error)) throw error;\n // Size-shaped, so the size was wrong — true whether or not the descent\n // below rescues it. The next chunk must not be cut at a size this one\n // already paid to discover was too big.\n sizeShaped = true;\n const half = Math.floor(chunkSize / 2);\n // Truncation descends by SIZE: demand halves with each subdivision,\n // so descent terminates — and list-dense text (registers, indexes)\n // honestly yields several times its input in annotation output, so\n // the descent must go as deep as the content demands. The floor\n // derives from the overlap constant; below it even solid names fit\n // the budget. Timeouts stay depth-capped and fail fast.\n //\n // A descent must also actually CHANGE the input: once a piece fits\n // inside the smaller chunk size, re-chunking returns it unchanged, and\n // at temperature 0 the identical call returns the identical failure —\n // measured live (P4 attempt 1: one 572-char piece \"descended\" through\n // three depths, same verdict each time). A piece that cannot shrink is\n // AT its floor, whatever the arithmetic floor says.\n const pieces = chunkText(piece, { chunkSize: half, overlap: chunking.overlap });\n const shrinks = pieces.length > 1 || pieces[0] !== piece;\n // Size-shaped failures (truncation, collapse, the F3 unknown-unreadable)\n // descend to the SIZE floor; only timeouts are depth-capped — the F3 fix\n // must reach failures that first appear mid-descent (measured at depth 3).\n const canDescend = shrinks && (truncation(error) || unknownUnreadable(error)\n ? half > 2 * OVERLAP_TOKENS\n : depth < MAX_SUBDIVISION_DEPTH);\n if (!canDescend) {\n // A collapse verdict at the floor is ACCEPTED, loudly (ruled\n // 2026-09-05): its salvage flows through with a warning instead of\n // one hostile piece discarding the whole unit's work. No re-roll —\n // the collapse is deterministic, a same-size retry changes nothing.\n if (error instanceof YieldCollapseError) {\n logger?.warn('Floor-size piece still flagged as collapsed — accepting its under-reported salvage and continuing', {\n pieceChars: piece.length,\n salvaged: error.salvage.length,\n error: error.message,\n });\n onUnderReport?.(error.verdict);\n onCounted?.(error.verdict.counted);\n return error.salvage as T[];\n }\n // At the size floor honest overflow is impossible, so truncation\n // here is a degeneration loop — a sampling accident. One same-size\n // re-roll; a second truncation propagates. Timeouts get no re-roll.\n if (!truncation(error)) throw error;\n logger?.warn('Floor-size piece truncated — re-rolling once before giving up', {\n pieceChars: piece.length,\n error: error instanceof Error ? error.message : String(error),\n });\n return (await recorded(piece, depth, true)).items;\n }\n logger?.warn('Chunk call failed at a size-shaped bound — subdividing and retrying smaller', {\n depth: depth + 1,\n pieceChars: piece.length,\n nextChunkSizeTokens: half,\n error: error instanceof Error ? error.message : String(error),\n });\n const collected: T[] = [];\n for (const p of pieces) {\n collected.push(...(await attempt(p, half, depth + 1)));\n }\n return collected;\n }\n }\n const items = await attempt(chunk, chunking.chunkSize, 0);\n const measured = callsMade > 0 && callsMeasured === callsMade;\n return {\n items,\n outcome: { truncated: sizeShaped, ...(measured ? { outputTokens } : {}) },\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 * Locale handling: builders take two optional BCP-47 tags. `language` is the\n * locale the *generated body text* should be written in (sourced from the user's\n * UI locale); `sourceLanguage` is the locale of the *text being analyzed*\n * (sourced from `ResourceDescriptor` / its primary representation). They are\n * independent — see `types.ts` \"Locale conventions\" for the full discussion.\n */\n\nimport { getLocaleEnglishName } from '@semiont/core';\n\nfunction languageName(tag: string): string {\n return getLocaleEnglishName(tag) || tag;\n}\n\n/** Returns \"Source text language: <Name>.\" or empty string. */\nfunction sourceLanguageGuidance(sourceLanguage?: string): string {\n if (!sourceLanguage) return '';\n return `\\n\\nSource text language: ${languageName(sourceLanguage)}.`;\n}\n\n/** Returns \"Write your <kind> in <Name>.\" or empty string. */\nfunction bodyLanguageGuidance(language: string | undefined, kind: string): string {\n if (!language || language === 'en') return '';\n return `\\n\\nIMPORTANT: Write your ${kind} in ${languageName(language)}.`;\n}\n\nexport class MotivationPrompts {\n /**\n * Build a prompt for detecting comment-worthy passages\n *\n * @param content - The text content to analyze — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 language?: string,\n sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n const bodyLang = bodyLanguageGuidance(language, 'comments');\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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"comment\": your comment following the instructions above\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"the quarterly review meeting\", \"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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"comment\": your explanatory comment (1-3 sentences, provide context/background/clarification)\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"Ouranos\", \"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 — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\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}${sourceLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"revenue grew 45% year-over-year\", \"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}${sourceLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"we will discontinue support for legacy systems by March 2025\", \"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 — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 language?: string,\n sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n const bodyLang = bodyLanguageGuidance(language, 'assessments');\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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"assessment\": your assessment following the instructions above\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"the quarterly revenue target\", \"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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"assessment\": your analytical assessment (1-3 sentences, evaluate validity/strength/implications)\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"AI will replace most jobs by 2030\", \"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 sourceLanguage?: string\n ): string {\n // Tags are schema-defined identifiers (\"Issue\", \"Rule\") — the LLM doesn't\n // generate the category label, so there's no body-language guidance here.\n // Only `sourceLanguage` is wired into the prompt; `language` (body locale)\n // is consumed at the body-stamp site in `processors.ts`.\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n\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)${sourceLang}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"What duty did the defendant owe?\", \"prefix\": \"The central question is: \", \"suffix\": \" This question must be\"},\n {\"exact\": \"In tort law, a duty of care is established when...\", \"prefix\": \"Legal framework:\\\\n\", \"suffix\": \"\\\\n\\\\nApplying this standard\"}\n]`;\n\n return prompt;\n }\n}\n","import type { AnchorMethod, Logger } from '@semiont/core';\nimport { recordAnchorOutcome } from '@semiont/observability';\n\n/**\n * The anchoring methods that picked a plausible occurrence rather than a\n * certain one: `first-of-many` had several candidates and no usable context,\n * `fuzzy-match` recovered through case/whitespace/Levenshtein. Neither is an\n * error — the write-time selector invariant still holds — but both are places\n * the span could be the wrong instance.\n *\n * ONE decider, deliberately. This classification lived in two places (the\n * reference path's inline warn and the motivation parsers' logger) that\n * happened to agree; two copies of a risk judgement is one copy too many.\n */\nconst DEGRADED: ReadonlySet<string> = new Set<AnchorMethod>(['first-of-many', 'fuzzy-match']);\n\n/**\n * Audit one anchoring outcome: counted always, warned only when degraded.\n *\n * Counting EVERY outcome is the point (P5). A warning tells an operator that\n * one anchor was uncertain; only a rate over all anchors says whether the\n * detection run was precise, and the rate is what the plan asks to put beside\n * the yield numbers.\n */\nexport function noteAnchor(label: string, exact: string, method: AnchorMethod, logger?: Logger): void {\n recordAnchorOutcome(label, method);\n if (!DEGRADED.has(method)) return;\n const detail = { text: exact, anchorMethod: method };\n if (logger) logger.warn('Annotation anchored via degraded method', { label, ...detail });\n else console.warn(`[${label}] anchored via ${method}: \"${exact}\"`);\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 { reconcileSelector, isObject, isString, type AnchorMethod } from '@semiont/core';\nimport type { ElementSchema } from '@semiont/inference';\nimport { noteAnchor } from './anchor-audit';\n\n// Parsers receive ALREADY-PARSED elements (`unknown[]`) from the structured\n// inference surface — `generateStructured` returns `T[]` or throws, so\n// \"could not read the model\" never reaches this layer and there is no string\n// to parse here (the former strict `parseJsonArray` moved into that contract,\n// as the earlier tolerant walker moved into it before). What remains here is\n// per-element structural validation (STRUCTURED-INFERENCE D5 — the last line\n// on the Ollama path and the schema/type drift guard) plus reconciliation\n// against the full document.\n//\n// Each element schema is declared ADJACENT to the Match interface it mirrors:\n// the schema constrains the wire, the interface is what the code consumes,\n// and nothing verifies they agree — adjacency is the drift guard.\n// `prefix`/`suffix` stay OUT of `required` deliberately: requiring them turns\n// \"sometimes absent\" into \"always present, sometimes empty\" (measured\n// 2026-08-06), an anchoring-path change Phase 3 examines before anyone\n// relies on it.\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/** Wire schema for one comment element — keep in lockstep with `CommentMatch`. */\nexport const COMMENT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n comment: { type: 'string' },\n },\n required: ['exact', 'comment'],\n additionalProperties: false,\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/** Wire schema for one highlight element — keep in lockstep with `HighlightMatch`. */\nexport const HIGHLIGHT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact'],\n additionalProperties: false,\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/** Wire schema for one assessment element — keep in lockstep with `AssessmentMatch`. */\nexport const ASSESSMENT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n assessment: { type: 'string' },\n },\n required: ['exact', 'assessment'],\n additionalProperties: false,\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\n/**\n * Wire schema for one tag element — keep in lockstep with `RawTagInput`\n * (the category is stamped by the caller, not emitted by the model).\n */\nexport const TAG_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact'],\n additionalProperties: false,\n};\n\nexport class MotivationParsers {\n /**\n * Validate and reconcile structured comment elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated comment matches\n */\n static parseComments(parsed: unknown[], content: string): CommentMatch[] {\n\n const valid = parsed.filter((c): c is { exact: string; prefix?: string; suffix?: string; comment: string } =>\n isObject(c) &&\n isString(c.exact) &&\n isString(c.comment) &&\n c.comment.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid comments from ${parsed.length} total`);\n\n const validatedComments: CommentMatch[] = [];\n for (const comment of valid) {\n const reconciled = reconcileSelector(content, {\n exact: comment.exact,\n ...(typeof comment.prefix === 'string' ? { prefix: comment.prefix } : {}),\n ...(typeof comment.suffix === 'string' ? { suffix: comment.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated comment \"${comment.exact}\"`);\n continue;\n }\n logAnchorMethod('comment', comment.exact, reconciled.anchorMethod);\n validatedComments.push({\n comment: comment.comment,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedComments;\n }\n\n /**\n * Validate and reconcile structured highlight elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated highlight matches\n */\n static parseHighlights(parsed: unknown[], content: string): HighlightMatch[] {\n\n const highlights = parsed.filter((h): h is { exact: string; prefix?: string; suffix?: string } =>\n isObject(h) && isString(h.exact)\n );\n\n const validatedHighlights: HighlightMatch[] = [];\n for (const highlight of highlights) {\n const reconciled = reconcileSelector(content, {\n exact: highlight.exact,\n ...(typeof highlight.prefix === 'string' ? { prefix: highlight.prefix } : {}),\n ...(typeof highlight.suffix === 'string' ? { suffix: highlight.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated highlight \"${highlight.exact}\"`);\n continue;\n }\n logAnchorMethod('highlight', highlight.exact, reconciled.anchorMethod);\n validatedHighlights.push({\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedHighlights;\n }\n\n /**\n * Validate and reconcile structured assessment elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated assessment matches\n */\n static parseAssessments(parsed: unknown[], content: string): AssessmentMatch[] {\n\n const assessments = parsed.filter((a): a is { exact: string; prefix?: string; suffix?: string; assessment: string } =>\n isObject(a) && isString(a.exact) && isString(a.assessment)\n );\n\n const validatedAssessments: AssessmentMatch[] = [];\n for (const assessment of assessments) {\n const reconciled = reconcileSelector(content, {\n exact: assessment.exact,\n ...(typeof assessment.prefix === 'string' ? { prefix: assessment.prefix } : {}),\n ...(typeof assessment.suffix === 'string' ? { suffix: assessment.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated assessment \"${assessment.exact}\"`);\n continue;\n }\n logAnchorMethod('assessment', assessment.exact, reconciled.anchorMethod);\n validatedAssessments.push({\n assessment: assessment.assessment,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedAssessments;\n }\n\n /**\n * Validate structured tag elements into raw, pre-reconciliation tag inputs.\n * Reconciliation happens in `validateTagOffsets`, which adds `start`/`end`\n * by anchoring `exact` against the source content.\n *\n * @param parsed - Already-parsed elements from the structured surface\n */\n static parseTags(parsed: unknown[]): RawTagInput[] {\n\n const valid = parsed.filter((t): t is RawTagInput =>\n isObject(t) && isString(t.exact) && 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 }\n\n /**\n * Anchor raw tag inputs against source content and add category.\n */\n static validateTagOffsets(\n tags: RawTagInput[],\n content: string,\n category: string\n ): TagMatch[] {\n const validatedTags: TagMatch[] = [];\n for (const tag of tags) {\n const reconciled = reconcileSelector(content, {\n exact: tag.exact,\n ...(typeof tag.prefix === 'string' ? { prefix: tag.prefix } : {}),\n ...(typeof tag.suffix === 'string' ? { suffix: tag.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated tag \"${tag.exact}\" for category \"${category}\"`);\n continue;\n }\n logAnchorMethod('tag', tag.exact, reconciled.anchorMethod);\n validatedTags.push({\n category,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n return validatedTags;\n }\n}\n\n/** Raw LLM-emitted tag, pre-reconciliation. */\nexport interface RawTagInput {\n exact: string;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * Audit one anchor-method classification. Forwards to the single decider\n * shared with the reference path (`anchor-audit.ts`) — which methods count as\n * risky is one judgement, and this file used to hold a second copy of it.\n */\nfunction logAnchorMethod(motivation: string, exact: string, anchorMethod: AnchorMethod): void {\n noteAnchor(motivation, exact, anchorMethod);\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Build AI prompts using MotivationPrompts\n * 2. Call AI inference\n * 3. Parse and validate results using MotivationParsers\n *\n * All methods take content as a string parameter — the worker process\n * fetches it and hands it in.\n */\n\nimport type { ElementSchema, InferenceClient } from '@semiont/inference';\nimport { estimateTokens, type UnitCursor } from '@semiont/core';\nimport { boundedGenerateStructured } from './inference-call';\nimport { assertNotTruncated, callChunkSubdividing, deriveDetectionBudget, runAdaptiveChunks, type ChunkCursor, DETECTION_TEMPERATURE } from './detection/detection-chunking';\nimport { MotivationPrompts } from './detection/motivation-prompts';\nimport {\n MotivationParsers,\n COMMENT_ELEMENT_SCHEMA,\n HIGHLIGHT_ELEMENT_SCHEMA,\n ASSESSMENT_ELEMENT_SCHEMA,\n TAG_ELEMENT_SCHEMA,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from './detection/motivation-parsers';\nimport type { TagSchema } from '@semiont/core';\n\n/**\n * Per-chunk detection loop shared by the four motivations.\n *\n * Budgets derive from the provider's actual limits plus the measured prompt\n * scaffold (`buildPrompt('')`) — no literals. The prompt receives one chunk;\n * `parse` reconciles against the FULL document (the callers close over it),\n * so offsets index into the whole resource with no re-anchoring arithmetic.\n * Overlap duplicates pass through — the processor's span-keyed seen-set is\n * the single dedupe point.\n *\n * `onActivity` fires whenever the detection is demonstrably alive: at each\n * chunk boundary (the count advances) AND periodically while one inference\n * call is in flight (the count repeats — liveness, not progress). Progress is\n * the worker's liveness heartbeat AND the client's inter-emission timeout\n * signal, so a silent single-chunk run kills a healthy job\n * (DETECTION-HEARTBEAT).\n */\nasync function detectInChunks<T>(\n client: InferenceClient,\n content: string,\n buildPrompt: (chunk: string) => string,\n motivation: string,\n elementSchema: ElementSchema,\n parse: (items: unknown[]) => T[],\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /**\n * This chunk's parsed matches, awaited before the loop continues: the\n * caller commits them, and the loop must not run ahead of durability.\n * Unlike `onActivity` (a liveness heartbeat, which may repeat), this fires\n * exactly once per chunk, including the last.\n *\n * `cursor` is where the run stands once this chunk is committed — handed over\n * WITH the results so a caller cannot record a position it has not made\n * durable (CHUNK-GRAIN-RESUME P2).\n */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3).\n * Before the callback below, which stays last. */\n resume?: UnitCursor,\n onChunkResults?: (parsed: T[], cursor: ChunkCursor) => Promise<void>,\n): Promise<T[]> {\n const limits = await client.limits();\n const scaffoldTokens = estimateTokens(buildPrompt(''));\n // One motivation's spans per call — the single span family this prompt\n // asks for, the motivation-path analogue of one entity type.\n const budget = deriveDetectionBudget(limits, scaffoldTokens, 1);\n const { outputBudget } = budget;\n\n const collected: T[] = [];\n await runAdaptiveChunks(content, budget, async ({ piece: chunk, size, at, next, totalChars }) => {\n // Structured surface: parsed elements or a throw — an unreadable model\n // response fails the job rather than reading as an empty detection. A\n // size-shaped failure (duration bound, truncation) subdivides in place\n // and retries smaller before it is allowed to fail the job.\n const { items, outcome } = await callChunkSubdividing<unknown>(\n motivation, chunk, { chunkSize: size, overlap: budget.chunking.overlap },\n async (piece) => {\n const response = await boundedGenerateStructured<unknown>(\n client, buildPrompt(piece), outputBudget, DETECTION_TEMPERATURE, elementSchema,\n // Still alive, same position (a long single call is otherwise silent).\n () => onActivity?.(at, totalChars),\n );\n assertNotTruncated(response, `${motivation} detection`, at, totalChars, outputBudget);\n // Usage rides back so the telemetry record carries what the call COST\n // beside what it yielded — the provider's own counts, not an estimate.\n return { items: response.items, ...(response.usage ? { usage: response.usage } : {}) };\n },\n );\n const fromChunk = parse(items);\n collected.push(...fromChunk);\n await onChunkResults?.(fromChunk, { next, size });\n // Chunk boundary: the cursor advances (real progress). Only when text\n // remains — the final cut has no boundary after it, and the caller reports\n // the unit's completion itself.\n if (next < totalChars) onActivity?.(next, totalChars);\n return outcome;\n }, resume);\n return collected;\n}\n\nexport class AnnotationDetection {\n\n /**\n * Detect comments in content.\n *\n * `language` is the locale the LLM should write comment text in (annotation\n * body locale). `sourceLanguage` is the locale of the content being analyzed\n * (source-resource locale). See `types.ts` \"Locale conventions\" for the\n * full discussion.\n */\n static async detectComments(\n content: string,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number,\n language?: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: CommentMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<CommentMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildCommentPrompt(chunk, instructions, tone, density, language, sourceLanguage),\n 'comment', COMMENT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseComments(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect highlights in content.\n *\n * Highlights have no body — only `sourceLanguage` (source-resource locale)\n * applies, used in the prompt so the LLM analyzes non-English source\n * correctly.\n */\n static async detectHighlights(\n content: string,\n client: InferenceClient,\n instructions?: string,\n density?: number,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: HighlightMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<HighlightMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildHighlightPrompt(chunk, instructions, density, sourceLanguage),\n 'highlight', HIGHLIGHT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseHighlights(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect assessments in content.\n *\n * `language` is the locale the LLM should write assessment text in\n * (annotation body locale). `sourceLanguage` is the locale of the content\n * being analyzed (source-resource locale).\n */\n static async detectAssessments(\n content: string,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number,\n language?: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: AssessmentMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<AssessmentMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildAssessmentPrompt(chunk, instructions, tone, density, language, sourceLanguage),\n 'assessment', ASSESSMENT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseAssessments(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect tags in content for a specific category.\n *\n * The full `TagSchema` is supplied by the dispatcher (resolved against\n * the per-KB tag-schema projection at job-creation time) so the worker\n * is independent of the registry.\n *\n * `sourceLanguage` is the locale of the content being analyzed. Body-locale\n * (`language`) doesn't influence the tag prompt — categories are schema\n * identifiers, not LLM-generated text — so it's consumed at the body-stamp\n * site, not here.\n */\n static async detectTags(\n content: string,\n client: InferenceClient,\n schema: TagSchema,\n category: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /**\n * This chunk's matches, ANCHORED before they leave: `parse` here yields\n * raw tags, so this path runs `validateTagOffsets` per chunk — a per-item\n * anchor against the full document, so partitioning changes nothing.\n */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: TagMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<TagMatch[]> {\n const categoryInfo = schema.tags.find((t) => t.name === category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schema.id}`);\n }\n\n // Parse per chunk; anchor once against the full document afterward.\n const parsedTags = await detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildTagPrompt(\n chunk,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples,\n sourceLanguage\n ),\n 'tag', TAG_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseTags(items),\n onActivity,\n resume,\n onChunkResults\n ? async (raw, cursor) => onChunkResults(MotivationParsers.validateTagOffsets(raw, content, category), cursor)\n : undefined,\n );\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n}\n","import type { ElementSchema, InferenceClient } from '@semiont/inference';\nimport { estimateTokens, getLocaleEnglishName, isObject, isString, type Logger, type UnitCursor } from '@semiont/core';\nimport { boundedGenerateStructured, boundedGenerateWithMetadata } from '../inference-call';\nimport { assertNotTruncated, callChunkSubdividing, deriveDetectionBudget, runAdaptiveChunks, type ChunkCursor, DETECTION_TEMPERATURE, YIELD_COLLAPSE_BAND, YieldCollapseError, type UnderReportedPiece } from './detection-chunking';\n\n/**\n * Entity reference extracted from text — pre-reconciliation.\n *\n * The LLM emits `exact` (verbatim text span), `entityType`, and optional\n * `prefix` / `suffix` context for disambiguation. Offsets are not asked\n * for — `reconcileSelector` computes them by anchoring `exact` against\n * the source content in the calling processor.\n */\nexport interface ExtractedEntity {\n exact: string;\n entityType: string;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * JSON Schema for one extracted entity — the provider-enforced shape.\n *\n * Declared adjacent to `ExtractedEntity` deliberately: the schema is what\n * constrains the wire and the interface is what the code consumes, and\n * nothing verifies they agree — adjacency is the drift guard. The\n * per-element `isObject`/`isString` checks below stay as the structural\n * backstop (STRUCTURED-INFERENCE D5).\n *\n * `prefix`/`suffix` are deliberately NOT in `required`: with all four\n * required, models return `\"prefix\": \"\"` instead of omitting the key\n * (measured 2026-08-06), turning \"sometimes absent\" into \"always present,\n * sometimes empty\" — an anchoring-path change Phase 3 re-examines before\n * anyone relies on it.\n */\nconst ENTITY_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n entityType: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact', 'entityType'],\n additionalProperties: false,\n};\n\n/**\n * Extract entity references from text using AI.\n *\n * Locale: entity references' bodies are entity-type identifiers (not\n * LLM-generated natural-language text), so only `sourceLanguage` (source-\n * resource locale) is meaningful here — it's used in the prompt so the LLM\n * analyzes non-English source correctly. There's no body-locale parameter.\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 - Logger for entity-extraction diagnostics (parse failures,\n * anchor decisions, drops). Required so dropped/filtered entities never\n * disappear silently.\n * @param sourceLanguage - BCP-47 tag for the source content's language\n * @param onActivity - Invoked with (consumedChars, totalChars) whenever the\n * extraction is demonstrably alive: at each chunk boundary (the cursor\n * advances) AND periodically while a single inference call is in flight\n * (the position repeats — liveness, not progress). Characters, not chunk\n * ordinals: chunk sizing is decided as the run goes, so there is no chunk\n * total to divide by — and the cursor was always the more honest numerator,\n * since boundary-seeking already made chunks unequal. The caller MUST forward\n * this to its progress channel: progress is the worker's liveness\n * heartbeat for the stall watchdog, and the client's timeout is an\n * INTER-EMISSION one, so a silent single-chunk run kills a healthy job\n * (DETECTION-HEARTBEAT).\n * @returns Array of extracted entities with their character offsets\n */\n/** Output cap for the count call: the answer is one number (≤7 digits), and a\n * tiny cap is itself the safety — a ~5-token output structurally cannot loop\n * or truncate the way the extraction's array can. */\nconst COUNT_MAX_TOKENS = 16;\n\n/** The count answer, read as its leading integer. \"Respond with only the\n * number\" is the prompt's contract, but a model that pads it (\"There are 50\")\n * still yields its verdict; anything with no integer yields none. */\nfunction parseCount(text: string): number | undefined {\n const m = text.trim().match(/\\d+/);\n return m ? Number(m[0]) : undefined;\n}\n\n/**\n * The count-verifier (OLLAMA-DETECTION-TESTING P3c): guard a SUCCESSFUL\n * extraction against silent yield collapse (F7) — a schema-clean response\n * carrying a fraction of the mentions present, measured deterministic and\n * classification-invisible, so nothing else can catch it.\n *\n * A cheap count call (\"respond with only the number\") sets the expectation\n * FROM THE SAME TEXT — corpus-free, per the no-input-assumptions principle.\n * An extraction under 1/BAND of the count throws the collapse verdict, which\n * subdivision treats like truncation (descend by size) except at the floor,\n * where it fails the job loudly (user-ratified).\n *\n * The verifier's own failure — count call errors, or answers with no number —\n * disables it for the chunk (warn, pass through): a safety net's outage must\n * not take down a healthy extraction. Known limit, documented in the bug\n * report: the count saturates past ~8K chars, so margins are cleanest at\n * post-descent sizes; it still flagged every measured collapse at 16K/32K.\n */\nasync function assertYieldNotCollapsed(\n client: InferenceClient,\n piece: string,\n items: readonly unknown[],\n entityTypesDescription: string,\n logger: Logger,\n): Promise<number | undefined> {\n const prompt = `Count every mention of: ${entityTypesDescription} in the following text. Repeated mentions of the same entity count separately. Respond with only the number.\n\nText:\n\"\"\"\n${piece}\n\"\"\"`;\n\n let counted: number | undefined;\n try {\n const response = await boundedGenerateWithMetadata(client, prompt, COUNT_MAX_TOKENS, DETECTION_TEMPERATURE, undefined, logger);\n counted = parseCount(response.text);\n } catch (err) {\n logger.warn('Count-verifier call failed — yield check skipped for this chunk', {\n pieceChars: piece.length,\n error: err instanceof Error ? err.message : String(err),\n });\n return undefined;\n }\n if (counted === undefined) {\n logger.warn('Count-verifier answer carried no number — yield check skipped for this chunk', { pieceChars: piece.length });\n return undefined;\n }\n if (items.length * YIELD_COLLAPSE_BAND < counted) {\n // The salvage rides the error: descent discards it (a smaller re-run does\n // better), the floor accepts it (better than nothing, and every span is\n // write-time-verified).\n throw new YieldCollapseError(\n `Extraction found ${items.length} entities where a count call reports ~${counted} mentions (band ×${YIELD_COLLAPSE_BAND}) on a ${piece.length}-char chunk — silent yield collapse (F7): deterministic — a same-size retry returns the identical under-report.`,\n [...items],\n { found: items.length, counted, pieceChars: piece.length },\n );\n }\n return counted;\n}\n\nexport async function extractEntities(\n exact: string,\n entityTypes: string[] | { type: string; examples?: string[] }[],\n client: InferenceClient,\n includeDescriptiveReferences: boolean,\n logger: Logger,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** A floor-accepted piece's evidence, as it is accepted. */\n onUnderReport?: (verdict: UnderReportedPiece) => void,\n /** Each accepted piece's count-verifier expectation — the denominator. */\n onCounted?: (counted: number) => void,\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). Absent on\n * a first attempt, and then the run opens at the top exactly as before.\n * Deliberately BEFORE the callback below, which stays last. */\n resume?: UnitCursor,\n /**\n * This chunk's entities, awaited before the loop continues: the caller\n * commits them, and the loop must not run ahead of durability. Unlike\n * `onActivity` (a liveness heartbeat, which may repeat), this fires exactly\n * once per chunk, including the last. Kept LAST on every detection seam —\n * test harnesses read it as the final positional argument, so a parameter\n * appended after it silently starves them of results.\n *\n * `cursor` is where the run stands ONCE THIS CHUNK IS COMMITTED — the pair\n * CHUNK-GRAIN-RESUME checkpoints. It is handed over with the results rather\n * than reported separately so the two cannot drift: a caller that records the\n * position without durably committing the annotations would checkpoint ahead\n * of the log.\n */\n onChunkResults?: (items: ExtractedEntity[], cursor: ChunkCursor) => Promise<void>,\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 sourceLangGuidance = sourceLanguage\n ? `\\nSource text language: ${getLocaleEnglishName(sourceLanguage) || sourceLanguage}.\\n`\n : '';\n\n // The LLM is asked for `exact`, `prefix`, and `suffix` — no character\n // offsets. Offsets get computed by `reconcileSelector` against the\n // source content. Asking the model for offsets wastes tokens and\n // encourages it to fabricate where it shouldn't.\n const buildPrompt = (text: string): string => `Identify entity references in the following text. Look for mentions of: ${entityTypesDescription}.\n${descriptiveReferenceGuidance}${sourceLangGuidance}\nText to analyze:\n\"\"\"\n${text}\n\"\"\"\n\nRespond with a JSON array of entities found. Each entity should have:\n- exact: the exact text span from the input (quoted verbatim — character-for-character)\n- entityType: one of the provided entity types\n- prefix: up to 64 characters of text immediately before the entity (used to disambiguate when the same text appears more than once)\n- suffix: up to 64 characters of text immediately after the entity (same purpose)\n\nIf no entities are found, respond with an empty array [].\n\nExample output:\n[{\"exact\":\"Alice\",\"entityType\":\"Person\",\"prefix\":\"\",\"suffix\":\" went to\"},{\"exact\":\"Paris\",\"entityType\":\"Location\",\"prefix\":\"went to \",\"suffix\":\" yesterday\"}]`;\n\n // Budgets derive from the provider's actual limits + the measured scaffold\n // (the template around the content) — no literals. Input is chunked only\n // when the derived budget forces it; small documents make one call, as\n // before.\n const limits = await client.limits();\n // The provider DECLARES whether its extractions get count-verified\n // (universal for real providers since the 2026-09-05 ruling — unverified\n // completeness is not a savings). Jobs does no provider-specific switching:\n // whatever varies by provider is a capability on the InferenceClient\n // contract, read here like `maxConcurrency`.\n const verifyYield = client.verifyDetectionYield;\n const scaffoldTokens = estimateTokens(buildPrompt(''));\n // One call asks for every type in `entityTypes` — the processor's per-type\n // loop passes one, so this is 1 in production today.\n const budget = deriveDetectionBudget(limits, scaffoldTokens, entityTypes.length);\n const { chunking, outputBudget } = budget;\n\n logger.debug('Sending entity extraction request', {\n entityTypes: entityTypesDescription,\n chars: exact.length,\n // The size the run OPENS at, and how far measured yield may move it. The\n // chunk COUNT is deliberately absent: with sizing decided as the run goes,\n // there is no honest total until the cursor reaches the end.\n openingChunkSizeTokens: chunking.chunkSize,\n ceilingChunkSizeTokens: budget.bounds.ceiling,\n outputBudget,\n });\n\n const collected: ExtractedEntity[] = [];\n await runAdaptiveChunks(exact, budget, async ({ piece: chunk, size, at, next, totalChars }) => {\n // The structured surface returns parsed elements or THROWS — an\n // unreadable model response is a job failure, never a silent []. A\n // size-shaped failure (duration bound, truncation) subdivides in place\n // and retries smaller before it is allowed to fail the job.\n const { items, outcome } = await callChunkSubdividing<unknown>(\n 'reference', chunk, { chunkSize: size, overlap: chunking.overlap },\n async (piece) => {\n const response = await boundedGenerateStructured<unknown>(\n client,\n buildPrompt(piece),\n outputBudget,\n DETECTION_TEMPERATURE,\n ENTITY_ELEMENT_SCHEMA,\n // Still alive, same position: a long single call would otherwise emit\n // nothing at all between start and finish.\n () => onActivity?.(at, totalChars),\n logger,\n );\n logger.debug('Got entity extraction response', {\n at,\n totalChars,\n chunkSizeTokens: size,\n pieceChars: piece.length,\n items: response.items.length,\n });\n\n // Truncation is data loss, not \"no entities\" — check it BEFORE\n // consuming: a truncated structured response can still carry a valid\n // partial array, so the items themselves cannot signal the loss.\n assertNotTruncated(response, 'Entity extraction', at, totalChars, outputBudget);\n // And a CLEAN response can still be a silent under-report (F7) — the\n // count-verifier is the only signal for that, and a flag throws the\n // collapse verdict so subdivision changes the input.\n const counted = verifyYield\n ? await assertYieldNotCollapsed(client, piece, response.items, entityTypesDescription, logger)\n : undefined;\n // Usage rides back so the telemetry record carries what the call COST\n // beside what it yielded — the provider's own counts, not an estimate.\n return {\n items: response.items,\n ...(response.usage ? { usage: response.usage } : {}),\n ...(counted !== undefined ? { counted } : {}),\n };\n },\n logger, onUnderReport, onCounted,\n );\n\n const fromChunk: ExtractedEntity[] = [];\n for (const e of items) {\n // No dedupe here: overlap duplicates from adjacent chunks pass through\n // to the caller's decider — the single dedupe point.\n if (isObject(e) && isString(e.exact) && isString(e.entityType)) {\n fromChunk.push({\n exact: e.exact,\n entityType: e.entityType,\n ...(isString(e.prefix) ? { prefix: e.prefix } : {}),\n ...(isString(e.suffix) ? { suffix: e.suffix } : {}),\n });\n } else {\n logger.debug('Dropped malformed LLM entity', { entity: e });\n }\n }\n collected.push(...fromChunk);\n await onChunkResults?.(fromChunk, { next, size });\n\n // Chunk boundary: the cursor advances (real progress). Only when text\n // remains — the final cut has no boundary after it, and the caller reports\n // the unit's completion itself.\n if (next < totalChars) onActivity?.(next, totalChars);\n return outcome;\n }, resume);\n\n return collected;\n}\n","/**\n * Resource Generation\n *\n * Generates markdown resources from topics using AI inference.\n */\n\nimport { getLocaleEnglishName, deriveViews } from '@semiont/core';\nimport type { GatheredContext, Logger, SupportedMediaType } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\nimport { boundedGenerateWithMetadata } from '../inference-call';\n\n\nfunction getLanguageName(locale: string): string {\n return getLocaleEnglishName(locale) || locale;\n}\n\n// Prompt-embedding caps — bound the context fed to the model (CONTEXT-IDENTIFIERS\n// D4: named constants; promote to caller-tunable options only if a consumer\n// actually hits the wall). A fact past these bounds never reaches the model.\nconst RESOURCE_CONTENT_CAP = 4000;\nconst SEMANTIC_MATCH_LIMIT = 3;\nconst SEMANTIC_MATCH_CHARS = 240;\n\n/**\n * Model-visible identifier handle for an embedded excerpt — the ONE bracket\n * convention across all context sections (CONTEXT-IDENTIFIERS D1/D2): resource id\n * always, annotation id as a suffix when the excerpt is annotation-derived.\n */\nfunction idLabel(resourceId: string, annotationId?: string): string {\n return `[${resourceId}${annotationId ? `/${annotationId}` : ''}]`;\n}\n\n/**\n * The canonical gateway default for maxTokens — a short-definition size. The\n * UI also initialises its field to 500 as a UX convenience, but the\n * authoritative fallback lives here so direct API callers get a sensible\n * limit when they omit the parameter. Exported so error messages elsewhere\n * can name the ceiling that actually applied (one constant, no drift).\n */\nexport const DEFAULT_MAX_TOKENS = 500;\n\n/**\n * Generate resource content using inference.\n *\n * Locale parameters: `locale` is the *body* locale — the language the\n * generated resource should be written in (sourced from the user's UI\n * locale). `sourceLanguage` is the *source* locale — the language of the\n * referenced resource whose context (selected passage, surrounding text)\n * is embedded into the prompt. They're independent: a German user can\n * generate German content from an English source resource. See\n * `types.ts` \"Locale conventions\" for the full discussion.\n */\nexport async function generateResourceFromTopic(\n topic: string,\n entityTypes: string[],\n client: InferenceClient,\n logger: Logger,\n userPrompt?: string,\n locale?: string,\n context?: GatheredContext,\n temperature?: number,\n maxTokens?: number,\n sourceLanguage?: string,\n outputMediaType: SupportedMediaType = 'text/markdown',\n task: string = 'resource',\n structure?: string,\n cite: boolean = false,\n repair?: { source: string; error: string }\n): Promise<{ title: string; content: string; truncated: boolean }> {\n logger.debug('Generating resource from topic', {\n topicPreview: topic.substring(0, 100),\n entityTypes,\n hasUserPrompt: !!userPrompt,\n locale,\n sourceLanguage,\n hasContext: !!context,\n temperature,\n maxTokens,\n outputMediaType,\n task,\n structure\n });\n\n // Use provided values or defaults.\n const finalTemperature = temperature ?? 0.7;\n const finalMaxTokens = maxTokens ?? DEFAULT_MAX_TOKENS;\n\n // Determine language instructions. Body locale (\"write the resource in X\")\n // and source locale (\"the embedded source text is in Y\") are independent —\n // a German user can ask for a German write-up of an English source.\n const languageInstruction = locale && locale !== 'en'\n ? `\\n\\nIMPORTANT: Write the entire resource in ${getLanguageName(locale)}.`\n : '';\n const sourceLanguageInstruction = sourceLanguage\n ? `\\n\\nThe source resource and embedded context are in ${getLanguageName(sourceLanguage)}.`\n : '';\n\n // ── Context sections — switch on the unified GatheredContext focus ─────────\n // Annotation focus drives the annotation + selected-passage sections; resource\n // focus drives a minimal resource anchor (the full grounding — summary,\n // suggestedReferences, content — is YIELD-FROM-RESOURCE Gap B). The graph and\n // semantic sections are shared base, rendered for either focus.\n let annotationSection = '';\n let contextSection = '';\n let resourceSection = '';\n let graphSection = '';\n\n if (context) {\n const { focus } = context;\n // The focal resource's id — equal to the id `buildKnowledgeGraph` (P3) anchored\n // the graph's main node on, so `deriveViews` resolves edges. Read directly off\n // the descriptor (a plain string on the generated type); there is no event id to\n // thread here as the matcher had.\n const mainResourceId =\n focus.kind === 'annotation'\n ? focus.sourceResource['@id']\n : focus.resource['@id'];\n const focalAnnotationId = focus.kind === 'annotation' ? focus.annotation.id : undefined;\n\n if (focus.kind === 'annotation') {\n const parts: string[] = [];\n parts.push(`- Annotation motivation: ${focus.annotation.motivation}`);\n parts.push(`- Source resource: ${focus.sourceResource.name} ${idLabel(mainResourceId)}`);\n // Include body text for commenting/assessing annotations\n const { motivation, body } = focus.annotation;\n if (motivation === 'commenting' || motivation === 'assessing') {\n const bodyItem = Array.isArray(body) ? body[0] : body;\n if (bodyItem && 'value' in bodyItem && bodyItem.value) {\n const label = motivation === 'commenting' ? 'Comment' : 'Assessment';\n parts.push(`- ${label}: ${bodyItem.value}`);\n }\n }\n // The wizard's Hint: supplements or replaces the selected text as the\n // subject signal (GatheredContext.json focus.userHint). The matcher folds\n // it into its search term the same way — the two consumers of one field.\n if (focus.userHint) {\n parts.push(`- User hint (steers what to generate): ${focus.userHint}`);\n }\n annotationSection = `\\n\\nAnnotation context:\\n${parts.join('\\n')}`;\n\n if (focus.selected) {\n const { before, text, after } = focus.selected;\n contextSection = `\\n\\nSource document context:\n---\n${before ? `...${before}` : ''}\n**[${text}]**\n${after ? `${after}...` : ''}\n---\n`;\n }\n } else {\n // Resource focus — ground in the focal resource's summary, suggested\n // references, and content (omit-empty). Content is capped per resource to\n // bound prompt size; the caller already chose breadth via gather.resource.\n const parts = [`- Resource: ${focus.resource.name} ${idLabel(mainResourceId)}`];\n if (focus.summary) parts.push(`- Summary: ${focus.summary}`);\n if (focus.suggestedReferences && focus.suggestedReferences.length > 0) {\n parts.push(`- Suggested references: ${focus.suggestedReferences.join(', ')}`);\n }\n resourceSection = `\\n\\nResource context:\\n${parts.join('\\n')}`;\n\n if (focus.content?.main) {\n resourceSection += `\\n\\nResource content:\\n---\\n${focus.content.main.slice(0, RESOURCE_CONTENT_CAP)}\\n---`;\n }\n const related = Object.entries(focus.content?.related ?? {});\n if (related.length > 0) {\n const blocks = related\n .map(([id, text]) => `[${id}]\\n${text.slice(0, RESOURCE_CONTENT_CAP)}`)\n .join('\\n\\n');\n resourceSection += `\\n\\nRelated resource content:\\n---\\n${blocks}\\n---`;\n }\n }\n\n // Shared base: graph-derived neighborhood (connections / citedBy / siblings)\n // plus the LLM relationship summary, recomputed from the unified graph.\n if (mainResourceId) {\n const views = deriveViews(context.graph, mainResourceId, focalAnnotationId);\n const parts: string[] = [];\n\n if (views.connections.length > 0) {\n const connList = views.connections\n .map(c => `${c.resourceName}${c.entityTypes.length ? ` (${c.entityTypes.join(', ')})` : ''} ${idLabel(c.resourceId)}`)\n .join(', ');\n parts.push(`- Connected resources: ${connList}`);\n }\n\n if (views.citedByCount > 0) {\n const citedNames = views.citedBy.map(c => `${c.resourceName} ${idLabel(c.resourceId)}`).join(', ');\n parts.push(`- This resource is cited by ${views.citedByCount} other resource${views.citedByCount > 1 ? 's' : ''}${citedNames ? `: ${citedNames}` : ''}`);\n }\n\n if (views.siblingEntityTypes.length > 0) {\n parts.push(`- Related entity types in this document: ${views.siblingEntityTypes.join(', ')}`);\n }\n\n if (context.inferredRelationshipSummary) {\n parts.push(`- Relationship summary: ${context.inferredRelationshipSummary}`);\n }\n\n if (parts.length > 0) {\n graphSection = `\\n\\nKnowledge graph context:\\n${parts.join('\\n')}`;\n }\n }\n }\n\n // Build semantic context section if available — the vector matches the gather\n // flow already retrieved for the focal passage, used to ground generation (RAG).\n // Capped and truncated to bound prompt cost (see the named caps above); the\n // gather step pre-filters to ≤10 matches above a 0.5 cosine threshold. Each\n // passage carries its source id so the model can attribute what it uses.\n // See .plans/SEMANTIC-CONTEXT-RAG.md + .plans/CONTEXT-IDENTIFIERS.md.\n let semanticContextSection = '';\n const similar = context?.semanticContext?.similar ?? [];\n if (similar.length > 0) {\n const lines = [...similar]\n .sort((a, b) => b.score - a.score)\n .slice(0, SEMANTIC_MATCH_LIMIT)\n .map(m => `- ${idLabel(m.resourceId, m.annotationId)} (${m.score.toFixed(2)})${m.machineRead ? ' [OCR]' : ''} ${m.text.slice(0, SEMANTIC_MATCH_CHARS)}`);\n // A passage marked [OCR] was recognized from a scanned image, so its\n // wording — and especially its digits — may be misread. Saying so is the\n // whole point of carrying the flag: the model is the only reader of these\n // passages, and it would otherwise quote a scanned figure as confidently\n // as a typed one.\n const ocrNote = similar.some(m => m.machineRead)\n ? '\\nPassages marked [OCR] were read from scanned images by character recognition; treat their exact wording and numbers as uncertain, and say so if you rely on one.'\n : '';\n semanticContextSection = `\\n\\nRelated passages from the knowledge base:\\n${lines.join('\\n')}${ocrNote}`;\n }\n\n // ── Task framing (YIELD-STRUCTURE D1): canonical tasks map to tested framings;\n // an unknown task string is used VERBATIM as the framing instruction (loud\n // degrade — warn, never a silent fallback to 'resource').\n let leadLine: string;\n if (task === 'resource') {\n leadLine = `Generate a concise, informative resource about \"${topic}\".`;\n } else if (task === 'answer') {\n leadLine = `Answer the following question directly and concisely, grounded in the provided context: \"${topic}\"`;\n } else if (task === 'summary') {\n leadLine = `Write a concise summary of \"${topic}\".`;\n } else {\n logger.warn('Unknown task — using it verbatim as the framing instruction', { task });\n leadLine = `${task}\\nTopic: \"${topic}\"`;\n }\n\n // ── Structure directive (YIELD-STRUCTURE D2/D4): emitted ONLY when the caller\n // sets one — unset means no directive at all (the task framing and the model\n // determine shape). Never derived from the token budget: maxTokens is length\n // only. The forced `# Title` heading exists only under canonical 'sections'.\n const isPlainText = outputMediaType === 'text/plain';\n // PDF output means the model authors Typst source (Q1, direct Typst); the\n // worker compiles it. The prompt therefore teaches Typst syntax, and the\n // markdown scaffolding never applies.\n const isPdf = outputMediaType === 'application/pdf';\n let structureRequirement = '';\n let titleRequirement = '';\n if (structure === 'sections') {\n structureRequirement = isPdf\n ? '\\n- Organize the content into titled sections (= Heading) with well-structured paragraphs'\n : isPlainText\n ? '\\n- Organize the content into titled sections with well-structured paragraphs'\n : '\\n- Organize the content into titled sections (## Section) with well-structured paragraphs';\n if (!isPlainText && !isPdf) {\n titleRequirement = '\\n- Start with a clear heading (# Title)';\n }\n } else if (structure === 'prose') {\n structureRequirement = '\\n- Write flowing, well-structured paragraphs with no section headings';\n } else if (structure === 'chat') {\n structureRequirement = '\\n- Structure the content as a conversational chat transcript — a sequence of alternating, speaker-labeled turns (no section headings)';\n } else if (structure) {\n logger.warn('Unknown structure — passing it through as freeform organization guidance', { structure });\n structureRequirement = `\\n- Organize the output as: ${structure}`;\n }\n\n // Citation instruction (INLINE-CITATIONS): ask the model to emit [[<id>]]\n // transport tokens next to each claim, citing only ids the context embedding\n // shows. The worker strips the tokens and reconciles them into linking\n // annotations — they never reach the stored content.\n const citeRequirement = cite\n ? '\\n- Ground every claim in the provided context. Immediately after each claim, cite its source by emitting [[<id>]], where <id> is an id shown in square brackets in the context above (for a passage labeled [abc], emit [[abc]]). Cite only ids that appear in the context.'\n : '';\n\n const formatRequirements = isPdf\n ? `- Write the response as Typst markup (the Typst typesetting language — not markdown, not LaTeX)\n- Headings are written as = Heading (deeper levels == Subheading); everything else is plain prose paragraphs\n- Do not emit markdown syntax or code fences`\n : isPlainText\n ? `- Write the response as plain text — no formatting markup (no #, *, backticks, headings, or links)\n- Begin with the title on its own first line`\n : `- Use markdown formatting\n- Write the response as markdown`;\n\n // Compile-repair context (PDF-GENERATION P3): the previous Typst source\n // failed to compile; the legible compiler diagnostics go back to the model\n // as an authoritative instruction to fix and re-emit the full document.\n const repairSection = repair\n ? `\\n\\nYour previous attempt failed to compile. Fix the error and return the complete corrected document — full source, not a diff.\nCompile error:\n${repair.error}\nPrevious source:\n${repair.source}`\n : '';\n\n // The caller's prompt is an authoritative leading Instruction (YIELD-STRUCTURE D3),\n // not background \"additional context\" — task = what to produce, prompt = how.\n const prompt = `${leadLine}\n${userPrompt ? `Instruction: ${userPrompt}` : ''}${repairSection}\n${entityTypes.length > 0 ? `Focus on these entity types: ${entityTypes.join(', ')}.` : ''}${annotationSection}${contextSection}${resourceSection}${graphSection}${semanticContextSection}${sourceLanguageInstruction}${languageInstruction}\n\nRequirements:\n- Aim for approximately ${finalMaxTokens} tokens of content\n- Be factual and informative${structureRequirement}${titleRequirement}${citeRequirement}\n${formatRequirements}`;\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') || content.startsWith('```typst')) {\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 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 boundedGenerateWithMetadata(client, prompt, finalMaxTokens, finalTemperature, undefined, logger);\n logger.debug('Got response from inference', { responseLength: response.text.length, stopReason: response.stopReason });\n\n const result = parseResponse(response.text);\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 // The provider's stopReason collapses to one protocol-owned bit HERE and\n // nowhere else (GENERATE-FROM-RESOURCE D6): 'max_tokens' means the artifact\n // is cut off, not complete; every other reason is a natural stop.\n return { ...result, truncated: response.stopReason === 'max_tokens' };\n}\n","/**\n * Typst compiler invocation (PDF-GENERATION P3).\n *\n * The model writes Typst source (Q1, settled 2026-08-04: direct Typst); this\n * module turns it into PDF bytes via the pinned binary the worker image ships\n * (P2 — `/usr/local/bin/typst`, v0.15.1, resolved through PATH so tests can\n * substitute a fake). Compile failures return the legible error text — Typst's\n * `file:line:col` + caret diagnostics are the load-bearing input to the bounded\n * repair loop in `processGenerationJob`.\n */\nimport { execFileSync } from 'node:child_process';\nimport { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Every compile pins the PDF creation timestamp. Unpinned compiles of\n * identical source produce different bytes every time (CreationDate/ModDate),\n * which churns the content checksum and makes the Smelter re-embed a document\n * that did not change — the spurious-re-embed failure S11/S12 exist to\n * prevent. The value is arbitrary; its fixity is the point.\n */\nexport const PINNED_CREATION_TIMESTAMP = 1700000000;\n\n/**\n * Model-authored source can fail to compile; the error is fed back for repair\n * a bounded number of times, then the job fails loudly with the compiler's\n * diagnostics. Bounded because generation is non-idempotent and paid per\n * attempt — this is a repair loop, not a retry loop.\n */\nexport const MAX_COMPILE_REPAIRS = 2;\n\nexport function compileTypst(source: string): { pdf: Uint8Array } | { error: string } {\n const dir = mkdtempSync(join(tmpdir(), 'typst-'));\n try {\n const inFile = join(dir, 'doc.typ');\n const outFile = join(dir, 'doc.pdf');\n writeFileSync(inFile, source);\n try {\n execFileSync(\n 'typst',\n ['compile', '--creation-timestamp', String(PINNED_CREATION_TIMESTAMP), inFile, outFile],\n { stdio: ['ignore', 'pipe', 'pipe'] },\n );\n } catch (err) {\n const stderr = (err as { stderr?: Buffer }).stderr;\n return { error: stderr?.length ? stderr.toString('utf8') : String(err) };\n }\n return { pdf: new Uint8Array(readFileSync(outFile)) };\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Citation-token resolver (INLINE-CITATIONS P1).\n *\n * Under `cite`, the generation prompt asks the model to emit `[[<resourceId>]]` /\n * `[[<resourceId>/<annotationId>]]` transport tokens after each claim, citing ids\n * the context embedding put in front of it (CONTEXT-IDENTIFIERS). Tokens are\n * TRANSPORT, not content: this resolver parses them, validates each id against the\n * ids actually present in the embedded context (the hallucination guard — an\n * unknown id is dropped loudly, never silently linked), STRIPS them from the\n * content before upload, and returns claim-span citations the worker mints as W3C\n * linking annotations on the derived resource. See .plans/INLINE-CITATIONS.md.\n */\nimport type { GatheredContext, Logger } from '@semiont/core';\n\nexport interface GenerationCitation {\n /** The cited source resource (validated present in the embedded context). */\n resourceId: string;\n /** The contributing annotation, when the cited excerpt was annotation-derived. */\n annotationId?: string;\n /** Claim span in the FINAL (token-stripped) content; substring(start, end) === exact. */\n start: number;\n end: number;\n exact: string;\n}\n\n/** `[[rid]]` or `[[rid/annId]]` — ids are bare (no whitespace, brackets, or slashes). */\nconst CITATION_TOKEN = /\\[\\[([^\\s[\\]/]+)(?:\\/([^\\s[\\]/]+))?\\]\\]/g;\n\n/**\n * The ids the context embedding actually put in front of the model — the\n * hallucination guard's ground truth. Mirrors what the prompt renderers label:\n * the focal resource, graph resource nodes, semantic matches, related content.\n */\nexport function collectContextResourceIds(context: GatheredContext | undefined): Set<string> {\n const ids = new Set<string>();\n if (!context) return ids;\n\n const { focus } = context;\n ids.add(focus.kind === 'annotation' ? focus.sourceResource['@id'] : focus.resource['@id']);\n for (const node of context.graph.nodes) {\n if (node.type === 'resource') ids.add(node.id);\n }\n for (const m of context.semanticContext?.similar ?? []) ids.add(m.resourceId);\n if (focus.kind === 'resource') {\n for (const id of Object.keys(focus.content?.related ?? {})) ids.add(id);\n }\n return ids;\n}\n\nexport function resolveCitationTokens(\n content: string,\n validResourceIds: ReadonlySet<string>,\n logger: Logger,\n): { content: string; citations: GenerationCitation[] } {\n const citations: GenerationCitation[] = [];\n let clean = '';\n let last = 0;\n\n for (const match of content.matchAll(CITATION_TOKEN)) {\n const token = match[0];\n const citedResourceId = match[1]!;\n const annotationId = match[2];\n\n // Append the text before the token, dropping the whitespace run immediately\n // preceding it so stripping never leaves a dangling space.\n clean += content.slice(last, match.index).replace(/[ \\t]+$/, '');\n last = match.index! + token.length;\n\n if (!validResourceIds.has(citedResourceId)) {\n logger.warn('Citation token references an id absent from the provided context — dropped', {\n resourceId: citedResourceId,\n });\n continue;\n }\n\n // Claim span: the sentence preceding the token, computed against the clean\n // content. Offsets are final — later appends never shift earlier positions.\n const end = clean.length;\n let start = 0;\n for (let i = end - 2; i >= 0; i--) {\n const ch = clean[i];\n if (ch === '.' || ch === '!' || ch === '?' || ch === '\\n') {\n start = i + 1;\n break;\n }\n }\n while (start < end && /\\s/.test(clean[start]!)) start++;\n const exact = clean.slice(start, end);\n if (exact.length === 0) {\n logger.warn('Citation token has no preceding claim text — dropped', {\n resourceId: citedResourceId,\n });\n continue;\n }\n\n citations.push({\n resourceId: citedResourceId,\n ...(annotationId ? { annotationId } : {}),\n start,\n end,\n exact,\n });\n }\n\n clean += content.slice(last);\n return { content: clean, citations };\n}\n","/**\n * Run `worker` over `items` with at most `limit` of them in flight at once\n * (DETECTION-QUALITY-THROUGHPUT P6). Hand-rolled rather than a dependency: the\n * need is exactly one bounded map, and the BOUND is the whole point — detection\n * parallelizes independent entity types, but unbounded fan-out just trades\n * sequential waiting for provider 429 thrash, so the cap is the feature.\n *\n * A fixed pool of `min(limit, items.length)` pumps, each pulling the next index\n * until the work is exhausted — so at most `limit` calls are ever awaiting at\n * once, whatever the item count. Results are returned in INPUT order (a caller\n * can zip them back to items); COMPLETION order is not input order — that is the\n * point of concurrency — so a caller that must act \"as each finishes\" does so\n * inside `worker`, not on the returned array.\n *\n * Failure matches the sequential loop it replaces: the first `worker` rejection\n * rejects the whole run. Pumps already awaiting finish (they cannot be\n * cancelled mid-await), but no new item is pulled once a rejection propagates.\n */\nexport async function runBounded<T, R>(\n items: readonly T[],\n limit: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n\n async function pump(): Promise<void> {\n while (true) {\n const i = next++;\n if (i >= items.length) return;\n results[i] = await worker(items[i]!, i);\n }\n }\n\n const poolSize = Math.max(1, Math.min(limit, items.length));\n await Promise.all(Array.from({ length: poolSize }, () => pump()));\n return results;\n}\n","/**\n * Job Processors\n *\n * Pure functions that take content + inference client + params,\n * report progress via callback, and return annotations + results.\n *\n * No EventBus, no JobQueue, no side effects except calling inference.\n * Driven by the remote worker process (worker-process.ts), which claims\n * jobs over SSE and dispatches by jobType to these functions.\n */\n\nimport { AnnotationDetection } from './workers/annotation-detection';\nimport { extractEntities } from './workers/detection/entity-extractor';\nimport { DEFAULT_MAX_TOKENS, generateResourceFromTopic } from './workers/generation/resource-generation';\nimport { compileTypst, MAX_COMPILE_REPAIRS } from './workers/generation/typst-compiler';\nimport { withinByteBudget, MAX_PDF_BYTES } from '@semiont/content';\nimport { resolveCitationTokens, collectContextResourceIds, type GenerationCitation } from './workers/generation/citation-resolver';\nimport { annotationIdFor } from '@semiont/event-sourcing';\nimport { GENERATABLE_MEDIA_TYPES, type Annotation, type GenerationJobParams, type Logger, type ResourceId, type SupportedMediaType, type components, type JobReferenceAnnotationResult, type JobHighlightAnnotationResult, type JobCommentAnnotationResult, type JobAssessmentAnnotationResult, type JobTagAnnotationResult, type UnitCursor } from '@semiont/core';\nimport { reconcileSelector, createFragmentSelector, locate, type ReconciledSelector, type AnchoredText } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\nimport type {\n HighlightDetectionParams,\n CommentDetectionParams,\n AssessmentDetectionParams,\n DetectionParams,\n TagDetectionParams,\n GenerationResult,\n} from './types';\nimport { noteAnchor } from './workers/detection/anchor-audit';\nimport { runBounded } from './workers/detection/bounded-concurrency';\n\ntype Agent = components['schemas']['Agent'];\n\n/** A detected span — offsets into the extracted `.text`, plus optional context. */\nexport type SpanMatch = { exact: string; start: number; end: number; prefix?: string; suffix?: string };\n\n/**\n * The span half of an annotation's identity (JOB-RESTART-SAFETY P3).\n *\n * Shared by both builders because the span IS the same fact in both — the PDF\n * path additionally persists geometry for it, but that geometry is derived\n * from these offsets, so hashing it too would add no distinguishing power and\n * would make an id depend on a layout the text path cannot reproduce.\n *\n * `exact` is included, not just the offsets: after a content update the same\n * offsets cover different text, and that is a different annotation.\n */\nfunction spanAnchor(match: Pick<SpanMatch, 'start' | 'end' | 'exact'>): string {\n return `${match.start}:${match.end}:${match.exact}`;\n}\n\n/**\n * Turn a detected span into a stored annotation. The media type, resource, and\n * attribution context are closed over by the caller (see `prepareDetection`);\n * the detection processor supplies only the motivation, the span, and any\n * motivation-specific body. This is the single axis that varies by media type,\n * so the detection processors themselves stay media-agnostic.\n */\nexport type BuildAnnotation = (\n motivation: Motivation,\n match: SpanMatch,\n body?: Annotation['body'],\n) => Annotation;\n\n/**\n * Progress callback. The two positional args are the required `JobProgress`\n * fields (`percentage`, `message`). The third optional arg carries the\n * job-type-specific fields (`completedEntityTypes`, `requestParams`, etc.)\n * that the progress UI renders.\n *\n * Anything in `extra` describing the RUN rather than the moment must be passed\n * on EVERY call: the client's `progress$` replaces its value per event, so a\n * field sent once disappears on the next tick.\n *\n * `message` is a CODE plus typed params, never a prose sentence\n * (ASSIST-PROGRESS-CONSOLIDATION A6). The producer reports what happened;\n * each client renders it in the user's language — react-ui from its 29\n * locales, the Go launcher from its English map. The vocabulary is frozen\n * by the census of these call sites: adding a shape means adding a variant\n * to `JobProgressMessage.json` and copy in every client, not composing a\n * new sentence here.\n */\nexport type OnProgress = (\n percentage: number,\n message: JobProgressMessage,\n extra?: Partial<JobProgress>,\n) => void;\n\ntype JobProgress = components['schemas']['JobProgress'];\n/** Derived from the wire, never restated: the per-unit entry's shape is the\n * spec's, so a field added there reaches these accumulators by regeneration\n * rather than by someone remembering two places. */\ntype CompletedItem = NonNullable<JobProgress['completedItems']>[number];\ntype JobProgressMessage = components['schemas']['JobProgressMessage'];\n\n/** The five W3C motivations this system mints — a closed vocabulary, so it is\n * typed as one rather than as `string`. */\nexport type Motivation = Annotation['motivation'];\n\n/**\n * A detection processor returns only its result. Annotations leave through\n * `onChunkComplete`, per chunk — a return that also carried them would be a\n * second path to the same write.\n */\nexport interface ProcessorResult<R> {\n result: R;\n}\n\n/**\n * Strip the audit-only fields (`anchorMethod`, `llmOffsets`, `matchQuality`)\n * off a `ReconciledSelector` so the rest is shaped like a match input for\n * `buildTextAnnotation`. The audit info belongs in logs, not in storage.\n */\nfunction toMatch(r: ReconciledSelector): { exact: string; start: number; end: number; prefix?: string; suffix?: string } {\n return {\n exact: r.exact,\n start: r.start,\n end: r.end,\n ...(r.prefix !== undefined ? { prefix: r.prefix } : {}),\n ...(r.suffix !== undefined ? { suffix: r.suffix } : {}),\n };\n}\n\n/**\n * Identity key for a built annotation: motivation + anchored span + body.\n * Two annotations with the same key are the same event written twice.\n */\nfunction annotationDedupeKey(ann: Record<string, unknown>): string {\n const target = ann.target as\n | { selector?: Array<{ type: string; start?: number; end?: number; value?: string; exact?: string; prefix?: string; suffix?: string }> }\n | undefined;\n const selectors = Array.isArray(target?.selector) ? target.selector : [];\n const pos = selectors.find((s) => s.type === 'TextPositionSelector');\n // Anchor identity is media-specific. Text annotations carry a\n // TextPositionSelector (durable char offsets). PDF annotations have none —\n // their anchor is the per-line FragmentSelector viewrect geometry plus the\n // TextQuoteSelector text. Keying only on TextPositionSelector would collapse\n // every PDF annotation sharing a motivation+body onto one (its offsets fall\n // back to '?'), so e.g. multiple PDF highlights emit as a single annotation.\n let anchor: string;\n if (pos) {\n anchor = `pos:${pos.start ?? '?'}:${pos.end ?? '?'}`;\n } else {\n const frags = selectors.filter((s) => s.type === 'FragmentSelector').map((s) => s.value ?? '').join(',');\n const quote = selectors.find((s) => s.type === 'TextQuoteSelector');\n anchor = `frag:${frags}|quote:${quote?.exact ?? ''}:${quote?.prefix ?? ''}:${quote?.suffix ?? ''}`;\n }\n return [ann.motivation as string, anchor, JSON.stringify(ann.body ?? null)].join('|');\n}\n\n/**\n * Drop annotations that are identical in the fields that define an\n * annotation's meaning: motivation, anchored span, and body.\n *\n * Why this is needed: each LLM-emitted span is reconciled independently\n * (no cross-entry coordination), and `reconcileSelector`'s `first-of-many`\n * fallback anchors every undisambiguated entry at the *same* first\n * occurrence. So a phrase repeated in non-distinctive context can produce\n * several entries that all collapse onto one span — identical events. This\n * collapses them back to one.\n *\n * What it does NOT drop: same span, *different* body (e.g. the same text\n * tagged as two entity types, or two distinct comments on one passage).\n * Those are legitimately distinct annotations.\n *\n * Applied identically by every processor below.\n */\n/**\n * THE dedupe decider — one mechanism for all five detection types, held\n * across a stream of chunk batches: adjacent chunks overlap, so the same\n * span arrives twice, and there is no post-pass to collapse it in. Scope it\n * to one emission stream — per unit for reference detection, per job for the\n * four motivations. Never add a batch post-pass beside it (gated).\n */\nfunction makeSpanDeduper(): (annotations: Annotation[]) => Annotation[] {\n const seen = new Set<string>();\n return (annotations) => {\n const out: Annotation[] = [];\n for (const ann of annotations) {\n const key = annotationDedupeKey(ann);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(ann);\n }\n return out;\n };\n}\n\nexport function buildTextAnnotation(\n content: string,\n resourceId: ResourceId,\n generator: Agent,\n motivation: Motivation,\n match: { exact: string; start: number; end: number; prefix?: string; suffix?: string },\n // Body may be a single AnnotationBody object or a non-empty array of\n // them, OR omitted entirely. W3C treats body as optional; annotations\n // whose motivation alone conveys meaning (highlighting) legitimately\n // skip it. Every other motivation currently passes something; the\n // processor that calls this makes the choice per-motivation.\n body?: Annotation['body'],\n) {\n // Write-time invariant. Every selector that reaches storage must be\n // internally consistent with the source content. If a worker bypasses\n // `reconcileSelector` or a future change re-introduces overlap, the\n // throw fires loudly here instead of corrupting the KB.\n if (content.substring(match.start, match.end) !== match.exact) {\n throw new Error(\n `buildTextAnnotation invariant: content.substring(${match.start}, ${match.end}) !== exact ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n if (match.prefix !== undefined) {\n const actualPrefix = content.substring(Math.max(0, match.start - match.prefix.length), match.start);\n if (actualPrefix !== match.prefix) {\n throw new Error(\n `buildTextAnnotation invariant: content prefix-slice !== prefix ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n }\n if (match.suffix !== undefined) {\n const actualSuffix = content.substring(match.end, Math.min(content.length, match.end + match.suffix.length));\n if (actualSuffix !== match.suffix) {\n throw new Error(\n `buildTextAnnotation invariant: content suffix-slice !== suffix ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n }\n\n // The worker says WHAT produced this — `generator`, which carries the\n // model's parameters — and nothing about who asked. `creator` and\n // `wasAttributedTo` are derived by the Stower from the cited job's own\n // events (VERIFIED-PROVENANCE P2); a payload carrying them is refused.\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationIdFor({ resourceId: resourceId as string, motivation, anchor: spanAnchor(match), body }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: {\n type: 'SpecificResource' as const,\n source: resourceId as string,\n selector: [\n { type: 'TextPositionSelector' as const, start: match.start, end: match.end },\n {\n type: 'TextQuoteSelector' as const,\n exact: match.exact,\n ...(match.prefix && { prefix: match.prefix }),\n ...(match.suffix && { suffix: match.suffix }),\n },\n ],\n },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * PDF sibling of `buildTextAnnotation`. The model returns the same\n * `{ exact, start, end, prefix?, suffix? }` match over the extracted text\n * layer's `text`; geometry comes from the layer, never the model.\n *\n * `target.selector` = one `FragmentSelector` per line (`locate` unions the\n * overlapping text-layer items into per-line viewrects) plus a\n * `TextQuoteSelector` anchor. No `TextPositionSelector`: the extracted text\n * layer is a derived artifact, not the stored content, so its char offsets are\n * not a durable anchor.\n *\n * **And the `id` is hashed over exactly those offsets** — `annotationIdFor` gets\n * `spanAnchor(match)`, i.e. `${start}:${end}:${exact}`. That is worth stating\n * plainly, because it sits in tension with the paragraph above: identity here\n * depends on something the annotation refuses to store, on the grounds that it is\n * not durable. The consequence is not a corrupt write but an invisible one — an\n * extraction that moved would re-identify the same visual span, and the two\n * annotations would agree in every stored field (same rects, same quoted text) and\n * differ only in `id`, so every dedupe layer would correctly let both through.\n *\n * It is left as it is on evidence, not by oversight. The offsets come from a\n * derivation cached per content checksum and gated by a stamp that a release of\n * `@semiont/content`, the PDF engine or its traineddata busts by design; measured\n * across the caret-reachable engine move (pdfjs 6.2.108 → 6.3.289) over 1,192 pages\n * of real documents, they did not move, and `pdf-offset-stability.test.ts` in\n * `@semiont/content` now fails if they ever do. The OCR path is unmeasured, and a\n * scanned document takes its whole text from there. If that gate ever fires, this\n * is the line to revisit: hashing the DURABLE anchor instead (page geometry plus\n * `exact`) makes identity depend only on what the annotation carries — at the cost\n * of one round of new ids for every PDF annotation minted afterwards.\n *\n * Write-time invariant (geometry <-> text): geometry is item-level (word runs),\n * so the covered items' text must *contain* `exact` (whitespace-normalized) —\n * containment, not reconstruction. An empty cover (no overlapping items -> no\n * rects) also fails. Throws loudly, naming the resource + motivation, rather\n * than persisting geometry that doesn't back the quoted text.\n */\nexport function buildPdfAnnotation(\n anchored: AnchoredText,\n resourceId: ResourceId,\n generator: Agent,\n motivation: Motivation,\n match: { exact: string; start: number; end: number; prefix?: string; suffix?: string },\n body?: Annotation['body'],\n) {\n // `locate` returns both the per-line rects and the overlap items it found;\n // reuse `overlap` for the containment check rather than re-scanning layer.items.\n const { rects, overlap } = locate(anchored, match.start, match.end);\n\n const coveredText = overlap.length\n ? anchored.text.substring(\n Math.min(...overlap.map((i) => i.start)),\n Math.max(...overlap.map((i) => i.end)),\n )\n : '';\n const normalize = (s: string) => s.replace(/\\s+/g, ' ').trim();\n // Two distinct failures, reported distinctly. Merged, both printed \"covered\n // text does not contain exact\" — which sends anyone debugging an empty cover\n // to inspect text matching that never ran. Same class deliberately: both stay\n // plain `Error`, so `classifyFailure` leaves them unrecognized and therefore\n // retryable (ABANDONED-INFERENCE HD2 is one-sided — only KNOWN-deterministic\n // failures skip the budget). No rects LOOKS deterministic, but the stored map\n // is keyed by content checksum, so a retry after the bytes change reads a\n // different map and can legitimately succeed.\n if (rects.length === 0) {\n throw new Error(\n `buildPdfAnnotation invariant: no rects located for offsets ${match.start}-${match.end} ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n if (!normalize(coveredText).includes(normalize(match.exact))) {\n throw new Error(\n `buildPdfAnnotation invariant: covered text does not contain exact ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n\n // As for the text builder: `generator` only; attribution is derived downstream.\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationIdFor({ resourceId: resourceId as string, motivation, anchor: spanAnchor(match), body }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: {\n type: 'SpecificResource' as const,\n source: resourceId as string,\n selector: [\n ...rects.map((coord) => ({\n type: 'FragmentSelector' as const,\n conformsTo: 'http://tools.ietf.org/rfc/rfc3778' as const,\n value: createFragmentSelector(coord),\n })),\n {\n type: 'TextQuoteSelector' as const,\n exact: match.exact,\n ...(match.prefix && { prefix: match.prefix }),\n ...(match.suffix && { suffix: match.suffix }),\n },\n ],\n },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * Where one unit stands once the chunk just handed over is durable\n * (CHUNK-GRAIN-RESUME P2).\n *\n * The unit is named HERE rather than in the detection layer, which knows about\n * chunks and nothing about jobs: for `reference-annotation` a unit is an entity\n * type, for `tag-annotation` a category — both loop over several — and for the\n * other three the job runs exactly one unit, its own motivation.\n */\nexport interface UnitCheckpoint {\n unit: string;\n cursor: UnitCursor;\n}\n\nexport async function processHighlightJob(\n content: string,\n inferenceClient: InferenceClient,\n params: HighlightDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobHighlightAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['highlighting'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectHighlights(\n content, inferenceClient, params.instructions, params.density, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['highlighting'],\n async (matches, cursor) => {\n found += matches.length;\n // Highlights carry no body — motivation:'highlighting' on a target\n // is a complete annotation per the W3C Web Annotation Model.\n const fresh = dedupe(matches.map((h) => buildAnnotation('highlighting', h)));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n // One motivation per job, so exactly one unit — and with only one, a\n // unit-grain checkpoint could record nothing until the whole document\n // was done. The cursor is the entire resume story for these three types.\n await onChunkComplete(fresh, { unit: 'highlighting', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'highlight' }, echo);\n\n return {\n result: { kind: 'highlight-annotation', highlightsFound: found, highlightsCreated: created },\n };\n}\n\n/**\n * The user's own inputs, echoed back for the progress widget. Labels are CODES\n * (the client localizes them); values are the user's words and are shown\n * verbatim. Absent or blank inputs are omitted rather than rendered as empty\n * rows — \"Instructions:\" with nothing after it is noise, not information.\n *\n * Returned as the `extra` object rather than a bare array because every\n * `onProgress` in the run passes it: `progress$` REPLACES its value per event\n * (mark-state-unit), so a field sent once would flash at 10% and disappear.\n * The parameters describe the whole run, so every event carries them — the\n * same convention `processReferenceJob` already follows for its entity types.\n */\nfunction detectionEcho(p: {\n instructions?: string;\n tone?: string;\n density?: number;\n}): Partial<JobProgress> {\n const requestParams: Array<{ label: 'instructions' | 'tone' | 'density'; value: string }> = [];\n if (p.instructions?.trim()) requestParams.push({ label: 'instructions', value: p.instructions.trim() });\n if (p.tone?.trim()) requestParams.push({ label: 'tone', value: p.tone.trim() });\n if (p.density !== undefined) requestParams.push({ label: 'density', value: String(p.density) });\n return requestParams.length > 0 ? { requestParams } : {};\n}\n\nexport async function processCommentJob(\n content: string,\n inferenceClient: InferenceClient,\n params: CommentDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobCommentAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n // The body's `language` reflects the locale the LLM was asked to write in\n // (`params.language` — the user's UI locale). Defaults to 'en' when the\n // caller didn't specify, matching what the LLM produces by default.\n const bodyLanguage = params.language ?? 'en';\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['commenting'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectComments(\n content, inferenceClient, params.instructions, params.tone, params.density,\n params.language, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['commenting'],\n async (comments, cursor) => {\n found += comments.length;\n const fresh = dedupe(comments.map((c) =>\n // Match the pre-#651 CommentAnnotationWorker: include format and\n // language on the body TextualBody. Optional in the schema, but\n // consumers that do language-aware rendering rely on them.\n buildAnnotation('commenting', c, [\n { type: 'TextualBody', value: c.comment, purpose: 'commenting', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n ]),\n ));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n await onChunkComplete(fresh, { unit: 'commenting', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'comment' }, echo);\n\n return {\n result: { kind: 'comment-annotation', commentsFound: found, commentsCreated: created },\n };\n}\n\nexport async function processAssessmentJob(\n content: string,\n inferenceClient: InferenceClient,\n params: AssessmentDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobAssessmentAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n const bodyLanguage = params.language ?? 'en';\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['assessing'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectAssessments(\n content, inferenceClient, params.instructions, params.tone, params.density,\n params.language, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['assessing'],\n async (assessments, cursor) => {\n found += assessments.length;\n const fresh = dedupe(assessments.map((a) =>\n // Single-object body with purpose aligned to motivation, matching the\n // pre-#651 AssessmentAnnotationWorker's shape and the majority of\n // persisted assessments. Do not switch to an array or to\n // purpose='describing' — that loses the \"this is an assessment, not\n // a description\" signal and breaks existing readers that access\n // `body.value` directly on the object.\n buildAnnotation('assessing', a, {\n type: 'TextualBody', value: a.assessment, purpose: 'assessing', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage,\n }),\n ));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n await onChunkComplete(fresh, { unit: 'assessing', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'assessment' }, echo);\n\n return {\n result: { kind: 'assessment-annotation', assessmentsFound: found, assessmentsCreated: created },\n };\n}\n\n/**\n * Reference detection commits per UNIT — one entity type — through\n * `onUnitComplete` (ABANDONED-INFERENCE P2, checkpointed resume): the\n * callback receives the unit's deduped annotations, and only after it\n * resolves does the unit count as complete. Emission belongs to the\n * callback alone; the processor returns only the result — returning the\n * annotations as well would recreate the post-run batch that N2 showed\n * discards completed work wholesale.\n */\nexport async function processReferenceJob(\n content: string,\n inferenceClient: InferenceClient,\n params: DetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n logger: Logger,\n /**\n * The CHECKPOINT, fired once per unit after every one of its chunks has\n * committed. It carries no annotations — the effect already happened per\n * chunk through `onChunkComplete`, and a unit callback that also carried\n * them would be a second commit path.\n */\n onUnitComplete: (entityType: string) => Promise<void>,\n signal?: AbortSignal,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete?: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each entity-type unit (CHUNK-GRAIN-RESUME P3).\n * A unit absent here starts at the top; units already COMPLETE never reach\n * this function at all, the caller having filtered them out. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<{ result: JobReferenceAnnotationResult }> {\n const entityTypeNames = params.entityTypes.map(String);\n const requestParams = [{ label: 'entity-types' as const, value: entityTypeNames.join(', ') }];\n const completedItems: CompletedItem[] = [];\n // Seeded with what earlier attempts already counted for the units this\n // attempt is RESUMING. Units that completed earlier carry no cursor — they\n // are filtered out before this function sees them — so their share is still\n // missing from the job total. That is the pre-existing unit-grain gap, named\n // in CHUNK-GRAIN-RESUME rather than silently half-fixed here.\n let totalFound = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.found, 0);\n let totalEmitted = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.emitted, 0);\n let errors = 0;\n let totalUnderReportedPieces = 0;\n // The denominator: cumulative count-verifier expectations over accepted\n // pieces. Zero means no piece was priced — the frame then carries nothing.\n let totalExpected = 0;\n\n onProgress(10, { code: 'loading' }, { requestParams });\n\n const bodyLanguage = params.language ?? 'en';\n\n // Entity types run BOUNDED-CONCURRENT (DETECTION-QUALITY-THROUGHPUT P6).\n // They are independent units — own extraction, own commit, own checkpoint —\n // and a single sequential job used a sliver of the provider's rate limit, so\n // the old `for … await` was the 9×-sequential ≈ 2.5 h/document. The bound is\n // the point: unbounded fan-out just trades sequential waiting for 429 thrash.\n //\n // Shared counters and `completedItems` are mutated SYNCHRONOUSLY between\n // awaits inside the worker — safe under the single-threaded event loop (no\n // read-modify-write straddles an await), so no locking is needed. Progress is\n // now \"M of N done\" rather than \"on type i\": concurrent types finish out of\n // order, and `completedItems` already tolerates that.\n let completed = 0;\n const total = entityTypeNames.length;\n\n const emitTypeProgress = (entityTypeName: string): void => {\n const pct = 20 + Math.round((completed / total) * 60);\n onProgress(pct, { code: 'detecting-entities', entityType: entityTypeName }, {\n current: { kind: 'entity-type', value: entityTypeName },\n processed: completed,\n total,\n entitiesFound: totalFound,\n ...(totalExpected > 0 ? { entitiesExpected: totalExpected } : {}),\n entitiesEmitted: totalEmitted,\n completedItems: [...completedItems],\n requestParams,\n });\n };\n\n // Concurrency is the PROVIDER's capability, not a flat constant: a hosted\n // API parallelizes, a local single-model server does not (P6). Reading it\n // from the client is what makes the same code correct on both.\n await runBounded(entityTypeNames, inferenceClient.maxConcurrency, async (entityTypeName) => {\n if (!entityTypeName) return;\n // Cooperative cancellation (JOB-RESTART-SAFETY P4): once aborted, a pending\n // type is skipped when its turn comes; types already in flight finish and\n // commit, so committed units stay checkpointed. The caller reads\n // `signal.aborted` to move the job to cancelled/ rather than complete/.\n if (signal?.aborted) return;\n\n emitTypeProgress(entityTypeName);\n\n // Unresolved reference body: the entity type as a tagging TextualBody,\n // stamped with the body locale to match the comment/assess/tag pattern.\n // The bind flow later appends a SpecificResource (purpose: 'linking') via\n // mark:body-updated to produce the resolved shape. Emitting an empty body\n // would break the append contract.\n const unresolvedBody: Annotation['body'] = [\n { type: 'TextualBody' as const, value: entityTypeName, purpose: 'tagging' as const, format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n ];\n\n // One deduper per unit, held across its chunks.\n const dedupe = makeSpanDeduper();\n // Seeded from what earlier attempts already counted for THIS unit, so the\n // terminal record describes the document rather than the remainder this\n // attempt happened to run. Absent (a first attempt) means zero, which is\n // the truth rather than a default.\n const priorUnit = resumeCursors?.[entityTypeName];\n let unitFound = priorUnit?.found ?? 0;\n let unitPersisted = priorUnit?.emitted ?? 0;\n // What remains unknown at the unit's end: floor-accepted pieces, folded.\n let underReported: { pieces: number; found: number; counted: number } | undefined;\n await extractEntities(\n content, [entityTypeName], inferenceClient, params.includeDescriptiveReferences ?? false, logger,\n params.sourceLanguage,\n // Liveness heartbeat (DETECTION-HEARTBEAT): fires at chunk boundaries and\n // every ~15 s while a call is in flight, so a long single-chunk call is\n // not silent. It repeats the current position rather than inventing an\n // advance — the stall watchdog, janitor and client timeout need a signal,\n // not a monotone.\n () => emitTypeProgress(entityTypeName),\n (verdict) => {\n underReported = {\n pieces: (underReported?.pieces ?? 0) + 1,\n found: (underReported?.found ?? 0) + verdict.found,\n counted: (underReported?.counted ?? 0) + verdict.counted,\n };\n },\n (counted) => {\n totalExpected += counted;\n emitTypeProgress(entityTypeName);\n },\n resumeCursors?.[entityTypeName],\n async (chunkEntities, cursor) => {\n const built: Annotation[] = [];\n for (const entity of chunkEntities) {\n const reconciled = reconcileSelector(content, {\n exact: entity.exact,\n ...(entity.prefix !== undefined ? { prefix: entity.prefix } : {}),\n ...(entity.suffix !== undefined ? { suffix: entity.suffix } : {}),\n });\n if (!reconciled) {\n logger.error('Entity dropped — text not found in source', {\n text: entity.exact,\n entityType: entity.entityType,\n });\n errors++;\n continue;\n }\n noteAnchor('reference', entity.exact, reconciled.anchorMethod, logger);\n built.push(buildAnnotation('linking', toMatch(reconciled), unresolvedBody));\n }\n const fresh = dedupe(built);\n // What this chunk makes true ONCE IT IS DURABLE. Computed before the\n // commit because the checkpoint is written inside it and has to carry\n // the running totals — a checkpoint reporting only this attempt's share\n // would reset the count on every death — but assigned after, so the\n // invariant below still holds.\n const nextFound = unitFound + chunkEntities.length;\n const nextEmitted = unitPersisted + fresh.length;\n // Awaited: a failed commit fails the unit before it can checkpoint;\n // the cursor rides with it so the checkpoint trails the log by\n // construction rather than by the caller remembering to order them.\n await onChunkComplete?.(fresh, {\n unit: entityTypeName,\n cursor: { ...cursor, found: nextFound, emitted: nextEmitted },\n });\n // Tallies move only PAST the awaited commit — a chunk that fails to\n // commit contributes nothing anywhere — and the numerator advances at\n // the same grain as the denominator: per chunk, in the same frame\n // family the viewer's found-of-~expected tally reads.\n unitFound = nextFound;\n unitPersisted = nextEmitted;\n totalFound += chunkEntities.length;\n totalEmitted += fresh.length;\n emitTypeProgress(entityTypeName);\n },\n );\n\n // Every chunk of this unit is durable; only now may it checkpoint.\n await onUnitComplete(entityTypeName);\n // Found vs persisted, per unit — the gap between them is this flow's yield.\n completedItems.push({\n value: entityTypeName,\n foundCount: unitFound,\n persistedCount: unitPersisted,\n ...(underReported ? { underReported } : {}),\n });\n if (underReported) totalUnderReportedPieces += underReported.pieces;\n completed++;\n emitTypeProgress(entityTypeName);\n });\n\n // The terminal frame carries the completed set, and it is the only frame\n // that can: the per-unit entries ride the progress emitted at the START of\n // each unit, so the LAST unit's entry — and on a single-type job, every\n // entry — was never reported anywhere (DETECTION-QUALITY-THROUGHPUT P1).\n onProgress(100, { code: 'complete-created', count: totalEmitted, kind: 'reference' }, {\n ...(totalExpected > 0 ? { entitiesExpected: totalExpected } : {}),\n completedItems: [...completedItems],\n requestParams,\n });\n\n return {\n result: {\n kind: 'reference-annotation', totalFound, totalEmitted, errors,\n ...(totalUnderReportedPieces > 0 ? { underReportedPieces: totalUnderReportedPieces } : {}),\n },\n };\n}\n\nexport async function processTagJob(\n content: string,\n inferenceClient: InferenceClient,\n params: TagDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each CATEGORY (CHUNK-GRAIN-RESUME P3) — a tag\n * job's units are its categories, not its motivation: each walks the whole\n * document, so one shared cursor would skip text for all but one of them. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobTagAnnotationResult>> {\n onProgress(10, { code: 'loading' });\n onProgress(30, { code: 'analyzing-tags' });\n\n const bodyLanguage = params.language ?? 'en';\n // One deduper across every category: they share an emission stream, and\n // the key includes the body, so only true repeats collapse.\n const dedupe = makeSpanDeduper();\n // Resumed tallies (CHUNK-GRAIN-RESUME HD3), and the two are seeded\n // DIFFERENTLY because they accumulate differently. `found` sums each\n // category's own running total at the end of that category, and those totals\n // are already seeded — seeding here too would count the earlier attempt\n // twice. `created` accumulates per chunk from this attempt only, so it must\n // start at what earlier attempts committed.\n let found = 0;\n let created = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.emitted, 0);\n // byCategory counts the DEDUPED set so the per-category counts match what\n // is actually stored. The category is the first (tagging) TextualBody.\n const byCategory: Record<string, number> = {};\n const completedItems: CompletedItem[] = [];\n\n for (let c = 0; c < params.categories.length; c++) {\n const category = params.categories[c]!;\n // The loop always existed; it just never reported itself, so the tag flow\n // was the one counting flow with no subject line (CLEAN-PROGRESS A5).\n const position = () => ({\n current: { kind: 'category' as const, value: category },\n processed: c,\n total: params.categories.length,\n completedItems: [...completedItems],\n });\n onProgress(\n 30 + Math.round((c / params.categories.length) * 30),\n { code: 'analyzing-tags' },\n position(),\n );\n // This category's own running tallies, seeded from its cursor so the\n // checkpoint it writes stays continuable for a third attempt.\n const priorCategory = resumeCursors?.[category];\n let categoryFound = priorCategory?.found ?? 0;\n let categoryCreated = priorCategory?.emitted ?? 0;\n await AnnotationDetection.detectTags(\n content, inferenceClient, params.schema, category, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): this category's\n // slice of the 30–60 band.\n (consumedChars, totalChars) => onProgress(\n 30 + Math.round(((c + consumedChars / totalChars) / params.categories.length) * 30),\n { code: 'analyzing-tags' },\n position(),\n ),\n resumeCursors?.[category],\n async (matches, cursor) => {\n categoryFound += matches.length;\n const fresh = dedupe(matches.map((t) => {\n const cat = t.category ?? 'unknown';\n // Two-body shape matches the pre-#651 TagAnnotationWorker and every\n // persisted tag annotation: the category as a tagging TextualBody,\n // plus the tagging-schema id as a classifying TextualBody. The\n // classifying body is the only trace of schema provenance in the\n // event log — do not drop it.\n return buildAnnotation('tagging', t, [\n { type: 'TextualBody', value: cat, purpose: 'tagging', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n { type: 'TextualBody', value: params.schema.id, purpose: 'classifying', format: 'text/plain' satisfies SupportedMediaType },\n ]);\n }));\n created += fresh.length;\n for (const ann of fresh) {\n const body = (ann as { body?: Array<{ value?: unknown }> }).body;\n const cat = Array.isArray(body) && typeof body[0]?.value === 'string' ? body[0].value : 'unknown';\n byCategory[cat] = (byCategory[cat] ?? 0) + 1;\n }\n onProgress(60, { code: 'creating-tag-annotations', count: created });\n // The unit is the CATEGORY, not the motivation. `tag-annotation` loops\n // over `params.categories`, each walking the whole document from zero,\n // so a single 'tagging' key would have every category overwriting one\n // cursor — and the monotone merge would keep the furthest, which is the\n // right answer for at most one of them and silently skips text for the\n // rest. Same shape as reference's entity types, for the same reason.\n categoryCreated += fresh.length;\n await onChunkComplete(fresh, {\n unit: category,\n cursor: { ...cursor, found: categoryFound, emitted: categoryCreated },\n });\n },\n );\n found += categoryFound;\n completedItems.push({ value: category, foundCount: categoryFound });\n }\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'tag' });\n\n return {\n result: { kind: 'tag-annotation', tagsFound: found, tagsCreated: created, byCategory },\n };\n}\n\n/**\n * Output bound (PDF-GENERATION P5), symmetric with #1124's extraction budget\n * and deliberately the SAME threshold: an artifact larger than what extraction\n * accepts would be a resource our own Smelter declines as 'too-large'. One\n * judgment, two enforcement points. A runaway generation fails loudly\n * (job:fail); it never uploads.\n */\nexport function assertWithinOutputBudget(byteLength: number): void {\n if (!withinByteBudget(byteLength)) {\n throw new Error(\n `Generated artifact exceeds the output byte budget: ${byteLength} bytes > ${MAX_PDF_BYTES}. Refusing a runaway generation.`,\n );\n }\n}\n\nexport async function processGenerationJob(\n inferenceClient: InferenceClient,\n params: GenerationJobParams,\n onProgress: OnProgress,\n logger: Logger,\n): Promise<{ content: Uint8Array; title: string; format: SupportedMediaType; citations: GenerationCitation[]; result: GenerationResult }> {\n // Refuse any requested media type the registry doesn't mark `generatable` —\n // loudly (the throw propagates as job:fail), never a silent markdown fallback\n // under a mislabeled format. The gate reads the registry capability\n // (PDF-GENERATION P1), not a local table. Validate before the LLM call.\n const outputMediaType: SupportedMediaType = params.outputMediaType ?? 'text/markdown';\n if (!GENERATABLE_MEDIA_TYPES.includes(outputMediaType)) {\n throw new Error(\n `Unsupported outputMediaType for generation: ${outputMediaType}. Generation produces ${GENERATABLE_MEDIA_TYPES.join(' or ')}.`,\n );\n }\n\n const title = params.title ?? 'Untitled';\n const entityTypes = (params.entityTypes ?? []).map(String);\n\n // PDF path (PDF-GENERATION P3): the model authors Typst; the worker's pinned\n // binary compiles it, with the legible compile errors fed back for a bounded\n // number of repairs. Citations on PDFs need page geometry, not text offsets —\n // until the citation branch (P4) provides it, `cite` fails fast and loudly\n // rather than minting selectors that would render nothing.\n if (outputMediaType === 'application/pdf') {\n onProgress(5, { code: 'generating-resource' });\n\n // Under `cite`, [[<id>]] tokens are stripped from the SOURCE before every\n // compile — they must never render into the artifact. The citations carry\n // the claim text; the worker re-anchors it by page geometry after\n // extraction (P4). Offsets in these citations index the Typst source and\n // are NOT used for PDF anchoring.\n const validIds = params.cite === true ? collectContextResourceIds(params.context) : null;\n\n let generated = await generateResourceFromTopic(\n title, entityTypes, inferenceClient, logger,\n params.prompt, params.language, params.context, params.temperature,\n params.maxTokens, params.sourceLanguage, outputMediaType,\n params.task, params.structure, params.cite,\n );\n let source = generated.content;\n let citations: GenerationCitation[] = [];\n if (validIds) {\n const resolved = resolveCitationTokens(generated.content, validIds, logger);\n source = resolved.content;\n citations = resolved.citations;\n }\n let compiled = compileTypst(source);\n let repairs = 0;\n while ('error' in compiled) {\n // A truncated source that fails to compile is cut off, not wrong —\n // every repair regenerates under the same ceiling and cannot restore\n // content that was never generated. Fail immediately with the actual\n // cause instead of burning the repair budget and blaming the compiler\n // (GENERATE-FROM-RESOURCE P3a).\n if (generated.truncated) {\n throw new Error(\n `Generation stopped at the maxTokens ceiling (${params.maxTokens ?? DEFAULT_MAX_TOKENS} tokens) and the cut-off Typst source does not compile — repair cannot help; raise maxTokens. Compile error: ${compiled.error}`,\n );\n }\n if (repairs >= MAX_COMPILE_REPAIRS) {\n throw new Error(\n `Typst compilation failed after ${MAX_COMPILE_REPAIRS} repair attempts: ${compiled.error}`,\n );\n }\n repairs++;\n logger.warn('Typst compile failed — feeding the error back for repair', {\n attempt: repairs,\n error: compiled.error.slice(0, 500),\n });\n generated = await generateResourceFromTopic(\n title, entityTypes, inferenceClient, logger,\n params.prompt, params.language, params.context, params.temperature,\n params.maxTokens, params.sourceLanguage, outputMediaType,\n params.task, params.structure, params.cite,\n { source, error: compiled.error },\n );\n if (validIds) {\n const resolved = resolveCitationTokens(generated.content, validIds, logger);\n source = resolved.content;\n citations = resolved.citations;\n } else {\n source = generated.content;\n }\n compiled = compileTypst(source);\n }\n\n assertWithinOutputBudget(compiled.pdf.byteLength);\n onProgress(95, { code: 'creating-resource' });\n // The producer owns terminality (GENERATE-FROM-RESOURCE P1/D1): without\n // this, the client's last frame is forever the 95% payload. Generic by\n // design — the outcome (name + link) travels on job:complete (D8).\n // `truncated` rides both surfaces (P3a/D6): truncation that lands at a\n // syntactic boundary still compiles, and the artifact is still cut off.\n onProgress(100, { code: 'complete-generated', truncated: generated.truncated });\n\n return {\n content: compiled.pdf,\n title,\n format: outputMediaType,\n citations,\n result: {\n kind: 'generation',\n resourceId: '' as ResourceId,\n resourceName: title,\n truncated: generated.truncated,\n },\n };\n }\n\n // Generation has exactly two observable transitions: the LLM call starting\n // ('generating') and content finalized / creation beginning ('creating').\n // There is no fetch — context arrives pre-gathered in params. Percentages\n // approximate the share of expected wall-clock complete at each transition\n // (a single atomic LLM call has no measurable progress, and inference\n // dominates the job): its start is ~5, its end ~95.\n onProgress(5, { code: 'generating-resource' });\n\n const generated = await generateResourceFromTopic(\n title,\n entityTypes,\n inferenceClient,\n logger,\n params.prompt,\n params.language,\n params.context,\n params.temperature,\n params.maxTokens,\n params.sourceLanguage,\n outputMediaType,\n params.task,\n params.structure,\n params.cite,\n );\n\n // Under `cite`, the model emitted [[<id>]] transport tokens — resolve them:\n // validate against the ids the context actually contained, strip from the\n // stored content, and carry claim-span citations for the worker to mint.\n // When cite is off, bracketed text is legitimate content — leave it alone.\n let content = generated.content;\n let citations: GenerationCitation[] = [];\n if (params.cite === true) {\n const resolved = resolveCitationTokens(content, collectContextResourceIds(params.context), logger);\n content = resolved.content;\n citations = resolved.citations;\n }\n\n onProgress(95, { code: 'creating-resource' });\n\n // The artifact is bytes; text is an encoding of them. One shape for every\n // output media type, so a string can never travel mislabeled as a binary\n // format (PDF-GENERATION P1). Citation offsets index the decoded text.\n const artifact = new TextEncoder().encode(content);\n assertWithinOutputBudget(artifact.byteLength);\n\n // The producer owns terminality (GENERATE-FROM-RESOURCE P1/D1): without\n // this, the client's last frame is forever the 95% payload. Generic by\n // design — the outcome (name + link) travels on job:complete (D8).\n // `truncated` rides both surfaces (P3a/D6): the event is the frame the\n // client renders, the result is the record.\n onProgress(100, { code: 'complete-generated', truncated: generated.truncated });\n\n return {\n content: artifact,\n title,\n format: outputMediaType,\n citations,\n result: {\n kind: 'generation',\n resourceId: '' as ResourceId,\n resourceName: title,\n truncated: generated.truncated,\n },\n };\n}\n","/**\n * Worker Runtime — the importable half of the worker host.\n *\n * `worker-main.ts` is a process entrypoint (config at module scope,\n * `main()` at import) and therefore untestable by construction; everything\n * a unit test needs to reach lives here instead, fully parameterized — no\n * module-scope env reads, no side effects at import.\n *\n * The load-bearing contract this module owns (and the reason it was\n * extracted): a worker's stamped identity is the DID the\n * `/api/tokens/agent` exchange MINTED for it, carried verbatim — never\n * re-derived from the URL the worker happens to dial. One logical agent\n * previously got two DIDs that way (.plans/bugs/agent-did-host-skew.md).\n */\n\nimport type { EventMap } from '@semiont/core';\nimport { startWorkerProcess } from './worker-process';\nimport type { MarkCommitAwaits, DescriptorReadAwaits, DurabilityProbeAwaits } from './worker-process';\nimport type { WorkerVitals, JobClaimAwaits } from './job-claim-adapter';\nimport type { ConsultAnchoredTextAwaits } from './workers/detection/prepare-detection';\nimport { answerLimitsRequests, type InferenceClient, type LimitsSource } from '@semiont/inference';\nimport { hostname } from 'os';\nimport {\n replyChannelsFor,\n didToAgent,\n baseUrl,\n retryWithBackoff,\n isTransientFetchError,\n STARTUP_FETCH_RETRY,\n type BusOperationKey,\n type RetryPolicy,\n type components,\n type Logger,\n type AccessToken,\n} from '@semiont/core';\nimport {\n InMemorySessionStorage,\n SemiontClient,\n SemiontSession,\n kbGatewayUrl,\n setStoredSession,\n type HttpEndpoint,\n type KbTarget,\n} from '@semiont/sdk';\nimport { HttpContentTransport, HttpTransport } from '@semiont/http-transport';\nimport type { ContentReads } from '@semiont/content';\nimport { BehaviorSubject } from 'rxjs';\nimport { serviceAccountToken } from '@semiont/core';\nimport type { ServiceAccountCredential } from '@semiont/core';\n\ntype Agent = components['schemas']['Agent'];\n\n/** Shape of each resolved worker inference entry under `_metadata.workers`. */\nexport type ResolvedInference = {\n type: 'anthropic' | 'ollama';\n model: string;\n apiKey?: string;\n endpoint?: string;\n baseURL?: string;\n};\n\n/** One agent identity: an inference engine and the job types it serves. */\nexport interface AgentGroup {\n inference: ResolvedInference;\n jobTypes: string[];\n client: InferenceClient;\n}\n\nexport interface WorkerRuntimeOptions {\n group: AgentGroup;\n /** The gateway URL this worker dials — connection topology ONLY, never identity. */\n gatewayBaseUrl: string;\n /** This process's own account at the issuer, and the bearer the byte reads\n * below show the Archivist. */\n credential: ServiceAccountCredential;\n /**\n * The resource's bytes, for detection's extraction seam. Built by the\n * entrypoint (`worker-main`) rather than here, so a worker with no\n * Archivist configured refuses at boot instead of failing every job\n * (SINGLE-KB-MOUNT P4).\n */\n contentReads: ContentReads;\n logger: Logger;\n /**\n * The clients whose limits this agent reports on `job:limits-requested`:\n * every group's, for the one agent that answers for its pool, and none for\n * the rest. The gateway delivers only the first reply to a request.\n */\n reportsLimitsOf: readonly LimitsSource[];\n}\n\n/** Per-agent liveness: the adapter's snapshot plus this agent's identity. */\nexport interface AgentVitals extends WorkerVitals {\n provider: string;\n model: string;\n did: string;\n jobTypes: string[];\n}\n\nexport interface AgentWorkerHandle {\n session: SemiontSession;\n vitals(): AgentVitals;\n dispose(): Promise<void>;\n}\n\nexport interface WorkerHealthPayload {\n status: 'ok';\n agents: number;\n workers: AgentVitals[];\n}\n\n/**\n * The `/health` body (WORKER-LIVENESS.md P1). Additive: existing\n * consumers (image HEALTHCHECK, compose `service_healthy`, `semiont start`)\n * keep reading `status`/`agents`; the per-agent vitals expose\n * claim-loop progress so a stalled worker is *visible*, not just alive.\n */\nexport function buildHealthPayload(workers: ReadonlyArray<{ vitals(): AgentVitals }>): WorkerHealthPayload {\n return {\n status: 'ok',\n agents: workers.length,\n workers: workers.map((w) => w.vitals()),\n };\n}\n\n/**\n * Stall watchdog (WORKER-LIVENESS.md P3) — the fail-fast line behind the\n * inference timeout. There is no poll timer to heartbeat — the worker pulls\n * when idle, and a parked idle worker is not a stall; the honest stall\n * signal is *processing without activity*: an agent holding a claimed job\n * whose `lastActivityAt` (claim / progress / finish) has stopped advancing\n * is wedged — the adapter defers every wake-up while a job is held and\n * pulls at settle, so a wedged agent never settles and never recovers on\n * its own. Silent hang → loud crash → whatever\n * restart policy the deployment chose.\n *\n * Thresholds are fixed by design (no env knobs) and deliberately\n * layered: inference timeout (10 min, P2) fires first; this watchdog\n * (15 min) catches wedges where the loop still turns but activity has\n * stopped; the gateway's dead-worker janitor (30 min) re-queues the job\n * regardless.\n *\n * The layering matters because this watchdog has a hard limit: it is an\n * IN-PROCESS timer, so it cannot fire while the event loop itself is\n * blocked — the exact condition a blocked loop creates\n * (JOB-RESTART-SAFETY P7, the 2026-09-03 finalization hang: 18 min silent,\n * this watchdog never fired, an empty /health confirming the loop was\n * wedged). The unbounded emit that caused that specific hang is now bounded\n * at the transport (`EMIT_TIMEOUT_MS`), so the loop errors instead of\n * blocking; but for any future blocked-loop bug the ONLY backstop is the\n * out-of-process one — the gateway's janitor sweeping this worker's job\n * files by mtime (`fs-job-queue.ts` `recoverStaleRunningJobs`). A liveness\n * guarantee a blocked loop defeats is not one; the janitor is the guarantee.\n */\nexport const STALL_THRESHOLD_MS = 15 * 60_000;\nexport const STALL_CHECK_INTERVAL_MS = 60_000;\n\nexport interface StallWatchdogOptions {\n workers: ReadonlyArray<{ vitals(): AgentVitals }>;\n logger: Logger;\n /** Test seam; defaults to process.exit. */\n exit?: (code: number) => void;\n}\n\nexport function startStallWatchdog(opts: StallWatchdogOptions): { dispose(): void } {\n const { workers, logger, exit = (code: number) => process.exit(code) } = opts;\n\n const timer = setInterval(() => {\n const now = Date.now();\n for (const worker of workers) {\n const v = worker.vitals();\n if (!v.activeJob || !v.lastActivityAt) continue;\n\n const silentForMs = now - Date.parse(v.lastActivityAt);\n if (silentForMs <= STALL_THRESHOLD_MS) continue;\n\n logger.error('Worker stalled — exiting for restart', {\n provider: v.provider,\n model: v.model,\n did: v.did,\n jobId: v.activeJob.jobId,\n jobType: v.activeJob.type,\n processingSince: v.activeJob.since,\n lastActivityAt: v.lastActivityAt,\n silentForMs,\n thresholdMs: STALL_THRESHOLD_MS,\n });\n clearInterval(timer);\n exit(1);\n return;\n }\n }, STALL_CHECK_INTERVAL_MS);\n timer.unref?.();\n\n return { dispose: () => clearInterval(timer) };\n}\n\n/**\n * The bus operations a worker process ever AWAITS a reply to. Reply channels\n * are global fan-out on the gateway, so a full `BRIDGED_CHANNELS`\n * subscription made every worker receive every other client's reply traffic\n * — measured at ~85 multi-MB `browse:annotations-result` frames/min during\n * the 2026-09-03 worker OOM, all parsed and dropped by cid filtering. The\n * worker subscribes exactly its own operations' reply channels instead.\n *\n * This list restates a fact the code owns (which operations worker code\n * paths call `busRequest` on); its gate is the build-time census below\n * (`workerAwaitCensus`): every awaiting site declares its operation next to\n * the call, and an operation awaited but missing here fails COMPILATION with\n * the operation named. `busRequest`'s `isSubscribed` probe remains the\n * runtime backstop for an await nobody declared — a loud `bus.unsubscribed`\n * at first use, never a silent 30 s timeout.\n * (`job:queued` is not here: it is a broadcast, not an awaited reply. The\n * broadcasts a worker consumes are declared in `WORKER_CONSUMED_BROADCASTS`\n * below, and `WORKER_CHANNELS` is the union.)\n */\nexport const WORKER_AWAITED_OPERATIONS = [\n 'job:claim',\n 'browse:resource-requested',\n // Canonical geometry for a geometry-bearing detection: the consult behind\n // `ConsultAnchoredText` (SMELTER-OWNS-OCR P2). Its omission broke every\n // PDF detection job at the transport probe\n // (.plans/WORKER-ANCHORED-TEXT-CHANNEL.md); the census below now fails the\n // BUILD when this list and the declared awaits drift.\n 'browse:anchored-text-requested',\n // Durability acknowledgement for a unit's annotations (JOB-RESTART-SAFETY\n // P6). The worker AWAITS this one — a unit may not advance until its\n // annotations are in the event log — so its replies must be in the narrow\n // channel set or every commit fails fast with `bus.unsubscribed`.\n 'mark:commit',\n // The durability probe for a commit whose acknowledgement never routed\n // (COMMIT-ACK-FALSE-FAILURE F1). SINGULAR by design: the annotation LIST\n // channel is the multi-MB fan-out this narrowing exists to keep out, and a\n // rare error path is no reason to let it back in.\n 'browse:annotation-requested',\n] as const satisfies readonly BusOperationKey[];\n\n/**\n * The broadcasts a worker CONSUMES — announcements nobody replies to, which\n * therefore derive from no operation.\n *\n * One home, because the alternative was proven: these lived as `addChannels`\n * calls beside their consumers, so the worker's complete set existed nowhere\n * and a widening could be deleted without any list getting shorter. That is\n * the 2026-09-16 outage — every worker idle on a `job:queued` its transport\n * would never carry, `lastQueuedEventAt: null`, nothing thrown and nothing\n * logged.\n *\n * An entry here must have a consumer and a consumer must have an entry; the\n * census beside this file asserts both directions.\n */\nexport const WORKER_CONSUMED_BROADCASTS = [\n // The queue announcement the claim adapter races for.\n 'job:queued',\n // Cooperative cancellation of the ACTIVE job (JOB-RESTART-SAFETY P4).\n 'job:cancel-requested',\n] as const satisfies readonly (keyof EventMap)[];\n\n/**\n * The requests a worker ANSWERS. It holds the inference credentials, so it is\n * the one service that can discover its models' limits from their providers.\n * One agent in a pool answers for all of them (`reportsLimitsOf`): only its\n * transport subscribes these, so no other agent receives a request it would\n * drop.\n */\nexport const WORKER_ANSWERED_OPERATIONS = [\n 'job:limits-requested',\n] as const satisfies readonly BusOperationKey[];\n\n/**\n * The global SSE channel set for a worker's transport: the whole manifest,\n * stated once and passed at construction. Nothing widens it afterwards.\n */\n// `replyChannelsFor` already returns `EventName[]`; annotating this\n// `readonly string[]` threw that proof away and was the only reason a\n// transport's channel roster was ever wider than the registry.\nexport const WORKER_CHANNELS: readonly (keyof EventMap)[] = [\n ...replyChannelsFor(WORKER_AWAITED_OPERATIONS),\n ...WORKER_CONSUMED_BROADCASTS,\n];\n\n/**\n * The build-time census gate (WORKER-ANCHORED-TEXT-CHANNEL F2).\n *\n * `WORKER_AWAITED_OPERATIONS` restates a fact the code owns — which\n * operations worker paths call `busRequest` on — and one of those calls\n * hides behind an injected seam (`ConsultAnchoredText` → the SDK), where no\n * grep and no runtime probe-before-shipping can see it. So every awaiting\n * site DECLARES its operation next to the call (the `*Awaits` aliases), the\n * declarations are assembled here, and this constant compiles ONLY when the\n * list and the declarations agree in BOTH directions. Drift fails the build\n * with the drifted operation named in the type error — at build time, not at\n * the first live job. `busRequest`'s `bus.unsubscribed` probe remains the\n * runtime backstop for an await nobody declared.\n */\ntype DeclaredWorkerAwaits =\n | JobClaimAwaits // job-claim-adapter.ts — claiming an announced job\n | DescriptorReadAwaits // worker-process.ts — the resource descriptor read\n | MarkCommitAwaits // worker-process.ts — the durability ack (JOB-RESTART-SAFETY P6)\n | DurabilityProbeAwaits // worker-process.ts — did the batch land? (COMMIT-ACK-FALSE-FAILURE F1)\n | ConsultAnchoredTextAwaits; // prepare-detection.ts — canonical geometry (SMELTER-OWNS-OCR P2)\n\ntype WorkerAwaitCensusDrift =\n | Exclude<DeclaredWorkerAwaits, (typeof WORKER_AWAITED_OPERATIONS)[number]>\n | Exclude<(typeof WORKER_AWAITED_OPERATIONS)[number], DeclaredWorkerAwaits>;\n\nexport const workerAwaitCensus: [WorkerAwaitCensusDrift] extends [never]\n ? 'in-census'\n : WorkerAwaitCensusDrift = 'in-census';\n\nexport function parseGatewayUrl(url: string): { protocol: 'http' | 'https'; host: string; port: number } {\n const parsed = new URL(url);\n const protocol = (parsed.protocol.replace(':', '') === 'https' ? 'https' : 'http') as 'http' | 'https';\n const host = parsed.hostname;\n const port = parsed.port\n ? Number(parsed.port)\n : protocol === 'https' ? 443 : 80;\n return { protocol, host, port };\n}\n\n/**\n * Exchange this process's issuer token for an agent JWT and its canonical DID.\n * The DID is minted by the gateway (under the KB's own domain) — the caller\n * carries it verbatim.\n *\n * Connection-level failures (`TypeError: fetch failed`) are retried with\n * exponential backoff: the gateway may be mid-restart or the container\n * network still warming up when this process starts, and orchestration\n * runs workers with `--rm` and no restart policy — exiting on the first\n * failed fetch is permanent death. HTTP-level rejections (401 on a bad\n * secret) are NOT retried; the gateway is up and said no.\n */\nexport async function authenticateAgent(opts: {\n gatewayBaseUrl: string;\n credential: ServiceAccountCredential;\n provider: string;\n model: string;\n logger?: Logger;\n retry?: RetryPolicy;\n}): Promise<{ token: string; did: string }> {\n const { gatewayBaseUrl, credential, provider, model, logger, retry = STARTUP_FETCH_RETRY } = opts;\n\n return retryWithBackoff(\n async () => {\n // The process proves who IT is, then asks for the agent identity it wants.\n // One worker holds several of the latter when job types are configured\n // with different models, which is why they are separate exchanges.\n const caller = await serviceAccountToken(credential);\n\n const response = await fetch(`${gatewayBaseUrl}/api/tokens/agent`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${caller}`,\n },\n body: JSON.stringify({ provider, model }),\n });\n\n if (!response.ok) {\n throw new Error(`Agent authentication failed for ${provider}:${model}: ${response.status} ${response.statusText}`);\n }\n\n return await response.json() as { token: string; did: string };\n },\n isTransientFetchError,\n retry,\n ({ attempt, attempts, delayMs, error }) => {\n logger?.warn('Gateway unreachable, retrying agent authentication', {\n agent: `${provider}:${model}`,\n attempt,\n attempts,\n retryInMs: delayMs,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n );\n}\n\nexport async function startAgentWorker(\n opts: WorkerRuntimeOptions,\n): Promise<AgentWorkerHandle> {\n const { group, gatewayBaseUrl, credential, contentReads, reportsLimitsOf, logger } = opts;\n const { inference } = group;\n\n const { protocol, host, port } = parseGatewayUrl(gatewayBaseUrl);\n const { token: initialToken, did } = await authenticateAgent({\n gatewayBaseUrl,\n credential,\n provider: inference.type,\n model: inference.model,\n logger,\n });\n\n // The exchange minted this worker's canonical DID (under the KB's own\n // domain) and we carry it VERBATIM — never re-derive identity from\n // the URL we happen to dial (`host` is connection topology only). One\n // logical agent previously got two DIDs this way:\n // .plans/bugs/agent-did-host-skew.md.\n const generator: Agent = didToAgent(did);\n\n const kbId = `agent-${inference.type}-${inference.model}-${hostname()}`;\n const endpoint: HttpEndpoint = { kind: 'http', host, port, protocol };\n const kb: KbTarget = {\n id: kbId,\n label: `${inference.type} / ${inference.model} @ ${host}`,\n endpoint,\n };\n const storage = new InMemorySessionStorage();\n // No refresh token: a worker renews by re-authenticating as its service\n // account, not by presenting a refresh grant. The client id and token\n // endpoint are its own, so the stored session names the credential that\n // actually backs it rather than leaving them blank.\n setStoredSession(storage, kbId, {\n access: initialToken,\n refresh: '',\n clientId: credential.clientId,\n tokenEndpoint: credential.issuer,\n });\n\n const token$ = new BehaviorSubject<AccessToken | null>(null);\n let session!: SemiontSession;\n const transport = new HttpTransport({\n baseUrl: baseUrl(kbGatewayUrl(endpoint)),\n token$,\n tokenRefresher: () => session.refresh().then((t) => t ?? null),\n // Only the reply channels this process awaits — not the full bridged\n // set. See WORKER_AWAITED_OPERATIONS. The agent that reports its pool's\n // limits also subscribes the requests it answers.\n channels: reportsLimitsOf.length > 0 ? [...WORKER_CHANNELS, ...WORKER_ANSWERED_OPERATIONS] : WORKER_CHANNELS,\n });\n const content = new HttpContentTransport(transport);\n const client = new SemiontClient(transport, content, transport);\n session = new SemiontSession({\n kb,\n storage,\n client,\n token$,\n refresh: async () => {\n try {\n const { token } = await authenticateAgent({\n gatewayBaseUrl,\n credential,\n provider: inference.type,\n model: inference.model,\n logger,\n });\n return token;\n } catch (err) {\n logger.error('Agent token refresh failed', {\n error: err instanceof Error ? err.message : String(err),\n agent: did,\n });\n return null;\n }\n },\n onError: (err) => {\n logger.error('Session error', { code: err.code, message: err.message, agent: did });\n },\n });\n await session.ready;\n\n const adapter = startWorkerProcess({\n session,\n jobTypes: group.jobTypes,\n inferenceClient: group.client,\n generator,\n // Byte reads for decode-path media only. A geometry-bearing type's text\n // never comes from bytes here — it is CONSULTED from the Smelter's\n // canonical anchored text over the bus (SMELTER-OWNS-OCR P2), and this\n // worker cannot derive even by mistake (READ-VS-EXTRACT P2).\n contentReads,\n logger,\n });\n\n const limitsResponder = reportsLimitsOf.length > 0\n ? answerLimitsRequests(transport, 'job:limits-requested', reportsLimitsOf, logger)\n : undefined;\n\n logger.info('Agent ready', {\n did,\n provider: inference.type,\n model: inference.model,\n jobTypes: group.jobTypes,\n });\n\n return {\n session,\n vitals: () => ({\n provider: inference.type,\n model: inference.model,\n did,\n jobTypes: group.jobTypes,\n ...adapter.vitals(),\n }),\n dispose: async () => {\n limitsResponder?.unsubscribe();\n adapter.dispose();\n await session.dispose();\n },\n };\n}\n"]}
1
+ {"version":3,"sources":["../../../node_modules/rxjs/src/internal/util/isFunction.ts","../../../node_modules/rxjs/src/internal/util/createErrorClass.ts","../../../node_modules/rxjs/src/internal/util/UnsubscriptionError.ts","../../../node_modules/rxjs/src/internal/util/arrRemove.ts","../../../node_modules/rxjs/src/internal/Subscription.ts","../../../node_modules/rxjs/src/internal/config.ts","../../../node_modules/rxjs/src/internal/scheduler/timeoutProvider.ts","../../../node_modules/rxjs/src/internal/util/reportUnhandledError.ts","../../../node_modules/rxjs/src/internal/util/noop.ts","../../../node_modules/rxjs/src/internal/NotificationFactories.ts","../../../node_modules/rxjs/src/internal/util/errorContext.ts","../../../node_modules/rxjs/src/internal/Subscriber.ts","../../../node_modules/rxjs/src/internal/symbol/observable.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/lift.ts","../../../node_modules/rxjs/src/internal/operators/OperatorSubscriber.ts","../../../node_modules/rxjs/src/internal/operators/refCount.ts","../../../node_modules/rxjs/src/internal/observable/ConnectableObservable.ts","../../../node_modules/rxjs/src/internal/scheduler/performanceTimestampProvider.ts","../../../node_modules/rxjs/src/internal/scheduler/animationFrameProvider.ts","../../../node_modules/rxjs/src/internal/observable/dom/animationFrames.ts","../../../node_modules/rxjs/src/internal/util/ObjectUnsubscribedError.ts","../../../node_modules/rxjs/src/internal/Subject.ts","../../../node_modules/rxjs/src/internal/BehaviorSubject.ts","../../../node_modules/rxjs/src/internal/scheduler/dateTimestampProvider.ts","../../../node_modules/rxjs/src/internal/ReplaySubject.ts","../../../node_modules/rxjs/src/internal/AsyncSubject.ts","../../../node_modules/rxjs/src/internal/scheduler/Action.ts","../../../node_modules/rxjs/src/internal/scheduler/intervalProvider.ts","../../../node_modules/rxjs/src/internal/scheduler/AsyncAction.ts","../../../node_modules/rxjs/src/internal/util/Immediate.ts","../../../node_modules/rxjs/src/internal/scheduler/immediateProvider.ts","../../../node_modules/rxjs/src/internal/scheduler/AsapAction.ts","../../../node_modules/rxjs/src/internal/Scheduler.ts","../../../node_modules/rxjs/src/internal/scheduler/AsyncScheduler.ts","../../../node_modules/rxjs/src/internal/scheduler/AsapScheduler.ts","../../../node_modules/rxjs/src/internal/scheduler/asap.ts","../../../node_modules/rxjs/src/internal/scheduler/async.ts","../../../node_modules/rxjs/src/internal/scheduler/QueueAction.ts","../../../node_modules/rxjs/src/internal/scheduler/QueueScheduler.ts","../../../node_modules/rxjs/src/internal/scheduler/queue.ts","../../../node_modules/rxjs/src/internal/scheduler/AnimationFrameAction.ts","../../../node_modules/rxjs/src/internal/scheduler/AnimationFrameScheduler.ts","../../../node_modules/rxjs/src/internal/scheduler/animationFrame.ts","../../../node_modules/rxjs/src/internal/scheduler/VirtualTimeScheduler.ts","../../../node_modules/rxjs/src/internal/observable/empty.ts","../../../node_modules/rxjs/src/internal/util/isScheduler.ts","../../../node_modules/rxjs/src/internal/util/args.ts","../../../node_modules/rxjs/src/internal/util/isArrayLike.ts","../../../node_modules/rxjs/src/internal/util/isPromise.ts","../../../node_modules/rxjs/src/internal/util/isInteropObservable.ts","../../../node_modules/rxjs/src/internal/util/isAsyncIterable.ts","../../../node_modules/rxjs/src/internal/util/throwUnobservableError.ts","../../../node_modules/rxjs/src/internal/symbol/iterator.ts","../../../node_modules/rxjs/src/internal/util/isIterable.ts","../../../node_modules/rxjs/src/internal/util/isReadableStreamLike.ts","../../../node_modules/rxjs/src/internal/observable/innerFrom.ts","../../../node_modules/rxjs/src/internal/util/executeSchedule.ts","../../../node_modules/rxjs/src/internal/operators/observeOn.ts","../../../node_modules/rxjs/src/internal/operators/subscribeOn.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleObservable.ts","../../../node_modules/rxjs/src/internal/scheduled/schedulePromise.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleArray.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleIterable.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleAsyncIterable.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduleReadableStreamLike.ts","../../../node_modules/rxjs/src/internal/scheduled/scheduled.ts","../../../node_modules/rxjs/src/internal/observable/from.ts","../../../node_modules/rxjs/src/internal/observable/of.ts","../../../node_modules/rxjs/src/internal/observable/throwError.ts","../../../node_modules/rxjs/src/internal/Notification.ts","../../../node_modules/rxjs/src/internal/util/isObservable.ts","../../../node_modules/rxjs/src/internal/util/EmptyError.ts","../../../node_modules/rxjs/src/internal/lastValueFrom.ts","../../../node_modules/rxjs/src/internal/firstValueFrom.ts","../../../node_modules/rxjs/src/internal/util/ArgumentOutOfRangeError.ts","../../../node_modules/rxjs/src/internal/util/NotFoundError.ts","../../../node_modules/rxjs/src/internal/util/SequenceError.ts","../../../node_modules/rxjs/src/internal/util/isDate.ts","../../../node_modules/rxjs/src/internal/operators/timeout.ts","../../../node_modules/rxjs/src/internal/operators/map.ts","../../../node_modules/rxjs/src/internal/util/mapOneOrManyArgs.ts","../../../node_modules/rxjs/src/internal/observable/bindCallbackInternals.ts","../../../node_modules/rxjs/src/internal/observable/bindCallback.ts","../../../node_modules/rxjs/src/internal/observable/bindNodeCallback.ts","../../../node_modules/rxjs/src/internal/util/argsArgArrayOrObject.ts","../../../node_modules/rxjs/src/internal/util/createObject.ts","../../../node_modules/rxjs/src/internal/observable/combineLatest.ts","../../../node_modules/rxjs/src/internal/operators/mergeInternals.ts","../../../node_modules/rxjs/src/internal/operators/mergeMap.ts","../../../node_modules/rxjs/src/internal/operators/mergeAll.ts","../../../node_modules/rxjs/src/internal/operators/concatAll.ts","../../../node_modules/rxjs/src/internal/observable/concat.ts","../../../node_modules/rxjs/src/internal/observable/defer.ts","../../../node_modules/rxjs/src/internal/observable/connectable.ts","../../../node_modules/rxjs/src/internal/observable/forkJoin.ts","../../../node_modules/rxjs/src/internal/observable/fromEvent.ts","../../../node_modules/rxjs/src/internal/observable/fromEventPattern.ts","../../../node_modules/rxjs/src/internal/observable/generate.ts","../../../node_modules/rxjs/src/internal/observable/iif.ts","../../../node_modules/rxjs/src/internal/observable/timer.ts","../../../node_modules/rxjs/src/internal/observable/interval.ts","../../../node_modules/rxjs/src/internal/observable/merge.ts","../../../node_modules/rxjs/src/internal/observable/never.ts","../../../node_modules/rxjs/src/internal/util/argsOrArgArray.ts","../../../node_modules/rxjs/src/internal/observable/onErrorResumeNext.ts","../../../node_modules/rxjs/src/internal/observable/pairs.ts","../../../node_modules/rxjs/src/internal/util/not.ts","../../../node_modules/rxjs/src/internal/operators/filter.ts","../../../node_modules/rxjs/src/internal/observable/partition.ts","../../../node_modules/rxjs/src/internal/observable/race.ts","../../../node_modules/rxjs/src/internal/observable/range.ts","../../../node_modules/rxjs/src/internal/observable/using.ts","../../../node_modules/rxjs/src/internal/observable/zip.ts","../../../node_modules/rxjs/dist/cjs/internal/types.js","../../../node_modules/rxjs/src/internal/operators/audit.ts","../../../node_modules/rxjs/src/internal/operators/auditTime.ts","../../../node_modules/rxjs/src/internal/operators/buffer.ts","../../../node_modules/rxjs/src/internal/operators/bufferCount.ts","../../../node_modules/rxjs/src/internal/operators/bufferTime.ts","../../../node_modules/rxjs/src/internal/operators/bufferToggle.ts","../../../node_modules/rxjs/src/internal/operators/bufferWhen.ts","../../../node_modules/rxjs/src/internal/operators/catchError.ts","../../../node_modules/rxjs/src/internal/operators/scanInternals.ts","../../../node_modules/rxjs/src/internal/operators/reduce.ts","../../../node_modules/rxjs/src/internal/operators/toArray.ts","../../../node_modules/rxjs/src/internal/operators/joinAllInternals.ts","../../../node_modules/rxjs/src/internal/operators/combineLatestAll.ts","../../../node_modules/rxjs/src/internal/operators/combineAll.ts","../../../node_modules/rxjs/src/internal/operators/combineLatest.ts","../../../node_modules/rxjs/src/internal/operators/combineLatestWith.ts","../../../node_modules/rxjs/src/internal/operators/concatMap.ts","../../../node_modules/rxjs/src/internal/operators/concatMapTo.ts","../../../node_modules/rxjs/src/internal/operators/concat.ts","../../../node_modules/rxjs/src/internal/operators/concatWith.ts","../../../node_modules/rxjs/src/internal/observable/fromSubscribable.ts","../../../node_modules/rxjs/src/internal/operators/connect.ts","../../../node_modules/rxjs/src/internal/operators/count.ts","../../../node_modules/rxjs/src/internal/operators/debounce.ts","../../../node_modules/rxjs/src/internal/operators/debounceTime.ts","../../../node_modules/rxjs/src/internal/operators/defaultIfEmpty.ts","../../../node_modules/rxjs/src/internal/operators/take.ts","../../../node_modules/rxjs/src/internal/operators/ignoreElements.ts","../../../node_modules/rxjs/src/internal/operators/mapTo.ts","../../../node_modules/rxjs/src/internal/operators/delayWhen.ts","../../../node_modules/rxjs/src/internal/operators/delay.ts","../../../node_modules/rxjs/src/internal/operators/dematerialize.ts","../../../node_modules/rxjs/src/internal/operators/distinct.ts","../../../node_modules/rxjs/src/internal/operators/distinctUntilChanged.ts","../../../node_modules/rxjs/src/internal/operators/distinctUntilKeyChanged.ts","../../../node_modules/rxjs/src/internal/operators/throwIfEmpty.ts","../../../node_modules/rxjs/src/internal/operators/elementAt.ts","../../../node_modules/rxjs/src/internal/operators/endWith.ts","../../../node_modules/rxjs/src/internal/operators/every.ts","../../../node_modules/rxjs/src/internal/operators/exhaustMap.ts","../../../node_modules/rxjs/src/internal/operators/exhaustAll.ts","../../../node_modules/rxjs/src/internal/operators/exhaust.ts","../../../node_modules/rxjs/src/internal/operators/expand.ts","../../../node_modules/rxjs/src/internal/operators/finalize.ts","../../../node_modules/rxjs/src/internal/operators/find.ts","../../../node_modules/rxjs/src/internal/operators/findIndex.ts","../../../node_modules/rxjs/src/internal/operators/first.ts","../../../node_modules/rxjs/src/internal/operators/groupBy.ts","../../../node_modules/rxjs/src/internal/operators/isEmpty.ts","../../../node_modules/rxjs/src/internal/operators/takeLast.ts","../../../node_modules/rxjs/src/internal/operators/last.ts","../../../node_modules/rxjs/src/internal/operators/materialize.ts","../../../node_modules/rxjs/src/internal/operators/max.ts","../../../node_modules/rxjs/src/internal/operators/flatMap.ts","../../../node_modules/rxjs/src/internal/operators/mergeMapTo.ts","../../../node_modules/rxjs/src/internal/operators/mergeScan.ts","../../../node_modules/rxjs/src/internal/operators/merge.ts","../../../node_modules/rxjs/src/internal/operators/mergeWith.ts","../../../node_modules/rxjs/src/internal/operators/min.ts","../../../node_modules/rxjs/src/internal/operators/multicast.ts","../../../node_modules/rxjs/src/internal/operators/onErrorResumeNextWith.ts","../../../node_modules/rxjs/src/internal/operators/pairwise.ts","../../../node_modules/rxjs/src/internal/operators/pluck.ts","../../../node_modules/rxjs/src/internal/operators/publish.ts","../../../node_modules/rxjs/src/internal/operators/publishBehavior.ts","../../../node_modules/rxjs/src/internal/operators/publishLast.ts","../../../node_modules/rxjs/src/internal/operators/publishReplay.ts","../../../node_modules/rxjs/src/internal/operators/raceWith.ts","../../../node_modules/rxjs/src/internal/operators/repeat.ts","../../../node_modules/rxjs/src/internal/operators/repeatWhen.ts","../../../node_modules/rxjs/src/internal/operators/retry.ts","../../../node_modules/rxjs/src/internal/operators/retryWhen.ts","../../../node_modules/rxjs/src/internal/operators/sample.ts","../../../node_modules/rxjs/src/internal/operators/sampleTime.ts","../../../node_modules/rxjs/src/internal/operators/scan.ts","../../../node_modules/rxjs/src/internal/operators/sequenceEqual.ts","../../../node_modules/rxjs/src/internal/operators/share.ts","../../../node_modules/rxjs/src/internal/operators/shareReplay.ts","../../../node_modules/rxjs/src/internal/operators/single.ts","../../../node_modules/rxjs/src/internal/operators/skip.ts","../../../node_modules/rxjs/src/internal/operators/skipLast.ts","../../../node_modules/rxjs/src/internal/operators/skipUntil.ts","../../../node_modules/rxjs/src/internal/operators/skipWhile.ts","../../../node_modules/rxjs/src/internal/operators/startWith.ts","../../../node_modules/rxjs/src/internal/operators/switchMap.ts","../../../node_modules/rxjs/src/internal/operators/switchAll.ts","../../../node_modules/rxjs/src/internal/operators/switchMapTo.ts","../../../node_modules/rxjs/src/internal/operators/switchScan.ts","../../../node_modules/rxjs/src/internal/operators/takeUntil.ts","../../../node_modules/rxjs/src/internal/operators/takeWhile.ts","../../../node_modules/rxjs/src/internal/operators/tap.ts","../../../node_modules/rxjs/src/internal/operators/throttle.ts","../../../node_modules/rxjs/src/internal/operators/throttleTime.ts","../../../node_modules/rxjs/src/internal/operators/timeInterval.ts","../../../node_modules/rxjs/src/internal/operators/timeoutWith.ts","../../../node_modules/rxjs/src/internal/operators/timestamp.ts","../../../node_modules/rxjs/src/internal/operators/window.ts","../../../node_modules/rxjs/src/internal/operators/windowCount.ts","../../../node_modules/rxjs/src/internal/operators/windowTime.ts","../../../node_modules/rxjs/src/internal/operators/windowToggle.ts","../../../node_modules/rxjs/src/internal/operators/windowWhen.ts","../../../node_modules/rxjs/src/internal/operators/withLatestFrom.ts","../../../node_modules/rxjs/src/internal/operators/zipAll.ts","../../../node_modules/rxjs/src/internal/operators/zip.ts","../../../node_modules/rxjs/src/internal/operators/zipWith.ts","../../../node_modules/rxjs/src/index.ts","../src/types.ts","../src/workers/inference-call.ts","../src/failure-class.ts","../src/workers/detection/chunk-size-controller.ts","../src/workers/detection/detection-chunking.ts","../src/workers/detection/motivation-prompts.ts","../src/workers/detection/anchor-audit.ts","../src/workers/detection/motivation-parsers.ts","../src/workers/annotation-detection.ts","../src/workers/detection/entity-extractor.ts","../src/workers/generation/resource-generation.ts","../src/workers/generation/typst-compiler.ts","../src/workers/generation/citation-resolver.ts","../src/workers/detection/bounded-concurrency.ts","../src/processors.ts","../src/job-claim-adapter.ts","../src/worker-runtime.ts"],"names":["Subscription","Subscriber","ConsumerObserver","SafeSubscriber","Observable","OperatorSubscriber","err","ConnectableObservable","Subject","AnonymousSubject","BehaviorSubject","ReplaySubject","AsyncSubject","Action","AsyncAction","AsapAction","Scheduler","AsyncScheduler","AsapScheduler","QueueAction","QueueScheduler","AnimationFrameAction","AnimationFrameScheduler","VirtualTimeScheduler","VirtualAction","process","NotificationKind","Notification","_i","i","sourceIndex","_a","TimeInterval","StructuredReadError","isObject","isString","getLocaleEnglishName","estimateTokens","response","reconcileSelector","generated","citations"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAIA,IAAA,SAAgB,WAAW,KAAA,EAAU;AACnC,MAAA,OAAO,OAAO,KAAA,KAAU,UAAA;AAC1B,IAAA;AAFA,IAAA,OAAA,CAAA,UAAA,GAAA,UAAA;;;;;;;;;ACKA,IAAA,SAAgB,iBAAoB,UAAA,EAAgC;AAClE,MAAA,IAAM,MAAA,GAAS,SAAC,QAAA,EAAa;AAC3B,QAAA,KAAA,CAAM,KAAK,QAAQ,CAAA;AACnB,QAAA,QAAA,CAAS,KAAA,GAAQ,IAAI,KAAA,EAAK,CAAG,KAAA;AAC/B,MAAA,CAAA;AAEA,MAAA,IAAM,QAAA,GAAW,WAAW,MAAM,CAAA;AAClC,MAAA,QAAA,CAAS,SAAA,GAAY,MAAA,CAAO,MAAA,CAAO,KAAA,CAAM,SAAS,CAAA;AAClD,MAAA,QAAA,CAAS,UAAU,WAAA,GAAc,QAAA;AACjC,MAAA,OAAO,QAAA;AACT,IAAA;AAVA,IAAA,OAAA,CAAA,gBAAA,GAAA,gBAAA;;;;;;;;;ACTA,IAAA,IAAA,kBAAA,GAAA,wBAAA,EAAA;AAkBa,IAAA,OAAA,CAAA,mBAAA,GAA+C,kBAAA,CAAA,gBAAA,CAC1D,SAAC,MAAA,EAAM;AACL,MAAA,OAAA,SAAS,wBAAmC,MAAA,EAA0B;AACpE,QAAA,MAAA,CAAO,IAAI,CAAA;AACX,QAAA,IAAA,CAAK,OAAA,GAAU,SACR,MAAA,CAAO,MAAA,GAAM,8CACxB,MAAA,CAAO,GAAA,CAAI,SAAC,GAAA,EAAK,CAAA,EAAC;AAAK,UAAA,OAAG,CAAA,GAAI,CAAA,GAAC,IAAA,GAAK,GAAA,CAAI,QAAA,EAAQ;QAAzB,CAA6B,CAAA,CA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AI,cAAc,CAAA;AAAA,QAClC,SAAA,EAAW,MAAA,IAAU,WAAA,KAAgB,IAAA,GACjC,EAAE,KAAA,EAAO,MAAA,CAAO,KAAA,EAAO,IAAA,EAAM,OAAO,IAAA,EAAM,KAAA,EAAO,GAAA,CAAI,WAAW,GAAG,GACnE,IAAA;AAAA,QACJ,aAAA,EAAe,eAAe,QAAA;AAAS,OACzC;AAAA,IACF,CAAA;AAAA,IAEA,eAAe,MAAM;AACnB,MAAA,cAAA,GAAiB,KAAK,GAAA,EAAI;AAAA,IAC5B,CAAA;AAAA,IAEA,SAAS,MAAM;AACb,MAAA,KAAA,MAAW,CAAA,IAAK,aAAA,EAAe,CAAA,CAAE,WAAA,EAAY;AAC7C,MAAA,aAAA,GAAgB,EAAC;AACjB,MAAA,OAAA,GAAU,KAAA;AACV,MAAA,UAAA,CAAW,QAAA,EAAS;AACpB,MAAA,aAAA,CAAc,QAAA,EAAS;AACvB,MAAA,cAAA,CAAe,QAAA,EAAS;AACxB,MAAA,OAAA,CAAQ,QAAA,EAAS;AACjB,MAAA,QAAA,CAAS,QAAA,EAAS;AAAA,IACpB;AAAA,GACF;AACF;ACjPO,IAAM,qBAAqB,EAAA,GAAK;AA8DhC,IAAM,yBAAA,GAA4B;AAAA,EACvC,WAAA;AAAA,EACA,2BAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,gCAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA,aAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAKA;AACF,CAAA;AAgBO,IAAM,0BAAA,GAA6B;AAAA;AAAA,EAExC,YAAA;AAAA;AAAA,EAEA;AACF;AAoBO,IAAM,eAAA,GAA+C;AAAA,EAC1D,GAAG,iBAAiB,yBAAyB,CAAA;AAAA,EAC7C,GAAG;AACL","file":"index.js","sourcesContent":["/**\n * Returns true if the object is a function.\n * @param value The value to check\n */\nexport function isFunction(value: any): value is (...args: any[]) => any {\n return typeof value === 'function';\n}\n","/**\n * Used to create Error subclasses until the community moves away from ES5.\n *\n * This is because compiling from TypeScript down to ES5 has issues with subclassing Errors\n * as well as other built-in types: https://github.com/Microsoft/TypeScript/issues/12123\n *\n * @param createImpl A factory function to create the actual constructor implementation. The returned\n * function should be a named function that calls `_super` internally.\n */\nexport function createErrorClass<T>(createImpl: (_super: any) => any): T {\n const _super = (instance: any) => {\n Error.call(instance);\n instance.stack = new Error().stack;\n };\n\n const ctorFunc = createImpl(_super);\n ctorFunc.prototype = Object.create(Error.prototype);\n ctorFunc.prototype.constructor = ctorFunc;\n return ctorFunc;\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface UnsubscriptionError extends Error {\n readonly errors: any[];\n}\n\nexport interface UnsubscriptionErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (errors: any[]): UnsubscriptionError;\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 = createErrorClass(\n (_super) =>\n function UnsubscriptionErrorImpl(this: any, errors: (Error | string)[]) {\n _super(this);\n this.message = errors\n ? `${errors.length} errors occurred during unsubscription:\n${errors.map((err, i) => `${i + 1}) ${err.toString()}`).join('\\n ')}`\n : '';\n this.name = 'UnsubscriptionError';\n this.errors = errors;\n }\n);\n","/**\n * Removes an item from an array, mutating it.\n * @param arr The array to remove the item from\n * @param item The item to remove\n */\nexport function arrRemove<T>(arr: T[] | undefined | null, item: T) {\n if (arr) {\n const index = arr.indexOf(item);\n 0 <= index && arr.splice(index, 1);\n }\n}\n","import { isFunction } from './util/isFunction';\nimport { UnsubscriptionError } from './util/UnsubscriptionError';\nimport { SubscriptionLike, TeardownLogic, Unsubscribable } from './types';\nimport { arrRemove } from './util/arrRemove';\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 */\nexport class Subscription implements SubscriptionLike {\n public static EMPTY = (() => {\n const empty = new Subscription();\n empty.closed = true;\n return empty;\n })();\n\n /**\n * A flag to indicate whether this Subscription has already been unsubscribed.\n */\n public closed = false;\n\n private _parentage: Subscription[] | Subscription | null = null;\n\n /**\n * The list of registered finalizers to execute upon unsubscription. Adding and removing from this\n * list occurs in the {@link #add} and {@link #remove} methods.\n */\n private _finalizers: Exclude<TeardownLogic, void>[] | null = null;\n\n /**\n * @param initialTeardown A function executed first as part of the finalization\n * process that is kicked off when {@link #unsubscribe} is called.\n */\n constructor(private initialTeardown?: () => void) {}\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 */\n unsubscribe(): void {\n let errors: any[] | undefined;\n\n if (!this.closed) {\n this.closed = true;\n\n // Remove this from it's parents.\n const { _parentage } = this;\n if (_parentage) {\n this._parentage = null;\n if (Array.isArray(_parentage)) {\n for (const parent of _parentage) {\n parent.remove(this);\n }\n } else {\n _parentage.remove(this);\n }\n }\n\n const { initialTeardown: initialFinalizer } = this;\n if (isFunction(initialFinalizer)) {\n try {\n initialFinalizer();\n } catch (e) {\n errors = e instanceof UnsubscriptionError ? e.errors : [e];\n }\n }\n\n const { _finalizers } = this;\n if (_finalizers) {\n this._finalizers = null;\n for (const finalizer of _finalizers) {\n try {\n execFinalizer(finalizer);\n } catch (err) {\n errors = errors ?? [];\n if (err instanceof UnsubscriptionError) {\n errors = [...errors, ...err.errors];\n } else {\n errors.push(err);\n }\n }\n }\n }\n\n if (errors) {\n throw new UnsubscriptionError(errors);\n }\n }\n }\n\n /**\n * Adds a finalizer to this subscription, so that finalization will be unsubscribed/called\n * when this subscription is unsubscribed. If this subscription is already {@link #closed},\n * because it has already been unsubscribed, then whatever finalizer is passed to it\n * will automatically be executed (unless the finalizer itself is also a closed subscription).\n *\n * Closed Subscriptions cannot be added as finalizers to any subscription. Adding a closed\n * subscription to a any subscription will result in no operation. (A noop).\n *\n * Adding a subscription to itself, or adding `null` or `undefined` will not perform any\n * operation at all. (A noop).\n *\n * `Subscription` instances that are added to this instance will automatically remove themselves\n * if they are unsubscribed. Functions and {@link Unsubscribable} objects that you wish to remove\n * will need to be removed manually with {@link #remove}\n *\n * @param teardown The finalization logic to add to this subscription.\n */\n add(teardown: TeardownLogic): void {\n // Only add the finalizer if it's not undefined\n // and don't add a subscription to itself.\n if (teardown && teardown !== this) {\n if (this.closed) {\n // If this subscription is already closed,\n // execute whatever finalizer is handed to it automatically.\n execFinalizer(teardown);\n } else {\n if (teardown instanceof Subscription) {\n // We don't add closed subscriptions, and we don't add the same subscription\n // twice. Subscription unsubscribe is idempotent.\n if (teardown.closed || teardown._hasParent(this)) {\n return;\n }\n teardown._addParent(this);\n }\n (this._finalizers = this._finalizers ?? []).push(teardown);\n }\n }\n }\n\n /**\n * Checks to see if a this subscription already has a particular parent.\n * This will signal that this subscription has already been added to the parent in question.\n * @param parent the parent to check for\n */\n private _hasParent(parent: Subscription) {\n const { _parentage } = this;\n return _parentage === parent || (Array.isArray(_parentage) && _parentage.includes(parent));\n }\n\n /**\n * Adds a parent to this subscription so it can be removed from the parent if it\n * unsubscribes on it's own.\n *\n * NOTE: THIS ASSUMES THAT {@link _hasParent} HAS ALREADY BEEN CHECKED.\n * @param parent The parent subscription to add\n */\n private _addParent(parent: Subscription) {\n const { _parentage } = this;\n this._parentage = Array.isArray(_parentage) ? (_parentage.push(parent), _parentage) : _parentage ? [_parentage, parent] : parent;\n }\n\n /**\n * Called on a child when it is removed via {@link #remove}.\n * @param parent The parent to remove\n */\n private _removeParent(parent: Subscription) {\n const { _parentage } = this;\n if (_parentage === parent) {\n this._parentage = null;\n } else if (Array.isArray(_parentage)) {\n arrRemove(_parentage, parent);\n }\n }\n\n /**\n * Removes a finalizer from this subscription that was previously added with the {@link #add} method.\n *\n * Note that `Subscription` instances, when unsubscribed, will automatically remove themselves\n * from every other `Subscription` they have been added to. This means that using the `remove` method\n * is not a common thing and should be used thoughtfully.\n *\n * If you add the same finalizer instance of a function or an unsubscribable object to a `Subscription` instance\n * more than once, you will need to call `remove` the same number of times to remove all instances.\n *\n * All finalizer instances are removed to free up memory upon unsubscription.\n *\n * @param teardown The finalizer to remove from this subscription\n */\n remove(teardown: Exclude<TeardownLogic, void>): void {\n const { _finalizers } = this;\n _finalizers && arrRemove(_finalizers, teardown);\n\n if (teardown instanceof Subscription) {\n teardown._removeParent(this);\n }\n }\n}\n\nexport const EMPTY_SUBSCRIPTION = Subscription.EMPTY;\n\nexport function isSubscription(value: any): value is Subscription {\n return (\n value instanceof Subscription ||\n (value && 'closed' in value && isFunction(value.remove) && isFunction(value.add) && isFunction(value.unsubscribe))\n );\n}\n\nfunction execFinalizer(finalizer: Unsubscribable | (() => void)) {\n if (isFunction(finalizer)) {\n finalizer();\n } else {\n finalizer.unsubscribe();\n }\n}\n","import { Subscriber } from './Subscriber';\nimport { ObservableNotification } from './types';\n\n/**\n * The {@link GlobalConfig} object for RxJS. It is used to configure things\n * like how to react on unhandled errors.\n */\nexport const config: GlobalConfig = {\n onUnhandledError: null,\n onStoppedNotification: null,\n Promise: undefined,\n useDeprecatedSynchronousErrorHandling: false,\n useDeprecatedNextContext: false,\n};\n\n/**\n * The global configuration object for RxJS, used to configure things\n * like how to react on unhandled errors. Accessible via {@link config}\n * object.\n */\nexport interface GlobalConfig {\n /**\n * A registration point for unhandled errors from RxJS. These are errors that\n * cannot were not handled by consuming code in the usual subscription path. For\n * example, if you have this configured, and you subscribe to an observable without\n * providing an error handler, errors from that subscription will end up here. This\n * will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onUnhandledError: ((err: any) => void) | null;\n\n /**\n * A registration point for notifications that cannot be sent to subscribers because they\n * have completed, errored or have been explicitly unsubscribed. By default, next, complete\n * and error notifications sent to stopped subscribers are noops. However, sometimes callers\n * might want a different behavior. For example, with sources that attempt to report errors\n * to stopped subscribers, a caller can configure RxJS to throw an unhandled error instead.\n * This will _always_ be called asynchronously on another job in the runtime. This is because\n * we do not want errors thrown in this user-configured handler to interfere with the\n * behavior of the library.\n */\n onStoppedNotification: ((notification: ObservableNotification<any>, subscriber: Subscriber<any>) => void) | null;\n\n /**\n * The promise constructor used by default for {@link Observable#toPromise toPromise} and {@link Observable#forEach forEach}\n * methods.\n *\n * @deprecated As of version 8, RxJS will no longer support this sort of injection of a\n * Promise constructor. If you need a Promise implementation other than native promises,\n * please polyfill/patch Promise as you see appropriate. Will be removed in v8.\n */\n Promise?: 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 BUY TIME\n * FOR MIGRATION REASONS.\n *\n * @deprecated As of version 8, RxJS will no longer support synchronous throwing\n * of unhandled errors. All errors will be thrown on a separate call stack to prevent bad\n * behaviors described above. Will be removed in v8.\n */\n useDeprecatedSynchronousErrorHandling: boolean;\n\n /**\n * If true, enables an as-of-yet undocumented feature from v5: The ability to access\n * `unsubscribe()` via `this` context in `next` functions created in observers passed\n * to `subscribe`.\n *\n * This is being removed because the performance was severely problematic, and it could also cause\n * issues when types other than POJOs are passed to subscribe as subscribers, as they will likely have\n * their `this` context overwritten.\n *\n * @deprecated As of version 8, RxJS will no longer support altering the\n * context of next functions provided as part of an observer to Subscribe. Instead,\n * you will have access to a subscription or a signal or token that will allow you to do things like\n * unsubscribe and test closed status. Will be removed in v8.\n */\n useDeprecatedNextContext: boolean;\n}\n","import type { TimerHandle } from './timerHandle';\ntype SetTimeoutFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearTimeoutFunction = (handle: TimerHandle) => void;\n\ninterface TimeoutProvider {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n delegate:\n | {\n setTimeout: SetTimeoutFunction;\n clearTimeout: ClearTimeoutFunction;\n }\n | undefined;\n}\n\nexport const timeoutProvider: TimeoutProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setTimeout(handler: () => void, timeout?: number, ...args) {\n const { delegate } = timeoutProvider;\n if (delegate?.setTimeout) {\n return delegate.setTimeout(handler, timeout, ...args);\n }\n return setTimeout(handler, timeout, ...args);\n },\n clearTimeout(handle) {\n const { delegate } = timeoutProvider;\n return (delegate?.clearTimeout || clearTimeout)(handle as any);\n },\n delegate: undefined,\n};\n","import { config } from '../config';\nimport { timeoutProvider } from '../scheduler/timeoutProvider';\n\n/**\n * Handles an error on another job either with the user-configured {@link onUnhandledError},\n * or by throwing it on that new job so it can be picked up by `window.onerror`, `process.on('error')`, etc.\n *\n * This should be called whenever there is an error that is out-of-band with the subscription\n * or when an error hits a terminal boundary of the subscription and no error handler was provided.\n *\n * @param err the error to report\n */\nexport function reportUnhandledError(err: any) {\n timeoutProvider.setTimeout(() => {\n const { onUnhandledError } = config;\n if (onUnhandledError) {\n // Execute the user-configured error handler.\n onUnhandledError(err);\n } else {\n // Throw so it is picked up by the runtime's uncaught error mechanism.\n throw err;\n }\n });\n}\n","/* tslint:disable:no-empty */\nexport function noop() { }\n","import { CompleteNotification, NextNotification, ErrorNotification } from './types';\n\n/**\n * A completion object optimized for memory use and created to be the\n * same \"shape\" as other notifications in v8.\n * @internal\n */\nexport const COMPLETE_NOTIFICATION = (() => createNotification('C', undefined, undefined) as CompleteNotification)();\n\n/**\n * Internal use only. Creates an optimized error notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function errorNotification(error: any): ErrorNotification {\n return createNotification('E', undefined, error) as any;\n}\n\n/**\n * Internal use only. Creates an optimized next notification that is the same \"shape\"\n * as other notifications.\n * @internal\n */\nexport function nextNotification<T>(value: T) {\n return createNotification('N', value, undefined) as NextNotification<T>;\n}\n\n/**\n * Ensures that all notifications created internally have the same \"shape\" in v8.\n *\n * TODO: This is only exported to support a crazy legacy test in `groupBy`.\n * @internal\n */\nexport function createNotification(kind: 'N' | 'E' | 'C', value: any, error: any) {\n return {\n kind,\n value,\n error,\n };\n}\n","import { config } from '../config';\n\nlet context: { errorThrown: boolean; error: any } | null = null;\n\n/**\n * Handles dealing with errors for super-gross mode. Creates a context, in which\n * any synchronously thrown errors will be passed to {@link captureError}. Which\n * will record the error such that it will be rethrown after the call back is complete.\n * TODO: Remove in v8\n * @param cb An immediately executed function.\n */\nexport function errorContext(cb: () => void) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n const isRoot = !context;\n if (isRoot) {\n context = { errorThrown: false, error: null };\n }\n cb();\n if (isRoot) {\n const { errorThrown, error } = context!;\n context = null;\n if (errorThrown) {\n throw error;\n }\n }\n } else {\n // This is the general non-deprecated path for everyone that\n // isn't crazy enough to use super-gross mode (useDeprecatedSynchronousErrorHandling)\n cb();\n }\n}\n\n/**\n * Captures errors only in super-gross mode.\n * @param err the error to capture\n */\nexport function captureError(err: any) {\n if (config.useDeprecatedSynchronousErrorHandling && context) {\n context.errorThrown = true;\n context.error = err;\n }\n}\n","import { isFunction } from './util/isFunction';\nimport { Observer, ObservableNotification } from './types';\nimport { isSubscription, Subscription } from './Subscription';\nimport { config } from './config';\nimport { reportUnhandledError } from './util/reportUnhandledError';\nimport { noop } from './util/noop';\nimport { nextNotification, errorNotification, COMPLETE_NOTIFICATION } from './NotificationFactories';\nimport { timeoutProvider } from './scheduler/timeoutProvider';\nimport { captureError } from './util/errorContext';\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 */\nexport class Subscriber<T> extends Subscription implements Observer<T> {\n /**\n * A static factory for a Subscriber, given a (potentially partial) definition\n * of an Observer.\n * @param next The `next` callback of an Observer.\n * @param error The `error` callback of an\n * Observer.\n * @param complete The `complete` callback of an\n * Observer.\n * @return A Subscriber wrapping the (partially defined)\n * Observer represented by the given arguments.\n * @deprecated Do not use. Will be removed in v8. There is no replacement for this\n * method, and there is no reason to be creating instances of `Subscriber` directly.\n * If you have a specific use case, please file an issue.\n */\n static create<T>(next?: (x?: T) => void, error?: (e?: any) => void, complete?: () => void): Subscriber<T> {\n return new SafeSubscriber(next, error, complete);\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected isStopped: boolean = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n protected destination: Subscriber<any> | Observer<any>; // this `any` is the escape hatch to erase extra type param (e.g. R)\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * There is no reason to directly create an instance of Subscriber. This type is exported for typings reasons.\n */\n constructor(destination?: Subscriber<any> | Observer<any>) {\n super();\n if (destination) {\n this.destination = destination;\n // Automatically chain subscriptions together here.\n // if destination is a Subscription, then it is a Subscriber.\n if (isSubscription(destination)) {\n destination.add(this);\n }\n } else {\n this.destination = EMPTY_OBSERVER;\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 value The `next` value.\n */\n next(value: T): void {\n if (this.isStopped) {\n handleStoppedNotification(nextNotification(value), this);\n } else {\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 err The `error` exception.\n */\n error(err?: any): void {\n if (this.isStopped) {\n handleStoppedNotification(errorNotification(err), this);\n } else {\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 */\n complete(): void {\n if (this.isStopped) {\n handleStoppedNotification(COMPLETE_NOTIFICATION, this);\n } else {\n this.isStopped = true;\n this._complete();\n }\n }\n\n unsubscribe(): void {\n if (!this.closed) {\n this.isStopped = true;\n super.unsubscribe();\n this.destination = null!;\n }\n }\n\n protected _next(value: T): void {\n this.destination.next(value);\n }\n\n protected _error(err: any): void {\n try {\n this.destination.error(err);\n } finally {\n this.unsubscribe();\n }\n }\n\n protected _complete(): void {\n try {\n this.destination.complete();\n } finally {\n this.unsubscribe();\n }\n }\n}\n\n/**\n * This bind is captured here because we want to be able to have\n * compatibility with monoid libraries that tend to use a method named\n * `bind`. In particular, a library called Monio requires this.\n */\nconst _bind = Function.prototype.bind;\n\nfunction bind<Fn extends (...args: any[]) => any>(fn: Fn, thisArg: any): Fn {\n return _bind.call(fn, thisArg);\n}\n\n/**\n * Internal optimization only, DO NOT EXPOSE.\n * @internal\n */\nclass ConsumerObserver<T> implements Observer<T> {\n constructor(private partialObserver: Partial<Observer<T>>) {}\n\n next(value: T): void {\n const { partialObserver } = this;\n if (partialObserver.next) {\n try {\n partialObserver.next(value);\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n\n error(err: any): void {\n const { partialObserver } = this;\n if (partialObserver.error) {\n try {\n partialObserver.error(err);\n } catch (error) {\n handleUnhandledError(error);\n }\n } else {\n handleUnhandledError(err);\n }\n }\n\n complete(): void {\n const { partialObserver } = this;\n if (partialObserver.complete) {\n try {\n partialObserver.complete();\n } catch (error) {\n handleUnhandledError(error);\n }\n }\n }\n}\n\nexport class SafeSubscriber<T> extends Subscriber<T> {\n constructor(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((e?: any) => void) | null,\n complete?: (() => void) | null\n ) {\n super();\n\n let partialObserver: Partial<Observer<T>>;\n if (isFunction(observerOrNext) || !observerOrNext) {\n // The first argument is a function, not an observer. The next\n // two arguments *could* be observers, or they could be empty.\n partialObserver = {\n next: (observerOrNext ?? undefined) as ((value: T) => void) | undefined,\n error: error ?? undefined,\n complete: complete ?? undefined,\n };\n } else {\n // The first argument is a partial observer.\n let context: any;\n if (this && config.useDeprecatedNextContext) {\n // This is a deprecated path that made `this.unsubscribe()` available in\n // next handler functions passed to subscribe. This only exists behind a flag\n // now, as it is *very* slow.\n context = Object.create(observerOrNext);\n context.unsubscribe = () => this.unsubscribe();\n partialObserver = {\n next: observerOrNext.next && bind(observerOrNext.next, context),\n error: observerOrNext.error && bind(observerOrNext.error, context),\n complete: observerOrNext.complete && bind(observerOrNext.complete, context),\n };\n } else {\n // The \"normal\" path. Just use the partial observer directly.\n partialObserver = observerOrNext;\n }\n }\n\n // Wrap the partial observer to ensure it's a full observer, and\n // make sure proper error handling is accounted for.\n this.destination = new ConsumerObserver(partialObserver);\n }\n}\n\nfunction handleUnhandledError(error: any) {\n if (config.useDeprecatedSynchronousErrorHandling) {\n captureError(error);\n } else {\n // Ideal path, we report this as an unhandled error,\n // which is thrown on a new call stack.\n reportUnhandledError(error);\n }\n}\n\n/**\n * An error handler used when no error handler was supplied\n * to the SafeSubscriber -- meaning no error handler was supplied\n * do the `subscribe` call on our observable.\n * @param err The error to handle\n */\nfunction defaultErrorHandler(err: any) {\n throw err;\n}\n\n/**\n * A handler for notifications that cannot be sent to a stopped subscriber.\n * @param notification The notification being sent.\n * @param subscriber The stopped subscriber.\n */\nfunction handleStoppedNotification(notification: ObservableNotification<any>, subscriber: Subscriber<any>) {\n const { onStoppedNotification } = config;\n onStoppedNotification && timeoutProvider.setTimeout(() => onStoppedNotification(notification, subscriber));\n}\n\n/**\n * The observer used as a stub for subscriptions where the user did not\n * pass any arguments to `subscribe`. Comes with the default error handling\n * behavior.\n */\nexport const EMPTY_OBSERVER: Readonly<Observer<any>> & { closed: true } = {\n closed: true,\n next: noop,\n error: defaultErrorHandler,\n complete: noop,\n};\n","/**\n * Symbol.observable or a string \"@@observable\". Used for interop\n *\n * @deprecated We will no longer be exporting this symbol in upcoming versions of RxJS.\n * Instead polyfill and use Symbol.observable directly *or* use https://www.npmjs.com/package/symbol-observable\n */\nexport const observable: string | symbol = (() => (typeof Symbol === 'function' && Symbol.observable) || '@@observable')();\n","/**\n * This function takes one parameter and just returns it. Simply put,\n * this is like `<T>(x: T): T => x`.\n *\n * ## Examples\n *\n * This is useful in some cases when using things like `mergeMap`\n *\n * ```ts\n * import { interval, take, map, range, mergeMap, identity } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(5));\n *\n * const result$ = source$.pipe(\n * map(i => range(i)),\n * mergeMap(identity) // same as mergeMap(x => x)\n * );\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * Or when you want to selectively apply an operator\n *\n * ```ts\n * import { interval, take, identity } from 'rxjs';\n *\n * const shouldLimit = () => Math.random() < 0.5;\n *\n * const source$ = interval(1000);\n *\n * const result$ = source$.pipe(shouldLimit() ? take(5) : identity);\n *\n * result$.subscribe({\n * next: console.log\n * });\n * ```\n *\n * @param x Any value that is returned by this function\n * @returns The value passed as the first parameter to this function\n */\nexport function identity<T>(x: T): T {\n return x;\n}\n","import { identity } from './identity';\nimport { UnaryFunction } from '../types';\n\nexport function pipe(): typeof identity;\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>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>\n): UnaryFunction<T, D>;\nexport function pipe<T, A, B, C, D, E>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>\n): UnaryFunction<T, E>;\nexport function pipe<T, A, B, C, D, E, F>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>\n): UnaryFunction<T, F>;\nexport function pipe<T, A, B, C, D, E, F, G>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>\n): UnaryFunction<T, G>;\nexport function pipe<T, A, B, C, D, E, F, G, H>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>\n): UnaryFunction<T, H>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>\n): UnaryFunction<T, I>;\nexport function pipe<T, A, B, C, D, E, F, G, H, I>(\n fn1: UnaryFunction<T, A>,\n fn2: UnaryFunction<A, B>,\n fn3: UnaryFunction<B, C>,\n fn4: UnaryFunction<C, D>,\n fn5: UnaryFunction<D, E>,\n fn6: UnaryFunction<E, F>,\n fn7: UnaryFunction<F, G>,\n fn8: UnaryFunction<G, H>,\n fn9: UnaryFunction<H, I>,\n ...fns: UnaryFunction<any, any>[]\n): UnaryFunction<T, unknown>;\n\n/**\n * pipe() can be called on one or more functions, each of which can take one argument (\"UnaryFunction\")\n * and uses it to return a value.\n * It returns a function that takes one argument, passes it to the first UnaryFunction, and then\n * passes the result to the next one, passes that result to the next one, and so on. \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 { SafeSubscriber, Subscriber } from './Subscriber';\nimport { isSubscription, Subscription } from './Subscription';\nimport { TeardownLogic, OperatorFunction, Subscribable, Observer } from './types';\nimport { observable as Symbol_observable } from './symbol/observable';\nimport { pipeFromArray } from './util/pipe';\nimport { config } from './config';\nimport { isFunction } from './util/isFunction';\nimport { errorContext } from './util/errorContext';\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 */\nexport class Observable<T> implements Subscribable<T> {\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n source: Observable<any> | undefined;\n\n /**\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n operator: Operator<any, T> | undefined;\n\n /**\n * @param 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 Observable by calling the Observable constructor\n * @param subscribe the subscriber function to be passed to the Observable constructor\n * @return A new observable.\n * @deprecated Use `new Observable()` instead. Will be removed in v8.\n */\n static create: (...args: any[]) => any = <T>(subscribe?: (subscriber: Subscriber<T>) => TeardownLogic) => {\n return new Observable<T>(subscribe);\n };\n\n /**\n * Creates a new Observable, with this Observable instance as the source, and the passed\n * operator defined as the new observable's operator.\n * @param operator the operator defining the operation to take on the observable\n * @return A new observable with the Operator applied.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n * If you have implemented an operator using `lift`, it is recommended that you create an\n * operator by simply returning `new Observable()` directly. See \"Creating new operators from\n * scratch\" section here: https://rxjs.dev/guide/operators\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(observerOrNext?: Partial<Observer<T>> | ((value: T) => void)): Subscription;\n /** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\n subscribe(next?: ((value: T) => void) | null, error?: ((error: any) => void) | null, complete?: (() => void) | null): 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 and an error happens,\n * it will be thrown asynchronously. Errors thrown asynchronously cannot be caught using `try`/`catch`. Instead,\n * use the {@link onUnhandledError} configuration option or use a runtime handler (like `window.onerror` or\n * `process.on('error)`) to be notified of unhandled errors. Because of this, it's recommended that you provide\n * an `error` method to avoid missing thrown errors.\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 an Observer,\n * if you do not need to listen for something, you can omit a function by passing `undefined` or `null`,\n * since `subscribe` recognizes these functions by where they were placed in function call. When it comes\n * to the `error` function, as with an Observer, if not provided, errors emitted by an Observable will be thrown asynchronously.\n *\n * You can, however, subscribe with no parameters at all. This may be the case where you're not interested in terminal events\n * and you also handled emissions internally by using operators (e.g. using `tap`).\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 * #### Examples\n *\n * Subscribe with an {@link guide/observer Observer}\n *\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 ({@link deprecations/subscribe-arguments deprecated})\n *\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 *\n * ```ts\n * import { interval } from 'rxjs';\n *\n * const subscription = interval(1000).subscribe({\n * next(num) {\n * console.log(num)\n * },\n * complete() {\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 observerOrNext Either an {@link Observer} with some or all callback methods,\n * or the `next` handler that is called for each value emitted from the subscribed Observable.\n * @param error A handler for a terminal event resulting from an error. If no error handler is provided,\n * the error will be thrown asynchronously as unhandled.\n * @param complete A handler for a terminal event resulting from successful completion.\n * @return A subscription reference to the registered handlers.\n */\n subscribe(\n observerOrNext?: Partial<Observer<T>> | ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n ): Subscription {\n const subscriber = isSubscriber(observerOrNext) ? observerOrNext : new SafeSubscriber(observerOrNext, error, complete);\n\n errorContext(() => {\n const { operator, source } = this;\n subscriber.add(\n operator\n ? // We're dealing with a subscription in the\n // operator chain to one of our lifted operators.\n operator.call(subscriber, source)\n : source\n ? // If `source` has a value, but `operator` does not, something that\n // had intimate knowledge of our API, like our `Subject`, must have\n // set it. We're going to just call `_subscribe` directly.\n this._subscribe(subscriber)\n : // In all other cases, we're likely wrapping a user-provided initializer\n // function, so we need to catch errors and handle them appropriately.\n this._trySubscribe(subscriber)\n );\n });\n\n return subscriber;\n }\n\n /** @internal */\n protected _trySubscribe(sink: Subscriber<T>): TeardownLogic {\n try {\n return this._subscribe(sink);\n } catch (err) {\n // We don't need to return anything in this case,\n // because it's just going to try to `add()` to a subscription\n // above.\n sink.error(err);\n }\n }\n\n /**\n * Used as a NON-CANCELLABLE means of subscribing to an observable, for use with\n * APIs that expect promises, like `async/await`. You cannot unsubscribe from this.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * #### Example\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const source$ = interval(1000).pipe(take(4));\n *\n * async function getTotal() {\n * let total = 0;\n *\n * await source$.forEach(value => {\n * total += value;\n * console.log('observable -> ' + value);\n * });\n *\n * return total;\n * }\n *\n * getTotal().then(\n * total => console.log('Total: ' + total)\n * );\n *\n * // Expected:\n * // 'observable -> 0'\n * // 'observable -> 1'\n * // 'observable -> 2'\n * // 'observable -> 3'\n * // 'Total: 6'\n * ```\n *\n * @param next A handler for each value emitted by the observable.\n * @return A promise that either resolves on observable completion or\n * rejects with the handled error.\n */\n forEach(next: (value: T) => void): Promise<void>;\n\n /**\n * @param next a handler for each value emitted by the observable\n * @param promiseCtor a constructor function used to instantiate the Promise\n * @return a promise that either resolves on observable completion or\n * rejects with the handled error\n * @deprecated Passing a Promise constructor will no longer be available\n * in upcoming versions of RxJS. This is because it adds weight to the library, for very\n * little benefit. If you need this functionality, it is recommended that you either\n * polyfill Promise, or you create an adapter to convert the returned native promise\n * to whatever promise implementation you wanted. Will be removed in v8.\n */\n forEach(next: (value: T) => void, promiseCtor: PromiseConstructorLike): Promise<void>;\n\n forEach(next: (value: T) => void, promiseCtor?: PromiseConstructorLike): Promise<void> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor<void>((resolve, reject) => {\n const subscriber = new SafeSubscriber<T>({\n next: (value) => {\n try {\n next(value);\n } catch (err) {\n reject(err);\n subscriber.unsubscribe();\n }\n },\n error: reject,\n complete: resolve,\n });\n this.subscribe(subscriber);\n }) as Promise<void>;\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<any>): TeardownLogic {\n return this.source?.subscribe(subscriber);\n }\n\n /**\n * An interop point defined by the es7-observable spec https://github.com/zenparsing/es-observable\n * @return 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>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>\n ): Observable<D>;\n pipe<A, B, C, D, E>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>\n ): Observable<E>;\n pipe<A, B, C, D, E, F>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>\n ): Observable<F>;\n pipe<A, B, C, D, E, F, G>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>\n ): Observable<G>;\n pipe<A, B, C, D, E, F, G, H>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>\n ): Observable<H>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>\n ): Observable<I>;\n pipe<A, B, C, D, E, F, G, H, I>(\n op1: OperatorFunction<T, A>,\n op2: OperatorFunction<A, B>,\n op3: OperatorFunction<B, C>,\n op4: OperatorFunction<C, D>,\n op5: OperatorFunction<D, E>,\n op6: OperatorFunction<E, F>,\n op7: OperatorFunction<F, G>,\n op8: OperatorFunction<G, H>,\n op9: OperatorFunction<H, I>,\n ...operations: OperatorFunction<any, any>[]\n ): Observable<unknown>;\n /* tslint:enable:max-line-length */\n\n /**\n * Used to stitch together functional operators into a chain.\n *\n * ## Example\n *\n * ```ts\n * import { interval, filter, map, scan } from 'rxjs';\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 * @return The Observable result of all the operators having been called\n * in the order they were passed in.\n */\n pipe(...operations: OperatorFunction<any, any>[]): Observable<any> {\n return pipeFromArray(operations)(this);\n }\n\n /* tslint:disable:max-line-length */\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: typeof Promise): Promise<T | undefined>;\n /** @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise */\n toPromise(PromiseCtor: PromiseConstructorLike): Promise<T | undefined>;\n /* tslint:enable:max-line-length */\n\n /**\n * Subscribe to this Observable and get a Promise resolving on\n * `complete` with the last emission (if any).\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * @param [promiseCtor] a constructor function used to instantiate\n * the Promise\n * @return A Promise that resolves with the last value emit, or\n * rejects on an error. If there were no emissions, Promise\n * resolves with undefined.\n * @deprecated Replaced with {@link firstValueFrom} and {@link lastValueFrom}. Will be removed in v8. Details: https://rxjs.dev/deprecations/to-promise\n */\n toPromise(promiseCtor?: PromiseConstructorLike): Promise<T | undefined> {\n promiseCtor = getPromiseCtor(promiseCtor);\n\n return new promiseCtor((resolve, reject) => {\n let value: T | undefined;\n this.subscribe(\n (x: T) => (value = x),\n (err: any) => reject(err),\n () => resolve(value)\n );\n }) as Promise<T | undefined>;\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 return promiseCtor ?? config.Promise ?? Promise;\n}\n\nfunction isObserver<T>(value: any): value is Observer<T> {\n return value && isFunction(value.next) && isFunction(value.error) && isFunction(value.complete);\n}\n\nfunction isSubscriber<T>(value: any): value is Subscriber<T> {\n return (value && value instanceof Subscriber) || (isObserver(value) && isSubscription(value));\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction } from '../types';\nimport { isFunction } from './isFunction';\n\n/**\n * Used to determine if an object is an Observable with a lift function.\n */\nexport function hasLift(source: any): source is { lift: InstanceType<typeof Observable>['lift'] } {\n return isFunction(source?.lift);\n}\n\n/**\n * Creates an `OperatorFunction`. Used to define operators throughout the library in a concise way.\n * @param init The logic to connect the liftedSource to the subscriber at the moment of subscription.\n */\nexport function operate<T, R>(\n init: (liftedSource: Observable<T>, subscriber: Subscriber<R>) => (() => void) | void\n): OperatorFunction<T, R> {\n return (source: Observable<T>) => {\n if (hasLift(source)) {\n return source.lift(function (this: Subscriber<R>, liftedSource: Observable<T>) {\n try {\n return init(liftedSource, this);\n } catch (err) {\n this.error(err);\n }\n });\n }\n throw new TypeError('Unable to lift unknown Observable type');\n };\n}\n","import { Subscriber } from '../Subscriber';\n\n/**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional teardown logic here. This will only be called on teardown if the\n * subscriber itself is not already closed. This is called after all other teardown logic is executed.\n */\nexport function createOperatorSubscriber<T>(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n onFinalize?: () => void\n): Subscriber<T> {\n return new OperatorSubscriber(destination, onNext, onComplete, onError, onFinalize);\n}\n\n/**\n * A generic helper for allowing operators to be created with a Subscriber and\n * use closures to capture necessary state from the operator function itself.\n */\nexport class OperatorSubscriber<T> extends Subscriber<T> {\n /**\n * Creates an instance of an `OperatorSubscriber`.\n * @param destination The downstream subscriber.\n * @param onNext Handles next values, only called if this subscriber is not stopped or closed. Any\n * error that occurs in this function is caught and sent to the `error` method of this subscriber.\n * @param onError Handles errors from the subscription, any errors that occur in this handler are caught\n * and send to the `destination` error handler.\n * @param onComplete Handles completion notification from the subscription. Any errors that occur in\n * this handler are sent to the `destination` error handler.\n * @param onFinalize Additional finalization logic here. This will only be called on finalization if the\n * subscriber itself is not already closed. This is called after all other finalization logic is executed.\n * @param shouldUnsubscribe An optional check to see if an unsubscribe call should truly unsubscribe.\n * NOTE: This currently **ONLY** exists to support the strange behavior of {@link groupBy}, where unsubscription\n * to the resulting observable does not actually disconnect from the source if there are active subscriptions\n * to any grouped observable. (DO NOT EXPOSE OR USE EXTERNALLY!!!)\n */\n constructor(\n destination: Subscriber<any>,\n onNext?: (value: T) => void,\n onComplete?: () => void,\n onError?: (err: any) => void,\n private onFinalize?: () => void,\n private shouldUnsubscribe?: () => boolean\n ) {\n // It's important - for performance reasons - that all of this class's\n // members are initialized and that they are always initialized in the same\n // order. This will ensure that all OperatorSubscriber instances have the\n // same hidden class in V8. This, in turn, will help keep the number of\n // hidden classes involved in property accesses within the base class as\n // low as possible. If the number of hidden classes involved exceeds four,\n // the property accesses will become megamorphic and performance penalties\n // will be incurred - i.e. inline caches won't be used.\n //\n // The reasons for ensuring all instances have the same hidden class are\n // further discussed in this blog post from Benedikt Meurer:\n // https://benediktmeurer.de/2018/03/23/impact-of-polymorphism-on-component-based-frameworks-like-react/\n super(destination);\n this._next = onNext\n ? function (this: OperatorSubscriber<T>, value: T) {\n try {\n onNext(value);\n } catch (err) {\n destination.error(err);\n }\n }\n : super._next;\n this._error = onError\n ? function (this: OperatorSubscriber<T>, err: any) {\n try {\n onError(err);\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._error;\n this._complete = onComplete\n ? function (this: OperatorSubscriber<T>) {\n try {\n onComplete();\n } catch (err) {\n // Send any errors that occur down stream.\n destination.error(err);\n } finally {\n // Ensure finalization.\n this.unsubscribe();\n }\n }\n : super._complete;\n }\n\n unsubscribe() {\n if (!this.shouldUnsubscribe || this.shouldUnsubscribe()) {\n const { closed } = this;\n super.unsubscribe();\n // Execute additional teardown if we have any and we didn't already do so.\n !closed && this.onFinalize?.();\n }\n }\n}\n","import { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Make a {@link ConnectableObservable} behave like a ordinary observable and automates the way\n * you can connect to it.\n *\n * Internally it counts the subscriptions to the observable and subscribes (only once) to the source if\n * the number of subscriptions is larger than 0. If the number of subscriptions is smaller than 1, it\n * unsubscribes from the source. This way you can make sure that everything before the *published*\n * refCount has only a single subscription independently of the number of subscribers to the target\n * observable.\n *\n * Note that using the {@link share} operator is exactly the same as using the `multicast(() => new Subject())` operator\n * (making the observable hot) and the *refCount* operator in a sequence.\n *\n * ![](refCount.png)\n *\n * ## Example\n *\n * In the following example there are two intervals turned into connectable observables\n * by using the *publish* operator. The first one uses the *refCount* operator, the\n * second one does not use it. You will notice that a connectable observable does nothing\n * until you call its connect function.\n *\n * ```ts\n * import { interval, tap, publish, refCount } from 'rxjs';\n *\n * // Turn the interval observable into a ConnectableObservable (hot)\n * const refCountInterval = interval(400).pipe(\n * tap(num => console.log(`refCount ${ num }`)),\n * publish(),\n * refCount()\n * );\n *\n * const publishedInterval = interval(400).pipe(\n * tap(num => console.log(`publish ${ num }`)),\n * publish()\n * );\n *\n * refCountInterval.subscribe();\n * refCountInterval.subscribe();\n * // 'refCount 0' -----> 'refCount 1' -----> etc\n * // All subscriptions will receive the same value and the tap (and\n * // every other operator) before the `publish` operator will be executed\n * // only once per event independently of the number of subscriptions.\n *\n * publishedInterval.subscribe();\n * // Nothing happens until you call .connect() on the observable.\n * ```\n *\n * @return A function that returns an Observable that automates the connection\n * to ConnectableObservable.\n * @see {@link ConnectableObservable}\n * @see {@link share}\n * @see {@link publish}\n * @deprecated Replaced with the {@link share} operator. How `share` is used\n * will depend on the connectable observable you created just prior to the\n * `refCount` operator.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function refCount<T>(): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let connection: Subscription | null = null;\n\n (source as any)._refCount++;\n\n const refCounter = createOperatorSubscriber(subscriber, undefined, undefined, undefined, () => {\n if (!source || (source as any)._refCount <= 0 || 0 < --(source as any)._refCount) {\n connection = null;\n return;\n }\n\n ///\n // Compare the local RefCountSubscriber's connection Subscription to the\n // connection Subscription on the shared ConnectableObservable. In cases\n // where the ConnectableObservable source synchronously emits values, and\n // the RefCountSubscriber's downstream Observers synchronously unsubscribe,\n // execution continues to here before the RefCountOperator has a chance to\n // supply the RefCountSubscriber with the shared connection Subscription.\n // For example:\n // ```\n // range(0, 10).pipe(\n // publish(),\n // refCount(),\n // take(5),\n // )\n // .subscribe();\n // ```\n // In order to account for this case, RefCountSubscriber should only dispose\n // the ConnectableObservable's shared connection Subscription if the\n // connection Subscription exists, *and* either:\n // a. RefCountSubscriber doesn't have a reference to the shared connection\n // Subscription yet, or,\n // b. RefCountSubscriber's connection Subscription reference is identical\n // to the shared connection Subscription\n ///\n\n const sharedConnection = (source as any)._connection;\n const conn = connection;\n connection = null;\n\n if (sharedConnection && (!conn || sharedConnection === conn)) {\n sharedConnection.unsubscribe();\n }\n\n subscriber.unsubscribe();\n });\n\n source.subscribe(refCounter);\n\n if (!refCounter.closed) {\n connection = (source as ConnectableObservable<T>).connect();\n }\n });\n}\n","import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { refCount as higherOrderRefCount } from '../operators/refCount';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { hasLift } from '../util/lift';\n\n/**\n * @class ConnectableObservable<T>\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * If you are using the `refCount` method of `ConnectableObservable`, use the {@link share} operator\n * instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport class ConnectableObservable<T> extends Observable<T> {\n protected _subject: Subject<T> | null = null;\n protected _refCount: number = 0;\n protected _connection: Subscription | null = null;\n\n /**\n * @param source The source observable\n * @param subjectFactory The factory that creates the subject used internally.\n * @deprecated Will be removed in v8. Use {@link connectable} to create a connectable observable.\n * `new ConnectableObservable(source, factory)` is equivalent to\n * `connectable(source, { connector: factory })`.\n * When the `refCount()` method is needed, the {@link share} operator should be used instead:\n * `new ConnectableObservable(source, factory).refCount()` is equivalent to\n * `source.pipe(share({ connector: factory }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n constructor(public source: Observable<T>, protected subjectFactory: () => Subject<T>) {\n super();\n // If we have lift, monkey patch that here. This is done so custom observable\n // types will compose through multicast. Otherwise the resulting observable would\n // simply be an instance of `ConnectableObservable`.\n if (hasLift(source)) {\n this.lift = source.lift;\n }\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>) {\n return this.getSubject().subscribe(subscriber);\n }\n\n protected getSubject(): Subject<T> {\n const subject = this._subject;\n if (!subject || subject.isStopped) {\n this._subject = this.subjectFactory();\n }\n return this._subject!;\n }\n\n protected _teardown() {\n this._refCount = 0;\n const { _connection } = this;\n this._subject = this._connection = null;\n _connection?.unsubscribe();\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use {@link connectable} instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n connect(): Subscription {\n let connection = this._connection;\n if (!connection) {\n connection = this._connection = new Subscription();\n const subject = this.getSubject();\n connection.add(\n this.source.subscribe(\n createOperatorSubscriber(\n subject as any,\n undefined,\n () => {\n this._teardown();\n subject.complete();\n },\n (err) => {\n this._teardown();\n subject.error(err);\n },\n () => this._teardown()\n )\n )\n );\n\n if (connection.closed) {\n this._connection = null;\n connection = Subscription.EMPTY;\n }\n }\n return connection;\n }\n\n /**\n * @deprecated {@link ConnectableObservable} will be removed in v8. Use the {@link share} operator instead.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\n refCount(): Observable<T> {\n return higherOrderRefCount()(this) as Observable<T>;\n }\n}\n","import { TimestampProvider } from '../types';\n\ninterface PerformanceTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const performanceTimestampProvider: PerformanceTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (performanceTimestampProvider.delegate || performance).now();\n },\n delegate: undefined,\n};\n","import { Subscription } from '../Subscription';\n\ninterface AnimationFrameProvider {\n schedule(callback: FrameRequestCallback): Subscription;\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n delegate:\n | {\n requestAnimationFrame: typeof requestAnimationFrame;\n cancelAnimationFrame: typeof cancelAnimationFrame;\n }\n | undefined;\n}\n\nexport const animationFrameProvider: AnimationFrameProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n schedule(callback) {\n let request = requestAnimationFrame;\n let cancel: typeof cancelAnimationFrame | undefined = cancelAnimationFrame;\n const { delegate } = animationFrameProvider;\n if (delegate) {\n request = delegate.requestAnimationFrame;\n cancel = delegate.cancelAnimationFrame;\n }\n const handle = request((timestamp) => {\n // Clear the cancel function. The request has been fulfilled, so\n // attempting to cancel the request upon unsubscription would be\n // pointless.\n cancel = undefined;\n callback(timestamp);\n });\n return new Subscription(() => cancel?.(handle));\n },\n requestAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.requestAnimationFrame || requestAnimationFrame)(...args);\n },\n cancelAnimationFrame(...args) {\n const { delegate } = animationFrameProvider;\n return (delegate?.cancelAnimationFrame || cancelAnimationFrame)(...args);\n },\n delegate: undefined,\n};\n","import { Observable } from '../../Observable';\nimport { TimestampProvider } from '../../types';\nimport { performanceTimestampProvider } from '../../scheduler/performanceTimestampProvider';\nimport { animationFrameProvider } from '../../scheduler/animationFrameProvider';\n\n/**\n * An observable of animation frames\n *\n * Emits the amount of time elapsed since subscription and the timestamp on each animation frame.\n * Defaults to milliseconds provided to the requestAnimationFrame's callback. Does not end on its own.\n *\n * Every subscription will start a separate animation loop. Since animation frames are always scheduled\n * by the browser to occur directly before a repaint, scheduling more than one animation frame synchronously\n * should not be much different or have more overhead than looping over an array of events during\n * a single animation frame. However, if for some reason the developer would like to ensure the\n * execution of animation-related handlers are all executed during the same task by the engine,\n * the `share` operator can be used.\n *\n * This is useful for setting up animations with RxJS.\n *\n * ## Examples\n *\n * Tweening a div to move it on the screen\n *\n * ```ts\n * import { animationFrames, map, takeWhile, endWith } from 'rxjs';\n *\n * function tween(start: number, end: number, duration: number) {\n * const diff = end - start;\n * return animationFrames().pipe(\n * // Figure out what percentage of time has passed\n * map(({ elapsed }) => elapsed / duration),\n * // Take the vector while less than 100%\n * takeWhile(v => v < 1),\n * // Finish with 100%\n * endWith(1),\n * // Calculate the distance traveled between start and end\n * map(v => v * diff + start)\n * );\n * }\n *\n * // Setup a div for us to move around\n * const div = document.createElement('div');\n * document.body.appendChild(div);\n * div.style.position = 'absolute';\n * div.style.width = '40px';\n * div.style.height = '40px';\n * div.style.backgroundColor = 'lime';\n * div.style.transform = 'translate3d(10px, 0, 0)';\n *\n * tween(10, 200, 4000).subscribe(x => {\n * div.style.transform = `translate3d(${ x }px, 0, 0)`;\n * });\n * ```\n *\n * Providing a custom timestamp provider\n *\n * ```ts\n * import { animationFrames, TimestampProvider } from 'rxjs';\n *\n * // A custom timestamp provider\n * let now = 0;\n * const customTSProvider: TimestampProvider = {\n * now() { return now++; }\n * };\n *\n * const source$ = animationFrames(customTSProvider);\n *\n * // Log increasing numbers 0...1...2... on every animation frame.\n * source$.subscribe(({ elapsed }) => console.log(elapsed));\n * ```\n *\n * @param timestampProvider An object with a `now` method that provides a numeric timestamp\n */\nexport function animationFrames(timestampProvider?: TimestampProvider) {\n return timestampProvider ? animationFramesFactory(timestampProvider) : DEFAULT_ANIMATION_FRAMES;\n}\n\n/**\n * Does the work of creating the observable for `animationFrames`.\n * @param timestampProvider The timestamp provider to use to create the observable\n */\nfunction animationFramesFactory(timestampProvider?: TimestampProvider) {\n return new Observable<{ timestamp: number; elapsed: number }>((subscriber) => {\n // If no timestamp provider is specified, use performance.now() - as it\n // will return timestamps 'compatible' with those passed to the run\n // callback and won't be affected by NTP adjustments, etc.\n const provider = timestampProvider || performanceTimestampProvider;\n\n // Capture the start time upon subscription, as the run callback can remain\n // queued for a considerable period of time and the elapsed time should\n // represent the time elapsed since subscription - not the time since the\n // first rendered animation frame.\n const start = provider.now();\n\n let id = 0;\n const run = () => {\n if (!subscriber.closed) {\n id = animationFrameProvider.requestAnimationFrame((timestamp: DOMHighResTimeStamp | number) => {\n id = 0;\n // Use the provider's timestamp to calculate the elapsed time. Note that\n // this means - if the caller hasn't passed a provider - that\n // performance.now() will be used instead of the timestamp that was\n // passed to the run callback. The reason for this is that the timestamp\n // passed to the callback can be earlier than the start time, as it\n // represents the time at which the browser decided it would render any\n // queued frames - and that time can be earlier the captured start time.\n const now = provider.now();\n subscriber.next({\n timestamp: timestampProvider ? now : timestamp,\n elapsed: now - start,\n });\n run();\n });\n }\n };\n\n run();\n\n return () => {\n if (id) {\n animationFrameProvider.cancelAnimationFrame(id);\n }\n };\n });\n}\n\n/**\n * In the common case, where the timestamp provided by the rAF API is used,\n * we use this shared observable to reduce overhead.\n */\nconst DEFAULT_ANIMATION_FRAMES = animationFramesFactory();\n","import { createErrorClass } from './createErrorClass';\n\nexport interface ObjectUnsubscribedError extends Error {}\n\nexport interface ObjectUnsubscribedErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ObjectUnsubscribedError;\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 = createErrorClass(\n (_super) =>\n function ObjectUnsubscribedErrorImpl(this: any) {\n _super(this);\n this.name = 'ObjectUnsubscribedError';\n this.message = 'object unsubscribed';\n }\n);\n","import { Operator } from './Operator';\nimport { Observable } from './Observable';\nimport { Subscriber } from './Subscriber';\nimport { Subscription, EMPTY_SUBSCRIPTION } from './Subscription';\nimport { Observer, SubscriptionLike, TeardownLogic } from './types';\nimport { ObjectUnsubscribedError } from './util/ObjectUnsubscribedError';\nimport { arrRemove } from './util/arrRemove';\nimport { errorContext } from './util/errorContext';\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 */\nexport class Subject<T> extends Observable<T> implements SubscriptionLike {\n closed = false;\n\n private currentObservers: Observer<T>[] | null = null;\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n observers: Observer<T>[] = [];\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n isStopped = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n hasError = false;\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n thrownError: any = null;\n\n /**\n * Creates a \"subject\" by basically gluing an observer to an observable.\n *\n * @deprecated Recommended you do not use. Will be removed at some point in the future. Plans for replacement still under discussion.\n */\n static create: (...args: any[]) => any = <T>(destination: Observer<T>, source: Observable<T>): AnonymousSubject<T> => {\n return new AnonymousSubject<T>(destination, source);\n };\n\n constructor() {\n // NOTE: This must be here to obscure Observable's constructor.\n super();\n }\n\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n lift<R>(operator: Operator<T, R>): Observable<R> {\n const subject = new AnonymousSubject(this, this);\n subject.operator = operator as any;\n return subject as any;\n }\n\n /** @internal */\n protected _throwIfClosed() {\n if (this.closed) {\n throw new ObjectUnsubscribedError();\n }\n }\n\n next(value: T) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n if (!this.currentObservers) {\n this.currentObservers = Array.from(this.observers);\n }\n for (const observer of this.currentObservers) {\n observer.next(value);\n }\n }\n });\n }\n\n error(err: any) {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.hasError = this.isStopped = true;\n this.thrownError = err;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.error(err);\n }\n }\n });\n }\n\n complete() {\n errorContext(() => {\n this._throwIfClosed();\n if (!this.isStopped) {\n this.isStopped = true;\n const { observers } = this;\n while (observers.length) {\n observers.shift()!.complete();\n }\n }\n });\n }\n\n unsubscribe() {\n this.isStopped = this.closed = true;\n this.observers = this.currentObservers = null!;\n }\n\n get observed() {\n return this.observers?.length > 0;\n }\n\n /** @internal */\n protected _trySubscribe(subscriber: Subscriber<T>): TeardownLogic {\n this._throwIfClosed();\n return super._trySubscribe(subscriber);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._checkFinalizedStatuses(subscriber);\n return this._innerSubscribe(subscriber);\n }\n\n /** @internal */\n protected _innerSubscribe(subscriber: Subscriber<any>) {\n const { hasError, isStopped, observers } = this;\n if (hasError || isStopped) {\n return EMPTY_SUBSCRIPTION;\n }\n this.currentObservers = null;\n observers.push(subscriber);\n return new Subscription(() => {\n this.currentObservers = null;\n arrRemove(observers, subscriber);\n });\n }\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber<any>) {\n const { hasError, thrownError, isStopped } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped) {\n subscriber.complete();\n }\n }\n\n /**\n * Creates a new Observable with this Subject as the source. You can do this\n * to create custom Observer-side logic of the Subject and conceal it from\n * code that uses the Observable.\n * @return Observable that this Subject casts to.\n */\n asObservable(): Observable<T> {\n const observable: any = new Observable<T>();\n observable.source = this;\n return observable;\n }\n}\n\nexport class AnonymousSubject<T> extends Subject<T> {\n constructor(\n /** @deprecated Internal implementation detail, do not use directly. Will be made internal in v8. */\n public destination?: Observer<T>,\n source?: Observable<T>\n ) {\n super();\n this.source = source;\n }\n\n next(value: T) {\n this.destination?.next?.(value);\n }\n\n error(err: any) {\n this.destination?.error?.(err);\n }\n\n complete() {\n this.destination?.complete?.();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n return this.source?.subscribe(subscriber) ?? EMPTY_SUBSCRIPTION;\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\n\n/**\n * A variant of Subject that requires an initial value and emits its current\n * value whenever it is subscribed to.\n */\nexport class BehaviorSubject<T> extends Subject<T> {\n constructor(private _value: T) {\n super();\n }\n\n get value(): T {\n return this.getValue();\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n const subscription = super._subscribe(subscriber);\n !subscription.closed && subscriber.next(this._value);\n return subscription;\n }\n\n getValue(): T {\n const { hasError, thrownError, _value } = this;\n if (hasError) {\n throw thrownError;\n }\n this._throwIfClosed();\n return _value;\n }\n\n next(value: T): void {\n super.next((this._value = value));\n }\n}\n","import { TimestampProvider } from '../types';\n\ninterface DateTimestampProvider extends TimestampProvider {\n delegate: TimestampProvider | undefined;\n}\n\nexport const dateTimestampProvider: DateTimestampProvider = {\n now() {\n // Use the variable rather than `this` so that the function can be called\n // without being bound to the provider.\n return (dateTimestampProvider.delegate || Date).now();\n },\n delegate: undefined,\n};\n","import { Subject } from './Subject';\nimport { TimestampProvider } from './types';\nimport { Subscriber } from './Subscriber';\nimport { Subscription } from './Subscription';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * A variant of {@link Subject} that \"replays\" old values to new subscribers by emitting them when they first subscribe.\n *\n * `ReplaySubject` has an internal buffer that will store a specified number of values that it has observed. Like `Subject`,\n * `ReplaySubject` \"observes\" values by having them passed to its `next` method. When it observes a value, it will store that\n * value for a time determined by the configuration of the `ReplaySubject`, as passed to its constructor.\n *\n * When a new subscriber subscribes to the `ReplaySubject` instance, it will synchronously emit all values in its buffer in\n * a First-In-First-Out (FIFO) manner. The `ReplaySubject` will also complete, if it has observed completion; and it will\n * error if it has observed an error.\n *\n * There are two main configuration items to be concerned with:\n *\n * 1. `bufferSize` - This will determine how many items are stored in the buffer, defaults to infinite.\n * 2. `windowTime` - The amount of time to hold a value in the buffer before removing it from the buffer.\n *\n * Both configurations may exist simultaneously. So if you would like to buffer a maximum of 3 values, as long as the values\n * are less than 2 seconds old, you could do so with a `new ReplaySubject(3, 2000)`.\n *\n * ### Differences with BehaviorSubject\n *\n * `BehaviorSubject` is similar to `new ReplaySubject(1)`, with a couple of exceptions:\n *\n * 1. `BehaviorSubject` comes \"primed\" with a single value upon construction.\n * 2. `ReplaySubject` will replay values, even after observing an error, where `BehaviorSubject` will not.\n *\n * @see {@link Subject}\n * @see {@link BehaviorSubject}\n * @see {@link shareReplay}\n */\nexport class ReplaySubject<T> extends Subject<T> {\n private _buffer: (T | number)[] = [];\n private _infiniteTimeWindow = true;\n\n /**\n * @param _bufferSize The size of the buffer to replay on subscription\n * @param _windowTime The amount of time the buffered items will stay buffered\n * @param _timestampProvider An object with a `now()` method that provides the current timestamp. This is used to\n * calculate the amount of time something has been buffered.\n */\n constructor(\n private _bufferSize = Infinity,\n private _windowTime = Infinity,\n private _timestampProvider: TimestampProvider = dateTimestampProvider\n ) {\n super();\n this._infiniteTimeWindow = _windowTime === Infinity;\n this._bufferSize = Math.max(1, _bufferSize);\n this._windowTime = Math.max(1, _windowTime);\n }\n\n next(value: T): void {\n const { isStopped, _buffer, _infiniteTimeWindow, _timestampProvider, _windowTime } = this;\n if (!isStopped) {\n _buffer.push(value);\n !_infiniteTimeWindow && _buffer.push(_timestampProvider.now() + _windowTime);\n }\n this._trimBuffer();\n super.next(value);\n }\n\n /** @internal */\n protected _subscribe(subscriber: Subscriber<T>): Subscription {\n this._throwIfClosed();\n this._trimBuffer();\n\n const subscription = this._innerSubscribe(subscriber);\n\n const { _infiniteTimeWindow, _buffer } = this;\n // We use a copy here, so reentrant code does not mutate our array while we're\n // emitting it to a new subscriber.\n const copy = _buffer.slice();\n for (let i = 0; i < copy.length && !subscriber.closed; i += _infiniteTimeWindow ? 1 : 2) {\n subscriber.next(copy[i] as T);\n }\n\n this._checkFinalizedStatuses(subscriber);\n\n return subscription;\n }\n\n private _trimBuffer() {\n const { _bufferSize, _timestampProvider, _buffer, _infiniteTimeWindow } = this;\n // If we don't have an infinite buffer size, and we're over the length,\n // use splice to truncate the old buffer values off. Note that we have to\n // double the size for instances where we're not using an infinite time window\n // because we're storing the values and the timestamps in the same array.\n const adjustedBufferSize = (_infiniteTimeWindow ? 1 : 2) * _bufferSize;\n _bufferSize < Infinity && adjustedBufferSize < _buffer.length && _buffer.splice(0, _buffer.length - adjustedBufferSize);\n\n // Now, if we're not in an infinite time window, remove all values where the time is\n // older than what is allowed.\n if (!_infiniteTimeWindow) {\n const now = _timestampProvider.now();\n let last = 0;\n // Search the array for the first timestamp that isn't expired and\n // truncate the buffer up to that point.\n for (let i = 1; i < _buffer.length && (_buffer[i] as number) <= now; i += 2) {\n last = i;\n }\n last && _buffer.splice(0, last + 1);\n }\n }\n}\n","import { Subject } from './Subject';\nimport { Subscriber } from './Subscriber';\n\n/**\n * A variant of Subject that only emits a value when it completes. It will emit\n * its latest value to all its observers on completion.\n */\nexport class AsyncSubject<T> extends Subject<T> {\n private _value: T | null = null;\n private _hasValue = false;\n private _isComplete = false;\n\n /** @internal */\n protected _checkFinalizedStatuses(subscriber: Subscriber<T>) {\n const { hasError, _hasValue, _value, thrownError, isStopped, _isComplete } = this;\n if (hasError) {\n subscriber.error(thrownError);\n } else if (isStopped || _isComplete) {\n _hasValue && subscriber.next(_value!);\n subscriber.complete();\n }\n }\n\n next(value: T): void {\n if (!this.isStopped) {\n this._value = value;\n this._hasValue = true;\n }\n }\n\n complete(): void {\n const { _hasValue, _value, _isComplete } = this;\n if (!_isComplete) {\n this._isComplete = true;\n _hasValue && super.next(_value!);\n super.complete();\n }\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Subscription } from '../Subscription';\nimport { SchedulerAction } from '../types';\n\n/**\n * A unit of work to be executed in a `scheduler`. An action is typically\n * created from within a {@link SchedulerLike} and an RxJS user does not need to concern\n * themselves about creating and manipulating an Action.\n *\n * ```ts\n * class Action<T> extends Subscription {\n * new (scheduler: Scheduler, work: (state?: T) => void);\n * schedule(state?: T, delay: number = 0): Subscription;\n * }\n * ```\n */\nexport class Action<T> extends Subscription {\n constructor(scheduler: Scheduler, work: (this: SchedulerAction<T>, state?: T) => void) {\n super();\n }\n /**\n * Schedules this action on its parent {@link SchedulerLike} for execution. May be passed\n * some context object, `state`. May happen at some point in the future,\n * according to the `delay` parameter, if specified.\n * @param state Some contextual data that the `work` function uses when called by the\n * Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is implicit\n * and defined by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule(state?: T, delay: number = 0): Subscription {\n return this;\n }\n}\n","import type { TimerHandle } from './timerHandle';\ntype SetIntervalFunction = (handler: () => void, timeout?: number, ...args: any[]) => TimerHandle;\ntype ClearIntervalFunction = (handle: TimerHandle) => void;\n\ninterface IntervalProvider {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n delegate:\n | {\n setInterval: SetIntervalFunction;\n clearInterval: ClearIntervalFunction;\n }\n | undefined;\n}\n\nexport const intervalProvider: IntervalProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setInterval(handler: () => void, timeout?: number, ...args) {\n const { delegate } = intervalProvider;\n if (delegate?.setInterval) {\n return delegate.setInterval(handler, timeout, ...args);\n }\n return setInterval(handler, timeout, ...args);\n },\n clearInterval(handle) {\n const { delegate } = intervalProvider;\n return (delegate?.clearInterval || clearInterval)(handle as any);\n },\n delegate: undefined,\n};\n","import { Action } from './Action';\nimport { SchedulerAction } from '../types';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { intervalProvider } from './intervalProvider';\nimport { arrRemove } from '../util/arrRemove';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncAction<T> extends Action<T> {\n public id: TimerHandle | undefined;\n public state?: T;\n // @ts-ignore: Property has no initializer and is not definitely assigned\n public delay: number;\n protected pending: boolean = false;\n\n constructor(protected scheduler: AsyncScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (this.closed) {\n return this;\n }\n\n // Always replace the current state with the new state.\n this.state = state;\n\n const id = this.id;\n const scheduler = this.scheduler;\n\n //\n // Important implementation note:\n //\n // Actions only execute once by default, unless rescheduled from within the\n // scheduled callback. This allows us to implement single and repeat\n // actions via the same code path, without adding API surface area, as well\n // as mimic traditional recursion but across asynchronous boundaries.\n //\n // However, JS runtimes and timers distinguish between intervals achieved by\n // serial `setTimeout` calls vs. a single `setInterval` call. An interval of\n // serial `setTimeout` calls can be individually delayed, which delays\n // scheduling the next `setTimeout`, and so on. `setInterval` attempts to\n // guarantee the interval callback will be invoked more precisely to the\n // interval period, regardless of load.\n //\n // Therefore, we use `setInterval` to schedule single and repeat actions.\n // If the action reschedules itself with the same delay, the interval is not\n // canceled. If the action doesn't reschedule, or reschedules with a\n // different delay, the interval will be canceled after scheduled callback\n // execution.\n //\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, delay);\n }\n\n // Set the pending flag indicating that this action has been scheduled, or\n // has recursively rescheduled itself.\n this.pending = true;\n\n this.delay = delay;\n // If this action has already an async Id, don't request a new one.\n this.id = this.id ?? this.requestAsyncId(scheduler, this.id, delay);\n\n return this;\n }\n\n protected requestAsyncId(scheduler: AsyncScheduler, _id?: TimerHandle, delay: number = 0): TimerHandle {\n return intervalProvider.setInterval(scheduler.flush.bind(scheduler, this), delay);\n }\n\n protected recycleAsyncId(_scheduler: AsyncScheduler, id?: TimerHandle, delay: number | null = 0): TimerHandle | undefined {\n // If this action is rescheduled with the same delay time, don't clear the interval id.\n if (delay != null && this.delay === delay && this.pending === false) {\n return id;\n }\n // Otherwise, if the action's delay time is different from the current delay,\n // or the action has been rescheduled before it's executed, clear the interval id\n if (id != null) {\n intervalProvider.clearInterval(id);\n }\n\n return undefined;\n }\n\n /**\n * Immediately executes this action and the `work` it contains.\n */\n public execute(state: T, delay: number): any {\n if (this.closed) {\n return new Error('executing a cancelled action');\n }\n\n this.pending = false;\n const error = this._execute(state, delay);\n if (error) {\n return error;\n } else if (this.pending === false && this.id != null) {\n // Dequeue if the action didn't reschedule itself. Don't call\n // unsubscribe(), because the action could reschedule later.\n // For example:\n // ```\n // scheduler.schedule(function doWork(counter) {\n // /* ... I'm a busy worker bee ... */\n // var originalAction = this;\n // /* wait 100ms before rescheduling the action */\n // setTimeout(function () {\n // originalAction.schedule(counter + 1);\n // }, 100);\n // }, 1000);\n // ```\n this.id = this.recycleAsyncId(this.scheduler, this.id, null);\n }\n }\n\n protected _execute(state: T, _delay: number): any {\n let errored: boolean = false;\n let errorValue: any;\n try {\n this.work(state);\n } catch (e) {\n errored = true;\n // HACK: Since code elsewhere is relying on the \"truthiness\" of the\n // return here, we can't have it return \"\" or 0 or false.\n // TODO: Clean this up when we refactor schedulers mid-version-8 or so.\n errorValue = e ? e : new Error('Scheduled action threw falsy error');\n }\n if (errored) {\n this.unsubscribe();\n return errorValue;\n }\n }\n\n unsubscribe() {\n if (!this.closed) {\n const { id, scheduler } = this;\n const { actions } = scheduler;\n\n this.work = this.state = this.scheduler = null!;\n this.pending = false;\n\n arrRemove(actions, this);\n if (id != null) {\n this.id = this.recycleAsyncId(scheduler, id, null);\n }\n\n this.delay = null!;\n super.unsubscribe();\n }\n }\n}\n","let nextHandle = 1;\n// The promise needs to be created lazily otherwise it won't be patched by Zones\nlet resolved: Promise<any>;\nconst activeHandles: { [key: number]: any } = {};\n\n/**\n * Finds the handle in the list of active handles, and removes it.\n * Returns `true` if found, `false` otherwise. Used both to clear\n * Immediate scheduled tasks, and to identify if a task should be scheduled.\n */\nfunction findAndClearHandle(handle: number): boolean {\n if (handle in activeHandles) {\n delete activeHandles[handle];\n return true;\n }\n return false;\n}\n\n/**\n * Helper functions to schedule and unschedule microtasks.\n */\nexport const Immediate = {\n setImmediate(cb: () => void): number {\n const handle = nextHandle++;\n activeHandles[handle] = true;\n if (!resolved) {\n resolved = Promise.resolve();\n }\n resolved.then(() => findAndClearHandle(handle) && cb());\n return handle;\n },\n\n clearImmediate(handle: number): void {\n findAndClearHandle(handle);\n },\n};\n\n/**\n * Used for internal testing purposes only. Do not export from library.\n */\nexport const TestTools = {\n pending() {\n return Object.keys(activeHandles).length;\n }\n};\n","import { Immediate } from '../util/Immediate';\nimport type { TimerHandle } from './timerHandle';\nconst { setImmediate, clearImmediate } = Immediate;\n\ntype SetImmediateFunction = (handler: () => void, ...args: any[]) => TimerHandle;\ntype ClearImmediateFunction = (handle: TimerHandle) => void;\n\ninterface ImmediateProvider {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n delegate:\n | {\n setImmediate: SetImmediateFunction;\n clearImmediate: ClearImmediateFunction;\n }\n | undefined;\n}\n\nexport const immediateProvider: ImmediateProvider = {\n // When accessing the delegate, use the variable rather than `this` so that\n // the functions can be called without being bound to the provider.\n setImmediate(...args) {\n const { delegate } = immediateProvider;\n return (delegate?.setImmediate || setImmediate)(...args);\n },\n clearImmediate(handle) {\n const { delegate } = immediateProvider;\n return (delegate?.clearImmediate || clearImmediate)(handle as any);\n },\n delegate: undefined,\n};\n","import { AsyncAction } from './AsyncAction';\nimport { AsapScheduler } from './AsapScheduler';\nimport { SchedulerAction } from '../types';\nimport { immediateProvider } from './immediateProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsapAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: AsapScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If a microtask has already been scheduled, don't schedule another\n // one. If a microtask hasn't been scheduled yet, schedule one now. Return\n // the current scheduled microtask id.\n return scheduler._scheduled || (scheduler._scheduled = immediateProvider.setImmediate(scheduler.flush.bind(scheduler, undefined)));\n }\n\n protected recycleAsyncId(scheduler: AsapScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested microtask and set the scheduled flag to undefined\n // so the next AsapAction will request its own.\n const { actions } = scheduler;\n if (id != null && actions[actions.length - 1]?.id !== id) {\n immediateProvider.clearImmediate(id);\n if (scheduler._scheduled === id) {\n scheduler._scheduled = undefined;\n }\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { Action } from './scheduler/Action';\nimport { Subscription } from './Subscription';\nimport { SchedulerLike, SchedulerAction } from './types';\nimport { dateTimestampProvider } from './scheduler/dateTimestampProvider';\n\n/**\n * An execution context and a data structure to order tasks and schedule their\n * execution. Provides a notion of (potentially virtual) time, through the\n * `now()` getter method.\n *\n * Each unit of work in a Scheduler is called an `Action`.\n *\n * ```ts\n * class Scheduler {\n * now(): number;\n * schedule(work, delay?, state?): Subscription;\n * }\n * ```\n *\n * @deprecated Scheduler is an internal implementation detail of RxJS, and\n * should not be used directly. Rather, create your own class and implement\n * {@link SchedulerLike}. Will be made internal in v8.\n */\nexport class Scheduler implements SchedulerLike {\n public static now: () => number = dateTimestampProvider.now;\n\n constructor(private schedulerActionCtor: typeof Action, now: () => number = Scheduler.now) {\n this.now = now;\n }\n\n /**\n * A getter method that returns a number representing the current time\n * (at the time this function was called) according to the scheduler's own\n * internal clock.\n * @return A number that represents the current time. May or may not\n * have a relation to wall-clock time. May or may not refer to a time unit\n * (e.g. milliseconds).\n */\n public now: () => number;\n\n /**\n * Schedules a function, `work`, for execution. May happen at some point in\n * the future, according to the `delay` parameter, if specified. May be passed\n * some context object, `state`, which will be passed to the `work` function.\n *\n * The given arguments will be processed an stored as an Action object in a\n * queue of actions.\n *\n * @param work A function representing a task, or some unit of work to be\n * executed by the Scheduler.\n * @param delay Time to wait before executing the work, where the time unit is\n * implicit and defined by the Scheduler itself.\n * @param state Some contextual data that the `work` function uses when called\n * by the Scheduler.\n * @return A subscription in order to be able to unsubscribe the scheduled work.\n */\n public schedule<T>(work: (this: SchedulerAction<T>, state?: T) => void, delay: number = 0, state?: T): Subscription {\n return new this.schedulerActionCtor<T>(this, work).schedule(state, delay);\n }\n}\n","import { Scheduler } from '../Scheduler';\nimport { Action } from './Action';\nimport { AsyncAction } from './AsyncAction';\nimport { TimerHandle } from './timerHandle';\n\nexport class AsyncScheduler extends Scheduler {\n public actions: Array<AsyncAction<any>> = [];\n /**\n * A flag to indicate whether the Scheduler is currently executing a batch of\n * queued actions.\n * @internal\n */\n public _active: boolean = false;\n /**\n * An internal ID used to track the latest asynchronous task such as those\n * coming from `setTimeout`, `setInterval`, `requestAnimationFrame`, and\n * others.\n * @internal\n */\n public _scheduled: TimerHandle | undefined;\n\n constructor(SchedulerAction: typeof Action, now: () => number = Scheduler.now) {\n super(SchedulerAction, now);\n }\n\n public flush(action: AsyncAction<any>): void {\n const { actions } = this;\n\n if (this._active) {\n actions.push(action);\n return;\n }\n\n let error: any;\n this._active = true;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions.shift()!)); // exhaust the scheduler queue\n\n this._active = false;\n\n if (error) {\n while ((action = actions.shift()!)) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AsapScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction<any>): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n const flushId = this._scheduled;\n this._scheduled = undefined;\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AsapAction } from './AsapAction';\nimport { AsapScheduler } from './AsapScheduler';\n\n/**\n *\n * Asap Scheduler\n *\n * <span class=\"informal\">Perform task as fast as it can be performed asynchronously</span>\n *\n * `asap` scheduler behaves the same as {@link asyncScheduler} scheduler when you use it to delay task\n * in time. If however you set delay to `0`, `asap` will wait for current synchronously executing\n * code to end and then it will try to execute given task as fast as possible.\n *\n * `asap` scheduler will do its best to minimize time between end of currently executing code\n * and start of scheduled task. This makes it best candidate for performing so called \"deferring\".\n * Traditionally this was achieved by calling `setTimeout(deferredTask, 0)`, but that technique involves\n * some (although minimal) unwanted delay.\n *\n * Note that using `asap` scheduler does not necessarily mean that your task will be first to process\n * after currently executing code. In particular, if some task was also scheduled with `asap` before,\n * that task will execute first. That being said, if you need to schedule task asynchronously, but\n * as soon as possible, `asap` scheduler is your best bet.\n *\n * ## Example\n * Compare async and asap scheduler<\n * ```ts\n * import { asapScheduler, asyncScheduler } from 'rxjs';\n *\n * asyncScheduler.schedule(() => console.log('async')); // scheduling 'async' first...\n * asapScheduler.schedule(() => console.log('asap'));\n *\n * // Logs:\n * // \"asap\"\n * // \"async\"\n * // ... but 'asap' goes first!\n * ```\n */\n\nexport const asapScheduler = new AsapScheduler(AsapAction);\n\n/**\n * @deprecated Renamed to {@link asapScheduler}. Will be removed in v8.\n */\nexport const asap = asapScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\n/**\n *\n * Async Scheduler\n *\n * <span class=\"informal\">Schedule task as if you used setTimeout(task, duration)</span>\n *\n * `async` scheduler schedules tasks asynchronously, by putting them on the JavaScript\n * event loop queue. It is best used to delay tasks in time or to schedule tasks repeating\n * in intervals.\n *\n * If you just want to \"defer\" task, that is to perform it right after currently\n * executing synchronous code ends (commonly achieved by `setTimeout(deferredTask, 0)`),\n * better choice will be the {@link asapScheduler} scheduler.\n *\n * ## Examples\n * Use async scheduler to delay task\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * const task = () => console.log('it works!');\n *\n * asyncScheduler.schedule(task, 2000);\n *\n * // After 2 seconds logs:\n * // \"it works!\"\n * ```\n *\n * Use async scheduler to repeat task in intervals\n * ```ts\n * import { asyncScheduler } from 'rxjs';\n *\n * function task(state) {\n * console.log(state);\n * this.schedule(state + 1, 1000); // `this` references currently executing Action,\n * // which we reschedule with new state and delay\n * }\n *\n * asyncScheduler.schedule(task, 3000, 0);\n *\n * // Logs:\n * // 0 after 3s\n * // 1 after 4s\n * // 2 after 5s\n * // 3 after 6s\n * ```\n */\n\nexport const asyncScheduler = new AsyncScheduler(AsyncAction);\n\n/**\n * @deprecated Renamed to {@link asyncScheduler}. Will be removed in v8.\n */\nexport const async = asyncScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { QueueScheduler } from './QueueScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class QueueAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: QueueScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (delay > 0) {\n return super.schedule(state, delay);\n }\n this.delay = delay;\n this.state = state;\n this.scheduler.flush(this);\n return this;\n }\n\n public execute(state: T, delay: number): any {\n return delay > 0 || this.closed ? super.execute(state, delay) : this._execute(state, delay);\n }\n\n protected requestAsyncId(scheduler: QueueScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n\n if ((delay != null && delay > 0) || (delay == null && this.delay > 0)) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n\n // Otherwise flush the scheduler starting with this action.\n scheduler.flush(this);\n\n // HACK: In the past, this was returning `void`. However, `void` isn't a valid\n // `TimerHandle`, and generally the return value here isn't really used. So the\n // compromise is to return `0` which is both \"falsy\" and a valid `TimerHandle`,\n // as opposed to refactoring every other instanceo of `requestAsyncId`.\n return 0;\n }\n}\n","import { AsyncScheduler } from './AsyncScheduler';\n\nexport class QueueScheduler extends AsyncScheduler {\n}\n","import { QueueAction } from './QueueAction';\nimport { QueueScheduler } from './QueueScheduler';\n\n/**\n *\n * Queue Scheduler\n *\n * <span class=\"informal\">Put every next task on a queue, instead of executing it immediately</span>\n *\n * `queue` scheduler, when used with delay, behaves the same as {@link asyncScheduler} scheduler.\n *\n * When used without delay, it schedules given task synchronously - executes it right when\n * it is scheduled. However when called recursively, that is when inside the scheduled task,\n * another task is scheduled with queue scheduler, instead of executing immediately as well,\n * that task will be put on a queue and wait for current one to finish.\n *\n * This means that when you execute task with `queue` scheduler, you are sure it will end\n * before any other task scheduled with that scheduler will start.\n *\n * ## Examples\n * Schedule recursively first, then do something\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(() => {\n * queueScheduler.schedule(() => console.log('second')); // will not happen now, but will be put on a queue\n *\n * console.log('first');\n * });\n *\n * // Logs:\n * // \"first\"\n * // \"second\"\n * ```\n *\n * Reschedule itself recursively\n * ```ts\n * import { queueScheduler } from 'rxjs';\n *\n * queueScheduler.schedule(function(state) {\n * if (state !== 0) {\n * console.log('before', state);\n * this.schedule(state - 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * console.log('after', state);\n * }\n * }, 0, 3);\n *\n * // In scheduler that runs recursively, you would expect:\n * // \"before\", 3\n * // \"before\", 2\n * // \"before\", 1\n * // \"after\", 1\n * // \"after\", 2\n * // \"after\", 3\n *\n * // But with queue it logs:\n * // \"before\", 3\n * // \"after\", 3\n * // \"before\", 2\n * // \"after\", 2\n * // \"before\", 1\n * // \"after\", 1\n * ```\n */\n\nexport const queueScheduler = new QueueScheduler(QueueAction);\n\n/**\n * @deprecated Renamed to {@link queueScheduler}. Will be removed in v8.\n */\nexport const queue = queueScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\nimport { SchedulerAction } from '../types';\nimport { animationFrameProvider } from './animationFrameProvider';\nimport { TimerHandle } from './timerHandle';\n\nexport class AnimationFrameAction<T> extends AsyncAction<T> {\n constructor(protected scheduler: AnimationFrameScheduler, protected work: (this: SchedulerAction<T>, state?: T) => void) {\n super(scheduler, work);\n }\n\n protected requestAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle {\n // If delay is greater than 0, request as an async action.\n if (delay !== null && delay > 0) {\n return super.requestAsyncId(scheduler, id, delay);\n }\n // Push the action to the end of the scheduler queue.\n scheduler.actions.push(this);\n // If an animation frame has already been requested, don't request another\n // one. If an animation frame hasn't been requested yet, request one. Return\n // the current animation frame request id.\n return scheduler._scheduled || (scheduler._scheduled = animationFrameProvider.requestAnimationFrame(() => scheduler.flush(undefined)));\n }\n\n protected recycleAsyncId(scheduler: AnimationFrameScheduler, id?: TimerHandle, delay: number = 0): TimerHandle | undefined {\n // If delay exists and is greater than 0, or if the delay is null (the\n // action wasn't rescheduled) but was originally scheduled as an async\n // action, then recycle as an async action.\n if (delay != null ? delay > 0 : this.delay > 0) {\n return super.recycleAsyncId(scheduler, id, delay);\n }\n // If the scheduler queue has no remaining actions with the same async id,\n // cancel the requested animation frame and set the scheduled flag to\n // undefined so the next AnimationFrameAction will request its own.\n const { actions } = scheduler;\n if (id != null && id === scheduler._scheduled && actions[actions.length - 1]?.id !== id) {\n animationFrameProvider.cancelAnimationFrame(id as number);\n scheduler._scheduled = undefined;\n }\n // Return undefined so the action knows to request a new async id if it's rescheduled.\n return undefined;\n }\n}\n","import { AsyncAction } from './AsyncAction';\nimport { AsyncScheduler } from './AsyncScheduler';\n\nexport class AnimationFrameScheduler extends AsyncScheduler {\n public flush(action?: AsyncAction<any>): void {\n this._active = true;\n // The async id that effects a call to flush is stored in _scheduled.\n // Before executing an action, it's necessary to check the action's async\n // id to determine whether it's supposed to be executed in the current\n // flush.\n // Previous implementations of this method used a count to determine this,\n // but that was unsound, as actions that are unsubscribed - i.e. cancelled -\n // are removed from the actions array and that can shift actions that are\n // scheduled to be executed in a subsequent flush into positions at which\n // they are executed within the current flush.\n let flushId;\n if (action) {\n flushId = action.id;\n } else {\n flushId = this._scheduled;\n this._scheduled = undefined;\n }\n\n const { actions } = this;\n let error: any;\n action = action || actions.shift()!;\n\n do {\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n } while ((action = actions[0]) && action.id === flushId && actions.shift());\n\n this._active = false;\n\n if (error) {\n while ((action = actions[0]) && action.id === flushId && actions.shift()) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n","import { AnimationFrameAction } from './AnimationFrameAction';\nimport { AnimationFrameScheduler } from './AnimationFrameScheduler';\n\n/**\n *\n * Animation Frame Scheduler\n *\n * <span class=\"informal\">Perform task when `window.requestAnimationFrame` would fire</span>\n *\n * When `animationFrame` scheduler is used with delay, it will fall back to {@link asyncScheduler} scheduler\n * behaviour.\n *\n * Without delay, `animationFrame` scheduler can be used to create smooth browser animations.\n * It makes sure scheduled task will happen just before next browser content repaint,\n * thus performing animations as efficiently as possible.\n *\n * ## Example\n * Schedule div height animation\n * ```ts\n * // html: <div style=\"background: #0ff;\"></div>\n * import { animationFrameScheduler } from 'rxjs';\n *\n * const div = document.querySelector('div');\n *\n * animationFrameScheduler.schedule(function(height) {\n * div.style.height = height + \"px\";\n *\n * this.schedule(height + 1); // `this` references currently executing Action,\n * // which we reschedule with new state\n * }, 0, 0);\n *\n * // You will see a div element growing in height\n * ```\n */\n\nexport const animationFrameScheduler = new AnimationFrameScheduler(AnimationFrameAction);\n\n/**\n * @deprecated Renamed to {@link animationFrameScheduler}. Will be removed in v8.\n */\nexport const animationFrame = animationFrameScheduler;\n","import { AsyncAction } from './AsyncAction';\nimport { Subscription } from '../Subscription';\nimport { AsyncScheduler } from './AsyncScheduler';\nimport { SchedulerAction } from '../types';\nimport { TimerHandle } from './timerHandle';\n\nexport class VirtualTimeScheduler extends AsyncScheduler {\n /** @deprecated Not used in VirtualTimeScheduler directly. Will be removed in v8. */\n static frameTimeFactor = 10;\n\n /**\n * The current frame for the state of the virtual scheduler instance. The difference\n * between two \"frames\" is synonymous with the passage of \"virtual time units\". So if\n * you record `scheduler.frame` to be `1`, then later, observe `scheduler.frame` to be at `11`,\n * that means `10` virtual time units have passed.\n */\n public frame: number = 0;\n\n /**\n * Used internally to examine the current virtual action index being processed.\n * @deprecated Internal implementation detail, do not use directly. Will be made internal in v8.\n */\n public index: number = -1;\n\n /**\n * This creates an instance of a `VirtualTimeScheduler`. Experts only. The signature of\n * this constructor is likely to change in the long run.\n *\n * @param schedulerActionCtor The type of Action to initialize when initializing actions during scheduling.\n * @param maxFrames The maximum number of frames to process before stopping. Used to prevent endless flush cycles.\n */\n constructor(schedulerActionCtor: typeof AsyncAction = VirtualAction as any, public maxFrames: number = Infinity) {\n super(schedulerActionCtor, () => this.frame);\n }\n\n /**\n * Prompt the Scheduler to execute all of its queued actions, therefore\n * clearing its queue.\n */\n public flush(): void {\n const { actions, maxFrames } = this;\n let error: any;\n let action: AsyncAction<any> | undefined;\n\n while ((action = actions[0]) && action.delay <= maxFrames) {\n actions.shift();\n this.frame = action.delay;\n\n if ((error = action.execute(action.state, action.delay))) {\n break;\n }\n }\n\n if (error) {\n while ((action = actions.shift())) {\n action.unsubscribe();\n }\n throw error;\n }\n }\n}\n\nexport class VirtualAction<T> extends AsyncAction<T> {\n protected active: boolean = true;\n\n constructor(\n protected scheduler: VirtualTimeScheduler,\n protected work: (this: SchedulerAction<T>, state?: T) => void,\n protected index: number = (scheduler.index += 1)\n ) {\n super(scheduler, work);\n this.index = scheduler.index = index;\n }\n\n public schedule(state?: T, delay: number = 0): Subscription {\n if (Number.isFinite(delay)) {\n if (!this.id) {\n return super.schedule(state, delay);\n }\n this.active = false;\n // If an action is rescheduled, we save allocations by mutating its state,\n // pushing it to the end of the scheduler queue, and recycling the action.\n // But since the VirtualTimeScheduler is used for testing, VirtualActions\n // must be immutable so they can be inspected later.\n const action = new VirtualAction(this.scheduler, this.work);\n this.add(action);\n return action.schedule(state, delay);\n } else {\n // If someone schedules something with Infinity, it'll never happen. So we\n // don't even schedule it.\n return Subscription.EMPTY;\n }\n }\n\n protected requestAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle {\n this.delay = scheduler.frame + delay;\n const { actions } = scheduler;\n actions.push(this);\n (actions as Array<VirtualAction<T>>).sort(VirtualAction.sortActions);\n return 1;\n }\n\n protected recycleAsyncId(scheduler: VirtualTimeScheduler, id?: any, delay: number = 0): TimerHandle | undefined {\n return undefined;\n }\n\n protected _execute(state: T, delay: number): any {\n if (this.active === true) {\n return super._execute(state, delay);\n }\n }\n\n private static sortActions<T>(a: VirtualAction<T>, b: VirtualAction<T>) {\n if (a.delay === b.delay) {\n if (a.index === b.index) {\n return 0;\n } else if (a.index > b.index) {\n return 1;\n } else {\n return -1;\n }\n } else if (a.delay > b.delay) {\n return 1;\n } else {\n return -1;\n }\n }\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\n/**\n * A simple Observable that emits no items to the Observer and immediately\n * emits a complete notification.\n *\n * <span class=\"informal\">Just emits 'complete', and nothing else.</span>\n *\n * ![](empty.png)\n *\n * A simple Observable that only emits the complete notification. It can be used\n * for composing with other Observables, such as in a {@link mergeMap}.\n *\n * ## Examples\n *\n * Log complete notification\n *\n * ```ts\n * import { EMPTY } from 'rxjs';\n *\n * EMPTY.subscribe({\n * next: () => console.log('Next'),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Outputs\n * // Complete!\n * ```\n *\n * Emit the number 7, then complete\n *\n * ```ts\n * import { EMPTY, startWith } from 'rxjs';\n *\n * const result = EMPTY.pipe(startWith(7));\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // 7\n * ```\n *\n * Map and flatten only odd numbers to the sequence `'a'`, `'b'`, `'c'`\n *\n * ```ts\n * import { interval, mergeMap, of, EMPTY } from 'rxjs';\n *\n * const interval$ = interval(1000);\n * const result = interval$.pipe(\n * mergeMap(x => x % 2 === 1 ? of('a', 'b', 'c') : EMPTY),\n * );\n * result.subscribe(x => console.log(x));\n *\n * // Results in the following to the console:\n * // x is equal to the count on the interval, e.g. (0, 1, 2, 3, ...)\n * // x will occur every 1000ms\n * // if x % 2 is equal to 1, print a, b, c (each on its own)\n * // if x % 2 is not equal to 1, nothing will be output\n * ```\n *\n * @see {@link Observable}\n * @see {@link NEVER}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const EMPTY = new Observable<never>((subscriber) => subscriber.complete());\n\n/**\n * @param scheduler A {@link SchedulerLike} to use for scheduling\n * the emission of the complete notification.\n * @deprecated Replaced with the {@link EMPTY} constant or {@link scheduled} (e.g. `scheduled([], scheduler)`). Will be removed in v8.\n */\nexport function empty(scheduler?: SchedulerLike) {\n return scheduler ? emptyScheduled(scheduler) : EMPTY;\n}\n\nfunction emptyScheduled(scheduler: SchedulerLike) {\n return new Observable<never>((subscriber) => scheduler.schedule(() => subscriber.complete()));\n}\n","import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport function isScheduler(value: any): value is SchedulerLike {\n return value && isFunction(value.schedule);\n}\n","import { SchedulerLike } from '../types';\nimport { isFunction } from './isFunction';\nimport { isScheduler } from './isScheduler';\n\nfunction last<T>(arr: T[]): T | undefined {\n return arr[arr.length - 1];\n}\n\nexport function popResultSelector(args: any[]): ((...args: unknown[]) => unknown) | undefined {\n return isFunction(last(args)) ? args.pop() : undefined;\n}\n\nexport function popScheduler(args: any[]): SchedulerLike | undefined {\n return isScheduler(last(args)) ? args.pop() : undefined;\n}\n\nexport function popNumber(args: any[], defaultValue: number): number {\n return typeof last(args) === 'number' ? args.pop()! : defaultValue;\n}\n","export const isArrayLike = (<T>(x: any): x is ArrayLike<T> => x && typeof x.length === 'number' && typeof x !== 'function');","import { isFunction } from \"./isFunction\";\n\n/**\n * Tests to see if the object is \"thennable\".\n * @param value the object to test\n */\nexport function isPromise(value: any): value is PromiseLike<any> {\n return isFunction(value?.then);\n}\n","import { InteropObservable } from '../types';\nimport { observable as Symbol_observable } from '../symbol/observable';\nimport { isFunction } from './isFunction';\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 isFunction(input[Symbol_observable]);\n}\n","import { isFunction } from './isFunction';\n\nexport function isAsyncIterable<T>(obj: any): obj is AsyncIterable<T> {\n return Symbol.asyncIterator && isFunction(obj?.[Symbol.asyncIterator]);\n}\n","/**\n * Creates the TypeError to throw if an invalid object is passed to `from` or `scheduled`.\n * @param input The object that was passed.\n */\nexport function createInvalidObservableTypeError(input: any) {\n // TODO: We should create error codes that can be looked up, so this can be less verbose.\n return new TypeError(\n `You provided ${\n input !== null && typeof input === 'object' ? 'an invalid object' : `'${input}'`\n } where a stream was expected. You can provide an Observable, Promise, ReadableStream, Array, AsyncIterable, or Iterable.`\n );\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","import { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from './isFunction';\n\n/** Identifies an input as being an Iterable */\nexport function isIterable(input: any): input is Iterable<any> {\n return isFunction(input?.[Symbol_iterator]);\n}\n","import { ReadableStreamLike } from '../types';\nimport { isFunction } from './isFunction';\n\nexport async function* readableStreamLikeToAsyncGenerator<T>(readableStream: ReadableStreamLike<T>): AsyncGenerator<T> {\n const reader = readableStream.getReader();\n try {\n while (true) {\n const { value, done } = await reader.read();\n if (done) {\n return;\n }\n yield value!;\n }\n } finally {\n reader.releaseLock();\n }\n}\n\nexport function isReadableStreamLike<T>(obj: any): obj is ReadableStreamLike<T> {\n // We don't want to use instanceof checks because they would return\n // false for instances from another Realm, like an <iframe>.\n return isFunction(obj?.getReader);\n}\n","import { isArrayLike } from '../util/isArrayLike';\nimport { isPromise } from '../util/isPromise';\nimport { Observable } from '../Observable';\nimport { ObservableInput, ObservedValueOf, ReadableStreamLike } from '../types';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isIterable } from '../util/isIterable';\nimport { isReadableStreamLike, readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\nimport { Subscriber } from '../Subscriber';\nimport { isFunction } from '../util/isFunction';\nimport { reportUnhandledError } from '../util/reportUnhandledError';\nimport { observable as Symbol_observable } from '../symbol/observable';\n\nexport function innerFrom<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\nexport function innerFrom<T>(input: ObservableInput<T>): Observable<T> {\n if (input instanceof Observable) {\n return input;\n }\n if (input != null) {\n if (isInteropObservable(input)) {\n return fromInteropObservable(input);\n }\n if (isArrayLike(input)) {\n return fromArrayLike(input);\n }\n if (isPromise(input)) {\n return fromPromise(input);\n }\n if (isAsyncIterable(input)) {\n return fromAsyncIterable(input);\n }\n if (isIterable(input)) {\n return fromIterable(input);\n }\n if (isReadableStreamLike(input)) {\n return fromReadableStreamLike(input);\n }\n }\n\n throw createInvalidObservableTypeError(input);\n}\n\n/**\n * Creates an RxJS Observable from an object that implements `Symbol.observable`.\n * @param obj An object that properly implements `Symbol.observable`.\n */\nexport function fromInteropObservable<T>(obj: any) {\n return new Observable((subscriber: Subscriber<T>) => {\n const obs = obj[Symbol_observable]();\n if (isFunction(obs.subscribe)) {\n return obs.subscribe(subscriber);\n }\n // Should be caught by observable subscribe function error handling.\n throw new TypeError('Provided object does not correctly implement Symbol.observable');\n });\n}\n\n/**\n * Synchronously emits the values of an array like and completes.\n * This is exported because there are creation functions and operators that need to\n * make direct use of the same logic, and there's no reason to make them run through\n * `from` conditionals because we *know* they're dealing with an array.\n * @param array The array to emit values from\n */\nexport function fromArrayLike<T>(array: ArrayLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n // Loop over the array and emit each value. Note two things here:\n // 1. We're making sure that the subscriber is not closed on each loop.\n // This is so we don't continue looping over a very large array after\n // something like a `take`, `takeWhile`, or other synchronous unsubscription\n // has already unsubscribed.\n // 2. In this form, reentrant code can alter that array we're looping over.\n // This is a known issue, but considered an edge case. The alternative would\n // be to copy the array before executing the loop, but this has\n // performance implications.\n for (let i = 0; i < array.length && !subscriber.closed; i++) {\n subscriber.next(array[i]);\n }\n subscriber.complete();\n });\n}\n\nexport function fromPromise<T>(promise: PromiseLike<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n promise\n .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, reportUnhandledError);\n });\n}\n\nexport function fromIterable<T>(iterable: Iterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n for (const value of iterable) {\n subscriber.next(value);\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n });\n}\n\nexport function fromAsyncIterable<T>(asyncIterable: AsyncIterable<T>) {\n return new Observable((subscriber: Subscriber<T>) => {\n process(asyncIterable, subscriber).catch((err) => subscriber.error(err));\n });\n}\n\nexport function fromReadableStreamLike<T>(readableStream: ReadableStreamLike<T>) {\n return fromAsyncIterable(readableStreamLikeToAsyncGenerator(readableStream));\n}\n\nasync function process<T>(asyncIterable: AsyncIterable<T>, subscriber: Subscriber<T>) {\n for await (const value of asyncIterable) {\n subscriber.next(value);\n // A side-effect may have closed our subscriber,\n // check before the next iteration.\n if (subscriber.closed) {\n return;\n }\n }\n subscriber.complete();\n}\n","import { Subscription } from '../Subscription';\nimport { SchedulerAction, SchedulerLike } from '../types';\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay: number,\n repeat: true\n): void;\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay?: number,\n repeat?: false\n): Subscription;\n\nexport function executeSchedule(\n parentSubscription: Subscription,\n scheduler: SchedulerLike,\n work: () => void,\n delay = 0,\n repeat = false\n): Subscription | void {\n const scheduleSubscription = scheduler.schedule(function (this: SchedulerAction<any>) {\n work();\n if (repeat) {\n parentSubscription.add(this.schedule(null, delay));\n } else {\n this.unsubscribe();\n }\n }, delay);\n\n parentSubscription.add(scheduleSubscription);\n\n if (!repeat) {\n // Because user-land scheduler implementations are unlikely to properly reuse\n // Actions for repeat scheduling, we can't trust that the returned subscription\n // will control repeat subscription scenarios. So we're trying to avoid using them\n // incorrectly within this library.\n return scheduleSubscription;\n }\n}\n","/** @prettier */\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Re-emits all notifications from source Observable with specified scheduler.\n *\n * <span class=\"informal\">Ensure a specific scheduler is used, from outside of an Observable.</span>\n *\n * `observeOn` is an operator that accepts a scheduler as a first parameter, which will be used to reschedule\n * notifications emitted by the source Observable. It might be useful, if you do not have control over\n * internal scheduler of a given Observable, but want to control when its values are emitted nevertheless.\n *\n * Returned Observable emits the same notifications (nexted values, complete and error events) as the source Observable,\n * but rescheduled with provided scheduler. Note that this doesn't mean that source Observables internal\n * scheduler will be replaced in any way. Original scheduler still will be used, but when the source Observable emits\n * notification, it will be immediately scheduled again - this time with scheduler passed to `observeOn`.\n * An anti-pattern would be calling `observeOn` on Observable that emits lots of values synchronously, to split\n * that emissions into asynchronous chunks. For this to happen, scheduler would have to be passed into the source\n * Observable directly (usually into the operator that creates it). `observeOn` simply delays notifications a\n * little bit more, to ensure that they are emitted at expected moments.\n *\n * As a matter of fact, `observeOn` accepts second parameter, which specifies in milliseconds with what delay notifications\n * will be emitted. The main difference between {@link delay} operator and `observeOn` is that `observeOn`\n * will delay all notifications - including error notifications - while `delay` will pass through error\n * from source Observable immediately when it is emitted. In general it is highly recommended to use `delay` operator\n * for any kind of delaying of values in the stream, while using `observeOn` to specify which scheduler should be used\n * for notification emissions in general.\n *\n * ## Example\n *\n * Ensure values in subscribe are called just before browser repaint\n *\n * ```ts\n * import { interval, observeOn, animationFrameScheduler } from 'rxjs';\n *\n * const someDiv = document.createElement('div');\n * someDiv.style.cssText = 'width: 200px;background: #09c';\n * document.body.appendChild(someDiv);\n * const intervals = interval(10); // Intervals are scheduled\n * // with async scheduler by default...\n * intervals.pipe(\n * observeOn(animationFrameScheduler) // ...but we will observe on animationFrame\n * ) // scheduler to ensure smooth animation.\n * .subscribe(val => {\n * someDiv.style.height = val + 'px';\n * });\n * ```\n *\n * @see {@link delay}\n *\n * @param scheduler Scheduler that will be used to reschedule notifications from source Observable.\n * @param delay Number of milliseconds that states with what delay every notification should be rescheduled.\n * @return A function that returns an Observable that emits the same\n * notifications as the source Observable, but with provided scheduler.\n */\nexport function observeOn<T>(scheduler: SchedulerLike, delay = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => executeSchedule(subscriber, scheduler, () => subscriber.next(value), delay),\n () => executeSchedule(subscriber, scheduler, () => subscriber.complete(), delay),\n (err) => executeSchedule(subscriber, scheduler, () => subscriber.error(err), delay)\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Asynchronously subscribes Observers to this Observable on the specified {@link SchedulerLike}.\n *\n * With `subscribeOn` you can decide what type of scheduler a specific Observable will be using when it is subscribed to.\n *\n * Schedulers control the speed and order of emissions to observers from an Observable stream.\n *\n * ![](subscribeOn.png)\n *\n * ## Example\n *\n * Given the following code:\n *\n * ```ts\n * import { of, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3);\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * // 6\n * ```\n *\n * Both Observable `a` and `b` will emit their values directly and synchronously once they are subscribed to.\n *\n * If we instead use the `subscribeOn` operator declaring that we want to use the {@link asyncScheduler} for values emitted by Observable `a`:\n *\n * ```ts\n * import { of, subscribeOn, asyncScheduler, merge } from 'rxjs';\n *\n * const a = of(1, 2, 3).pipe(subscribeOn(asyncScheduler));\n * const b = of(4, 5, 6);\n *\n * merge(a, b).subscribe(console.log);\n *\n * // Outputs\n * // 4\n * // 5\n * // 6\n * // 1\n * // 2\n * // 3\n * ```\n *\n * The reason for this is that Observable `b` emits its values directly and synchronously like before\n * but the emissions from `a` are scheduled on the event loop because we are now using the {@link asyncScheduler} for that specific Observable.\n *\n * @param scheduler The {@link SchedulerLike} to perform subscription actions on.\n * @param delay A delay to pass to the scheduler to delay subscriptions\n * @return A function that returns an Observable modified so that its\n * subscriptions happen on the specified {@link SchedulerLike}.\n */\nexport function subscribeOn<T>(scheduler: SchedulerLike, delay: number = 0): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n subscriber.add(scheduler.schedule(() => source.subscribe(subscriber), delay));\n });\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { InteropObservable, SchedulerLike } from '../types';\n\nexport function scheduleObservable<T>(input: InteropObservable<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { observeOn } from '../operators/observeOn';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { SchedulerLike } from '../types';\n\nexport function schedulePromise<T>(input: PromiseLike<T>, scheduler: SchedulerLike) {\n return innerFrom(input).pipe(subscribeOn(scheduler), observeOn(scheduler));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\n\nexport function scheduleArray<T>(input: ArrayLike<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n // The current array index.\n let i = 0;\n // Start iterating over the array like on a schedule.\n return scheduler.schedule(function () {\n if (i === input.length) {\n // If we have hit the end of the array like in the\n // previous job, we can complete.\n subscriber.complete();\n } else {\n // Otherwise let's next the value at the current index,\n // then increment our index.\n subscriber.next(input[i++]);\n // If the last emission didn't cause us to close the subscriber\n // (via take or some side effect), reschedule the job and we'll\n // make another pass.\n if (!subscriber.closed) {\n this.schedule();\n }\n }\n });\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { iterator as Symbol_iterator } from '../symbol/iterator';\nimport { isFunction } from '../util/isFunction';\nimport { executeSchedule } from '../util/executeSchedule';\n\n/**\n * Used in {@link scheduled} to create an observable from an Iterable.\n * @param input The iterable to create an observable from\n * @param scheduler The scheduler to use\n */\nexport function scheduleIterable<T>(input: Iterable<T>, scheduler: SchedulerLike) {\n return new Observable<T>((subscriber) => {\n let iterator: Iterator<T, T>;\n\n // Schedule the initial creation of the iterator from\n // the iterable. This is so the code in the iterable is\n // not called until the scheduled job fires.\n executeSchedule(subscriber, scheduler, () => {\n // Create the iterator.\n iterator = (input as any)[Symbol_iterator]();\n\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n let value: T;\n let done: boolean | undefined;\n try {\n // Pull the value out of the iterator\n ({ value, done } = iterator.next());\n } catch (err) {\n // We got an error while pulling from the iterator\n subscriber.error(err);\n return;\n }\n\n if (done) {\n // If it is \"done\" we just complete. This mimics the\n // behavior of JavaScript's `for..of` consumption of\n // iterables, which will not emit the value from an iterator\n // result of `{ done: true: value: 'here' }`.\n subscriber.complete();\n } else {\n // The iterable is not done, emit the value.\n subscriber.next(value);\n }\n },\n 0,\n true\n );\n });\n\n // During finalization, if we see this iterator has a `return` method,\n // then we know it is a Generator, and not just an Iterator. So we call\n // the `return()` function. This will ensure that any `finally { }` blocks\n // inside of the generator we can hit will be hit properly.\n return () => isFunction(iterator?.return) && iterator.return();\n });\n}\n","import { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function scheduleAsyncIterable<T>(input: AsyncIterable<T>, scheduler: SchedulerLike) {\n if (!input) {\n throw new Error('Iterable cannot be null');\n }\n return new Observable<T>((subscriber) => {\n executeSchedule(subscriber, scheduler, () => {\n const iterator = input[Symbol.asyncIterator]();\n executeSchedule(\n subscriber,\n scheduler,\n () => {\n iterator.next().then((result) => {\n if (result.done) {\n // This will remove the subscriptions from\n // the parent subscription.\n subscriber.complete();\n } else {\n subscriber.next(result.value);\n }\n });\n },\n 0,\n true\n );\n });\n });\n}\n","import { SchedulerLike, ReadableStreamLike } from '../types';\nimport { Observable } from '../Observable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { readableStreamLikeToAsyncGenerator } from '../util/isReadableStreamLike';\n\nexport function scheduleReadableStreamLike<T>(input: ReadableStreamLike<T>, scheduler: SchedulerLike): Observable<T> {\n return scheduleAsyncIterable(readableStreamLikeToAsyncGenerator(input), scheduler);\n}\n","import { scheduleObservable } from './scheduleObservable';\nimport { schedulePromise } from './schedulePromise';\nimport { scheduleArray } from './scheduleArray';\nimport { scheduleIterable } from './scheduleIterable';\nimport { scheduleAsyncIterable } from './scheduleAsyncIterable';\nimport { isInteropObservable } from '../util/isInteropObservable';\nimport { isPromise } from '../util/isPromise';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isIterable } from '../util/isIterable';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { isAsyncIterable } from '../util/isAsyncIterable';\nimport { createInvalidObservableTypeError } from '../util/throwUnobservableError';\nimport { isReadableStreamLike } from '../util/isReadableStreamLike';\nimport { scheduleReadableStreamLike } from './scheduleReadableStreamLike';\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 {@link from}\n * @see {@link 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 }\n if (isArrayLike(input)) {\n return scheduleArray(input, scheduler);\n }\n if (isPromise(input)) {\n return schedulePromise(input, scheduler);\n }\n if (isAsyncIterable(input)) {\n return scheduleAsyncIterable(input, scheduler);\n }\n if (isIterable(input)) {\n return scheduleIterable(input, scheduler);\n }\n if (isReadableStreamLike(input)) {\n return scheduleReadableStreamLike(input, scheduler);\n }\n }\n throw createInvalidObservableTypeError(input);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf } from '../types';\nimport { scheduled } from '../scheduled/scheduled';\nimport { innerFrom } from './innerFrom';\n\nexport function from<O extends ObservableInput<any>>(input: O): Observable<ObservedValueOf<O>>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function from<O extends ObservableInput<any>>(input: O, scheduler: SchedulerLike | undefined): 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 * Convert an infinite iterable (from a generator) to an Observable\n *\n * ```ts\n * import { from, take } from 'rxjs';\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 * With `asyncScheduler`\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 input A subscription object, a Promise, an Observable-like,\n * an Array, an iterable, or an array-like object to be converted.\n * @param scheduler An optional {@link SchedulerLike} on which to schedule the emission of values.\n * @return An Observable converted from {@link ObservableInput}.\n */\nexport function from<T>(input: ObservableInput<T>, scheduler?: SchedulerLike): Observable<T> {\n return scheduler ? scheduled(input, scheduler) : innerFrom(input);\n}\n","import { SchedulerLike, ValueFromArray } from '../types';\nimport { Observable } from '../Observable';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\n\n// Devs are more likely to pass null or undefined than they are a scheduler\n// without accompanying values. To make things easier for (naughty) devs who\n// use the `strictNullChecks: false` TypeScript compiler option, these\n// overloads with explicit null and undefined values are included.\n\nexport function of(value: null): Observable<null>;\nexport function of(value: undefined): Observable<undefined>;\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of(scheduler: SchedulerLike): Observable<never>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function of<A extends readonly unknown[]>(...valuesAndScheduler: [...A, SchedulerLike]): Observable<ValueFromArray<A>>;\n\nexport function of(): Observable<never>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function of<T>(): Observable<T>;\nexport function of<T>(value: T): Observable<T>;\nexport function of<A extends readonly unknown[]>(...values: A): Observable<ValueFromArray<A>>;\n\n/**\n * Converts the arguments to an observable sequence.\n *\n * <span class=\"informal\">Each argument becomes a `next` notification.</span>\n *\n * ![](of.png)\n *\n * Unlike {@link from}, it does not do any flattening and emits each argument in whole\n * as a separate `next` notification.\n *\n * ## Examples\n *\n * Emit the values `10, 20, 30`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of(10, 20, 30)\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: 10\n * // next: 20\n * // next: 30\n * // the end\n * ```\n *\n * Emit the array `[1, 2, 3]`\n *\n * ```ts\n * import { of } from 'rxjs';\n *\n * of([1, 2, 3])\n * .subscribe({\n * next: value => console.log('next:', value),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // Outputs\n * // next: [1, 2, 3]\n * // the end\n * ```\n *\n * @see {@link from}\n * @see {@link range}\n *\n * @param args A comma separated list of arguments you want to be emitted.\n * @return An Observable that synchronously emits the arguments described\n * above and then immediately completes.\n */\nexport function of<T>(...args: Array<T | SchedulerLike>): Observable<T> {\n const scheduler = popScheduler(args);\n return from(args as T[], scheduler);\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { SchedulerLike } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * Creates an observable that will create an error instance and push it to the consumer as an error\n * immediately upon subscription.\n *\n * <span class=\"informal\">Just errors and does nothing else</span>\n *\n * ![](throw.png)\n *\n * This creation function is useful for creating an observable that will create an error and error every\n * time it is subscribed to. Generally, inside of most operators when you might want to return an errored\n * observable, this is unnecessary. In most cases, such as in the inner return of {@link concatMap},\n * {@link mergeMap}, {@link defer}, and many others, you can simply throw the error, and RxJS will pick\n * that up and notify the consumer of the error.\n *\n * ## Example\n *\n * Create a simple observable that will create a new error with a timestamp and log it\n * and the message every time you subscribe to it\n *\n * ```ts\n * import { throwError } from 'rxjs';\n *\n * let errorCount = 0;\n *\n * const errorWithTimestamp$ = throwError(() => {\n * const error: any = new Error(`This is error number ${ ++errorCount }`);\n * error.timestamp = Date.now();\n * return error;\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * errorWithTimestamp$.subscribe({\n * error: err => console.log(err.timestamp, err.message)\n * });\n *\n * // Logs the timestamp and a new error message for each subscription\n * ```\n *\n * ### Unnecessary usage\n *\n * Using `throwError` inside of an operator or creation function\n * with a callback, is usually not necessary\n *\n * ```ts\n * import { of, concatMap, timer, throwError } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // This is probably overkill.\n * return throwError(() => new Error(`Invalid time ${ ms }`));\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * You can just throw the error instead\n *\n * ```ts\n * import { of, concatMap, timer } from 'rxjs';\n *\n * const delays$ = of(1000, 2000, Infinity, 3000);\n *\n * delays$.pipe(\n * concatMap(ms => {\n * if (ms < 10000) {\n * return timer(ms);\n * } else {\n * // Cleaner and easier to read for most folks.\n * throw new Error(`Invalid time ${ ms }`);\n * }\n * })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * @param errorFactory A factory function that will create the error instance that is pushed.\n */\nexport function throwError(errorFactory: () => any): Observable<never>;\n\n/**\n * Returns an observable that will error with the specified error immediately upon subscription.\n *\n * @param error The error instance to emit\n * @deprecated Support for passing an error value will be removed in v8. Instead, pass a factory function to `throwError(() => new Error('test'))`. This is\n * because it will create the error at the moment it should be created and capture a more appropriate stack trace. If\n * for some reason you need to create the error ahead of time, you can still do that: `const err = new Error('test'); throwError(() => err);`.\n */\nexport function throwError(error: any): Observable<never>;\n\n/**\n * Notifies the consumer of an error using a given scheduler by scheduling it at delay `0` upon subscription.\n *\n * @param errorOrErrorFactory An error instance or error factory\n * @param scheduler A scheduler to use to schedule the error notification\n * @deprecated The `scheduler` parameter will be removed in v8.\n * Use `throwError` in combination with {@link observeOn}: `throwError(() => new Error('test')).pipe(observeOn(scheduler));`.\n * Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function throwError(errorOrErrorFactory: any, scheduler: SchedulerLike): Observable<never>;\n\nexport function throwError(errorOrErrorFactory: any, scheduler?: SchedulerLike): Observable<never> {\n const errorFactory = isFunction(errorOrErrorFactory) ? errorOrErrorFactory : () => errorOrErrorFactory;\n const init = (subscriber: Subscriber<never>) => subscriber.error(errorFactory());\n return new Observable(scheduler ? (subscriber) => scheduler.schedule(init as any, 0, subscriber) : init);\n}\n","import { PartialObserver, ObservableNotification, CompleteNotification, NextNotification, ErrorNotification } from './types';\nimport { Observable } from './Observable';\nimport { EMPTY } from './observable/empty';\nimport { of } from './observable/of';\nimport { throwError } from './observable/throwError';\nimport { isFunction } from './util/isFunction';\n\n// TODO: When this enum is removed, replace it with a type alias. See #4556.\n/**\n * @deprecated Use a string literal instead. `NotificationKind` will be replaced with a type alias in v8.\n * It will not be replaced with a const enum as those are not compatible with isolated modules.\n */\nexport enum NotificationKind {\n NEXT = 'N',\n ERROR = 'E',\n COMPLETE = 'C',\n}\n\n/**\n * Represents a push-based event or value that an {@link Observable} can emit.\n * This class is particularly useful for operators that manage notifications,\n * like {@link materialize}, {@link dematerialize}, {@link observeOn}, and\n * others. Besides wrapping the actual delivered value, it also annotates it\n * with metadata of, for instance, what type of push message it is (`next`,\n * `error`, or `complete`).\n *\n * @see {@link materialize}\n * @see {@link dematerialize}\n * @see {@link observeOn}\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\nexport class Notification<T> {\n /**\n * A value signifying that the notification will \"next\" if observed. In truth,\n * This is really synonymous with just checking `kind === \"N\"`.\n * @deprecated Will be removed in v8. Instead, just check to see if the value of `kind` is `\"N\"`.\n */\n readonly hasValue: boolean;\n\n /**\n * Creates a \"Next\" notification object.\n * @param kind Always `'N'`\n * @param value The value to notify with if observed.\n * @deprecated Internal implementation detail. Use {@link Notification#createNext createNext} instead.\n */\n constructor(kind: 'N', value?: T);\n /**\n * Creates an \"Error\" notification object.\n * @param kind Always `'E'`\n * @param value Always `undefined`\n * @param error The error to notify with if observed.\n * @deprecated Internal implementation detail. Use {@link Notification#createError createError} instead.\n */\n constructor(kind: 'E', value: undefined, error: any);\n /**\n * Creates a \"completion\" notification object.\n * @param kind Always `'C'`\n * @deprecated Internal implementation detail. Use {@link Notification#createComplete createComplete} instead.\n */\n constructor(kind: 'C');\n constructor(public readonly kind: 'N' | 'E' | 'C', public readonly value?: T, public readonly error?: any) {\n this.hasValue = kind === 'N';\n }\n\n /**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param observer The observer to notify.\n */\n observe(observer: PartialObserver<T>): void {\n return observeNotification(this as ObservableNotification<T>, observer);\n }\n\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @param complete A complete handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void, error: (err: any) => void): void;\n /**\n * Executes the next handler if the Notification is of `kind` `\"N\"`. Otherwise\n * this will not error, and it will be a noop.\n * @param next The next handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n do(next: (value: T) => void): void;\n do(nextHandler: (value: T) => void, errorHandler?: (err: any) => void, completeHandler?: () => void): void {\n const { kind, value, error } = this;\n return kind === 'N' ? nextHandler?.(value!) : kind === 'E' ? errorHandler?.(error) : completeHandler?.();\n }\n\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @param complete A complete handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void, error: (err: any) => void, complete: () => void): void;\n /**\n * Executes a notification on the appropriate handler from a list provided.\n * If a handler is missing for the kind of notification, nothing is called\n * and no error is thrown, it will be a noop.\n * @param next A next handler\n * @param error An error handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void, error: (err: any) => void): void;\n /**\n * Executes the next handler if the Notification is of `kind` `\"N\"`. Otherwise\n * this will not error, and it will be a noop.\n * @param next The next handler\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(next: (value: T) => void): void;\n\n /**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param observer The observer to notify.\n * @deprecated Replaced with {@link Notification#observe observe}. Will be removed in v8.\n */\n accept(observer: PartialObserver<T>): void;\n accept(nextOrObserver: PartialObserver<T> | ((value: T) => void), error?: (err: any) => void, complete?: () => void) {\n return isFunction((nextOrObserver as any)?.next)\n ? this.observe(nextOrObserver as PartialObserver<T>)\n : this.do(nextOrObserver as (value: T) => void, error as any, complete as any);\n }\n\n /**\n * Returns a simple Observable that just delivers the notification represented\n * by this Notification instance.\n *\n * @deprecated Will be removed in v8. To convert a `Notification` to an {@link Observable},\n * use {@link of} and {@link dematerialize}: `of(notification).pipe(dematerialize())`.\n */\n toObservable(): Observable<T> {\n const { kind, value, error } = this;\n // Select the observable to return by `kind`\n const result =\n kind === 'N'\n ? // Next kind. Return an observable of that value.\n of(value!)\n : //\n kind === 'E'\n ? // Error kind. Return an observable that emits the error.\n throwError(() => error)\n : //\n kind === 'C'\n ? // Completion kind. Kind is \"C\", return an observable that just completes.\n EMPTY\n : // Unknown kind, return falsy, so we error below.\n 0;\n if (!result) {\n // TODO: consider removing this check. The only way to cause this would be to\n // use the Notification constructor directly in a way that is not type-safe.\n // and direct use of the Notification constructor is deprecated.\n throw new TypeError(`Unexpected notification kind ${kind}`);\n }\n return result;\n }\n\n private static completeNotification = new Notification('C') as Notification<never> & CompleteNotification;\n /**\n * A shortcut to create a Notification instance of the type `next` from a\n * given value.\n * @param value The `next` value.\n * @return The \"next\" Notification representing the argument.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createNext<T>(value: T) {\n return new Notification('N', value) as Notification<T> & NextNotification<T>;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `error` from a\n * given error.\n * @param err The `error` error.\n * @return The \"error\" Notification representing the argument.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createError(err?: any) {\n return new Notification('E', undefined, err) as Notification<never> & ErrorNotification;\n }\n\n /**\n * A shortcut to create a Notification instance of the type `complete`.\n * @return The valueless \"complete\" Notification.\n * @deprecated It is NOT recommended to create instances of `Notification` directly.\n * Rather, try to create POJOs matching the signature outlined in {@link ObservableNotification}.\n * For example: `{ kind: 'N', value: 1 }`, `{ kind: 'E', error: new Error('bad') }`, or `{ kind: 'C' }`.\n * Will be removed in v8.\n */\n static createComplete(): Notification<never> & CompleteNotification {\n return Notification.completeNotification;\n }\n}\n\n/**\n * Executes the appropriate handler on a passed `observer` given the `kind` of notification.\n * If the handler is missing it will do nothing. Even if the notification is an error, if\n * there is no error handler on the observer, an error will not be thrown, it will noop.\n * @param notification The notification object to observe.\n * @param observer The observer to notify.\n */\nexport function observeNotification<T>(notification: ObservableNotification<T>, observer: PartialObserver<T>) {\n const { kind, value, error } = notification as any;\n if (typeof kind !== 'string') {\n throw new TypeError('Invalid notification, missing \"kind\"');\n }\n kind === 'N' ? observer.next?.(value!) : kind === 'E' ? observer.error?.(error) : observer.complete?.();\n}\n","/** prettier */\nimport { Observable } from '../Observable';\nimport { isFunction } from './isFunction';\n\n/**\n * Tests to see if the object is an RxJS {@link Observable}\n * @param obj the object to test\n */\nexport function isObservable(obj: any): obj is Observable<unknown> {\n // The !! is to ensure that this publicly exposed function returns\n // `false` if something like `null` or `0` is passed.\n return !!obj && (obj instanceof Observable || (isFunction(obj.lift) && isFunction(obj.subscribe)));\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface EmptyError extends Error {}\n\nexport interface EmptyErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): EmptyError;\n}\n\n/**\n * An error thrown when an Observable or a sequence was queried but has no\n * elements.\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link single}\n * @see {@link firstValueFrom}\n * @see {@link lastValueFrom}\n */\nexport const EmptyError: EmptyErrorCtor = createErrorClass(\n (_super) =>\n function EmptyErrorImpl(this: any) {\n _super(this);\n this.name = 'EmptyError';\n this.message = 'no elements in sequence';\n }\n);\n","import { Observable } from './Observable';\nimport { EmptyError } from './util/EmptyError';\n\nexport interface LastValueFromConfig<T> {\n defaultValue: T;\n}\n\nexport function lastValueFrom<T, D>(source: Observable<T>, config: LastValueFromConfig<D>): Promise<T | D>;\nexport function lastValueFrom<T>(source: Observable<T>): Promise<T>;\n\n/**\n * Converts an observable to a promise by subscribing to the observable,\n * waiting for it to complete, and resolving the returned promise with the\n * last value from the observed stream.\n *\n * If the observable stream completes before any values were emitted, the\n * returned promise will reject with {@link EmptyError} or will resolve\n * with the default value if a default was specified.\n *\n * If the observable stream emits an error, the returned promise will reject\n * with that error.\n *\n * **WARNING**: Only use this with observables you *know* will complete. If the source\n * observable does not complete, you will end up with a promise that is hung up, and\n * potentially all of the state of an async function hanging out in memory. To avoid\n * this situation, look into adding something like {@link timeout}, {@link take},\n * {@link takeWhile}, or {@link takeUntil} amongst others.\n *\n * ## Example\n *\n * Wait for the last value from a stream and emit it from a promise in\n * an async function\n *\n * ```ts\n * import { interval, take, lastValueFrom } from 'rxjs';\n *\n * async function execute() {\n * const source$ = interval(2000).pipe(take(10));\n * const finalNumber = await lastValueFrom(source$);\n * console.log(`The final number is ${ finalNumber }`);\n * }\n *\n * execute();\n *\n * // Expected output:\n * // 'The final number is 9'\n * ```\n *\n * @see {@link firstValueFrom}\n *\n * @param source the observable to convert to a promise\n * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value\n */\nexport function lastValueFrom<T, D>(source: Observable<T>, config?: LastValueFromConfig<D>): Promise<T | D> {\n const hasConfig = typeof config === 'object';\n return new Promise<T | D>((resolve, reject) => {\n let _hasValue = false;\n let _value: T;\n source.subscribe({\n next: (value) => {\n _value = value;\n _hasValue = true;\n },\n error: reject,\n complete: () => {\n if (_hasValue) {\n resolve(_value);\n } else if (hasConfig) {\n resolve(config!.defaultValue);\n } else {\n reject(new EmptyError());\n }\n },\n });\n });\n}\n","import { Observable } from './Observable';\nimport { EmptyError } from './util/EmptyError';\nimport { SafeSubscriber } from './Subscriber';\n\nexport interface FirstValueFromConfig<T> {\n defaultValue: T;\n}\n\nexport function firstValueFrom<T, D>(source: Observable<T>, config: FirstValueFromConfig<D>): Promise<T | D>;\nexport function firstValueFrom<T>(source: Observable<T>): Promise<T>;\n\n/**\n * Converts an observable to a promise by subscribing to the observable,\n * and returning a promise that will resolve as soon as the first value\n * arrives from the observable. The subscription will then be closed.\n *\n * If the observable stream completes before any values were emitted, the\n * returned promise will reject with {@link EmptyError} or will resolve\n * with the default value if a default was specified.\n *\n * If the observable stream emits an error, the returned promise will reject\n * with that error.\n *\n * **WARNING**: Only use this with observables you *know* will emit at least one value,\n * *OR* complete. If the source observable does not emit one value or complete, you will\n * end up with a promise that is hung up, and potentially all of the state of an\n * async function hanging out in memory. To avoid this situation, look into adding\n * something like {@link timeout}, {@link take}, {@link takeWhile}, or {@link takeUntil}\n * amongst others.\n *\n * ## Example\n *\n * Wait for the first value from a stream and emit it from a promise in\n * an async function\n *\n * ```ts\n * import { interval, firstValueFrom } from 'rxjs';\n *\n * async function execute() {\n * const source$ = interval(2000);\n * const firstNumber = await firstValueFrom(source$);\n * console.log(`The first number is ${ firstNumber }`);\n * }\n *\n * execute();\n *\n * // Expected output:\n * // 'The first number is 0'\n * ```\n *\n * @see {@link lastValueFrom}\n *\n * @param source the observable to convert to a promise\n * @param config a configuration object to define the `defaultValue` to use if the source completes without emitting a value\n */\nexport function firstValueFrom<T, D>(source: Observable<T>, config?: FirstValueFromConfig<D>): Promise<T | D> {\n const hasConfig = typeof config === 'object';\n return new Promise<T | D>((resolve, reject) => {\n const subscriber = new SafeSubscriber<T>({\n next: (value) => {\n resolve(value);\n subscriber.unsubscribe();\n },\n error: reject,\n complete: () => {\n if (hasConfig) {\n resolve(config!.defaultValue);\n } else {\n reject(new EmptyError());\n }\n },\n });\n source.subscribe(subscriber);\n });\n}\n","import { createErrorClass } from './createErrorClass';\n\nexport interface ArgumentOutOfRangeError extends Error {}\n\nexport interface ArgumentOutOfRangeErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (): ArgumentOutOfRangeError;\n}\n\n/**\n * An error thrown when an element was queried at a certain index of an\n * Observable, but no such index or position exists in that sequence.\n *\n * @see {@link elementAt}\n * @see {@link take}\n * @see {@link takeLast}\n */\nexport const ArgumentOutOfRangeError: ArgumentOutOfRangeErrorCtor = createErrorClass(\n (_super) =>\n function ArgumentOutOfRangeErrorImpl(this: any) {\n _super(this);\n this.name = 'ArgumentOutOfRangeError';\n this.message = 'argument out of range';\n }\n);\n","import { createErrorClass } from './createErrorClass';\n\nexport interface NotFoundError extends Error {}\n\nexport interface NotFoundErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (message: string): NotFoundError;\n}\n\n/**\n * An error thrown when a value or values are missing from an\n * observable sequence.\n *\n * @see {@link operators/single}\n */\nexport const NotFoundError: NotFoundErrorCtor = createErrorClass(\n (_super) =>\n function NotFoundErrorImpl(this: any, message: string) {\n _super(this);\n this.name = 'NotFoundError';\n this.message = message;\n }\n);\n","import { createErrorClass } from './createErrorClass';\n\nexport interface SequenceError extends Error {}\n\nexport interface SequenceErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new (message: string): SequenceError;\n}\n\n/**\n * An error thrown when something is wrong with the sequence of\n * values arriving on the observable.\n *\n * @see {@link operators/single}\n */\nexport const SequenceError: SequenceErrorCtor = createErrorClass(\n (_super) =>\n function SequenceErrorImpl(this: any, message: string) {\n _super(this);\n this.name = 'SequenceError';\n this.message = message;\n }\n);\n","/**\n * Checks to see if a value is not only a `Date` object,\n * but a *valid* `Date` object that can be converted to a\n * number. For example, `new Date('blah')` is indeed an\n * `instanceof Date`, however it cannot be converted to a\n * number.\n */\nexport function isValidDate(value: any): value is Date {\n return value instanceof Date && !isNaN(value as any);\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { isValidDate } from '../util/isDate';\nimport { Subscription } from '../Subscription';\nimport { operate } from '../util/lift';\nimport { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createErrorClass } from '../util/createErrorClass';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport interface TimeoutConfig<T, O extends ObservableInput<unknown> = ObservableInput<T>, M = unknown> {\n /**\n * The time allowed between values from the source before timeout is triggered.\n */\n each?: number;\n\n /**\n * The relative time as a `number` in milliseconds, or a specific time as a `Date` object,\n * by which the first value must arrive from the source before timeout is triggered.\n */\n first?: number | Date;\n\n /**\n * The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler}\n */\n scheduler?: SchedulerLike;\n\n /**\n * A factory used to create observable to switch to when timeout occurs. Provides\n * a {@link TimeoutInfo} about the source observable's emissions and what delay or\n * exact time triggered the timeout.\n */\n with?: (info: TimeoutInfo<T, M>) => O;\n\n /**\n * Optional additional metadata you can provide to code that handles\n * the timeout, will be provided through the {@link TimeoutError}.\n * This can be used to help identify the source of a timeout or pass along\n * other information related to the timeout.\n */\n meta?: M;\n}\n\nexport interface TimeoutInfo<T, M = unknown> {\n /** Optional metadata that was provided to the timeout configuration. */\n readonly meta: M;\n /** The number of messages seen before the timeout */\n readonly seen: number;\n /** The last message seen */\n readonly lastValue: T | null;\n}\n\n/**\n * An error emitted when a timeout occurs.\n */\nexport interface TimeoutError<T = unknown, M = unknown> extends Error {\n /**\n * The information provided to the error by the timeout\n * operation that created the error. Will be `null` if\n * used directly in non-RxJS code with an empty constructor.\n * (Note that using this constructor directly is not recommended,\n * you should create your own errors)\n */\n info: TimeoutInfo<T, M> | null;\n}\n\nexport interface TimeoutErrorCtor {\n /**\n * @deprecated Internal implementation detail. Do not construct error instances.\n * Cannot be tagged as internal: https://github.com/ReactiveX/rxjs/issues/6269\n */\n new <T = unknown, M = unknown>(info?: TimeoutInfo<T, M>): TimeoutError<T, M>;\n}\n\n/**\n * An error thrown by the {@link timeout} operator.\n *\n * Provided so users can use as a type and do quality comparisons.\n * We recommend you do not subclass this or create instances of this class directly.\n * If you have need of a error representing a timeout, you should\n * create your own error class and use that.\n *\n * @see {@link timeout}\n */\nexport const TimeoutError: TimeoutErrorCtor = createErrorClass(\n (_super) =>\n function TimeoutErrorImpl(this: any, info: TimeoutInfo<any> | null = null) {\n _super(this);\n this.message = 'Timeout has occurred';\n this.name = 'TimeoutError';\n this.info = info;\n }\n);\n\n/**\n * If `with` is provided, this will return an observable that will switch to a different observable if the source\n * does not push values within the specified time parameters.\n *\n * <span class=\"informal\">The most flexible option for creating a timeout behavior.</span>\n *\n * The first thing to know about the configuration is if you do not provide a `with` property to the configuration,\n * when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory\n * function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by\n * the settings in `first` and `each`.\n *\n * The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the\n * point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of\n * the first value from the source _only_. The timings of all subsequent values from the source will be checked\n * against the time period provided by `each`, if it was provided.\n *\n * The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of\n * time the resulting observable will wait between the arrival of values from the source before timing out. Note that if\n * `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first\n * value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first.\n *\n * ## Examples\n *\n * Emit a custom error if there is too much time between values\n *\n * ```ts\n * import { interval, timeout, throwError } from 'rxjs';\n *\n * class CustomTimeoutError extends Error {\n * constructor() {\n * super('It was too slow');\n * this.name = 'CustomTimeoutError';\n * }\n * }\n *\n * const slow$ = interval(900);\n *\n * slow$.pipe(\n * timeout({\n * each: 1000,\n * with: () => throwError(() => new CustomTimeoutError())\n * })\n * )\n * .subscribe({\n * error: console.error\n * });\n * ```\n *\n * Switch to a faster observable if your source is slow.\n *\n * ```ts\n * import { interval, timeout } from 'rxjs';\n *\n * const slow$ = interval(900);\n * const fast$ = interval(500);\n *\n * slow$.pipe(\n * timeout({\n * each: 1000,\n * with: () => fast$,\n * })\n * )\n * .subscribe(console.log);\n * ```\n * @param config The configuration for the timeout.\n */\nexport function timeout<T, O extends ObservableInput<unknown>, M = unknown>(\n config: TimeoutConfig<T, O, M> & { with: (info: TimeoutInfo<T, M>) => O }\n): OperatorFunction<T, T | ObservedValueOf<O>>;\n\n/**\n * Returns an observable that will error or switch to a different observable if the source does not push values\n * within the specified time parameters.\n *\n * <span class=\"informal\">The most flexible option for creating a timeout behavior.</span>\n *\n * The first thing to know about the configuration is if you do not provide a `with` property to the configuration,\n * when timeout conditions are met, this operator will emit a {@link TimeoutError}. Otherwise, it will use the factory\n * function provided by `with`, and switch your subscription to the result of that. Timeout conditions are provided by\n * the settings in `first` and `each`.\n *\n * The `first` property can be either a `Date` for a specific time, a `number` for a time period relative to the\n * point of subscription, or it can be skipped. This property is to check timeout conditions for the arrival of\n * the first value from the source _only_. The timings of all subsequent values from the source will be checked\n * against the time period provided by `each`, if it was provided.\n *\n * The `each` property can be either a `number` or skipped. If a value for `each` is provided, it represents the amount of\n * time the resulting observable will wait between the arrival of values from the source before timing out. Note that if\n * `first` is _not_ provided, the value from `each` will be used to check timeout conditions for the arrival of the first\n * value and all subsequent values. If `first` _is_ provided, `each` will only be use to check all values after the first.\n *\n * ### Handling TimeoutErrors\n *\n * If no `with` property was provided, subscriptions to the resulting observable may emit an error of {@link TimeoutError}.\n * The timeout error provides useful information you can examine when you're handling the error. The most common way to handle\n * the error would be with {@link catchError}, although you could use {@link tap} or just the error handler in your `subscribe` call\n * directly, if your error handling is only a side effect (such as notifying the user, or logging).\n *\n * In this case, you would check the error for `instanceof TimeoutError` to validate that the error was indeed from `timeout`, and\n * not from some other source. If it's not from `timeout`, you should probably rethrow it if you're in a `catchError`.\n *\n * ## Examples\n *\n * Emit a {@link TimeoutError} if the first value, and _only_ the first value, does not arrive within 5 seconds\n *\n * ```ts\n * import { interval, timeout } from 'rxjs';\n *\n * // A random interval that lasts between 0 and 10 seconds per tick\n * const source$ = interval(Math.round(Math.random() * 10_000));\n *\n * source$.pipe(\n * timeout({ first: 5_000 })\n * )\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * Emit a {@link TimeoutError} if the source waits longer than 5 seconds between any two values or the first value\n * and subscription.\n *\n * ```ts\n * import { timer, timeout, expand } from 'rxjs';\n *\n * const getRandomTime = () => Math.round(Math.random() * 10_000);\n *\n * // An observable that waits a random amount of time between each delivered value\n * const source$ = timer(getRandomTime())\n * .pipe(expand(() => timer(getRandomTime())));\n *\n * source$\n * .pipe(timeout({ each: 5_000 }))\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n *\n * Emit a {@link TimeoutError} if the source does not emit before 7 seconds, _or_ if the source waits longer than\n * 5 seconds between any two values after the first.\n *\n * ```ts\n * import { timer, timeout, expand } from 'rxjs';\n *\n * const getRandomTime = () => Math.round(Math.random() * 10_000);\n *\n * // An observable that waits a random amount of time between each delivered value\n * const source$ = timer(getRandomTime())\n * .pipe(expand(() => timer(getRandomTime())));\n *\n * source$\n * .pipe(timeout({ first: 7_000, each: 5_000 }))\n * .subscribe({\n * next: console.log,\n * error: console.error\n * });\n * ```\n */\nexport function timeout<T, M = unknown>(config: Omit<TimeoutConfig<T, any, M>, 'with'>): OperatorFunction<T, T>;\n\n/**\n * Returns an observable that will error if the source does not push its first value before the specified time passed as a `Date`.\n * This is functionally the same as `timeout({ first: someDate })`.\n *\n * <span class=\"informal\">Errors if the first value doesn't show up before the given date and time</span>\n *\n * ![](timeout.png)\n *\n * @param first The date to at which the resulting observable will timeout if the source observable\n * does not emit at least one value.\n * @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}.\n */\nexport function timeout<T>(first: Date, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an observable that will error if the source does not push a value within the specified time in milliseconds.\n * This is functionally the same as `timeout({ each: milliseconds })`.\n *\n * <span class=\"informal\">Errors if it waits too long between any value</span>\n *\n * ![](timeout.png)\n *\n * @param each The time allowed between each pushed value from the source before the resulting observable\n * will timeout.\n * @param scheduler The scheduler to use. Defaults to {@link asyncScheduler}.\n */\nexport function timeout<T>(each: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n *\n * Errors if Observable does not emit a value in given time span.\n *\n * <span class=\"informal\">Timeouts on Observable that doesn't emit values fast enough.</span>\n *\n * ![](timeout.png)\n *\n * @see {@link timeoutWith}\n *\n * @return A function that returns an Observable that mirrors behaviour of the\n * source Observable, unless timeout happens when it throws an error.\n */\nexport function timeout<T, O extends ObservableInput<any>, M>(\n config: number | Date | TimeoutConfig<T, O, M>,\n schedulerArg?: SchedulerLike\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n // Intentionally terse code.\n // If the first argument is a valid `Date`, then we use it as the `first` config.\n // Otherwise, if the first argument is a `number`, then we use it as the `each` config.\n // Otherwise, it can be assumed the first argument is the configuration object itself, and\n // we destructure that into what we're going to use, setting important defaults as we do.\n // NOTE: The default for `scheduler` will be the `scheduler` argument if it exists, or\n // it will default to the `asyncScheduler`.\n const {\n first,\n each,\n with: _with = timeoutErrorFactory,\n scheduler = schedulerArg ?? asyncScheduler,\n meta = null!,\n } = (isValidDate(config) ? { first: config } : typeof config === 'number' ? { each: config } : config) as TimeoutConfig<T, O, M>;\n\n if (first == null && each == null) {\n // Ensure timeout was provided at runtime.\n throw new TypeError('No timeout provided.');\n }\n\n return operate((source, subscriber) => {\n // This subscription encapsulates our subscription to the\n // source for this operator. We're capturing it separately,\n // because if there is a `with` observable to fail over to,\n // we want to unsubscribe from our original subscription, and\n // hand of the subscription to that one.\n let originalSourceSubscription: Subscription;\n // The subscription for our timeout timer. This changes\n // every time we get a new value.\n let timerSubscription: Subscription;\n // A bit of state we pass to our with and error factories to\n // tell what the last value we saw was.\n let lastValue: T | null = null;\n // A bit of state we pass to the with and error factories to\n // tell how many values we have seen so far.\n let seen = 0;\n const startTimer = (delay: number) => {\n timerSubscription = executeSchedule(\n subscriber,\n scheduler,\n () => {\n try {\n originalSourceSubscription.unsubscribe();\n innerFrom(\n _with!({\n meta,\n lastValue,\n seen,\n })\n ).subscribe(subscriber);\n } catch (err) {\n subscriber.error(err);\n }\n },\n delay\n );\n };\n\n originalSourceSubscription = source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // clear the timer so we can emit and start another one.\n timerSubscription?.unsubscribe();\n seen++;\n // Emit\n subscriber.next((lastValue = value));\n // null | undefined are both < 0. Thanks, JavaScript.\n each! > 0 && startTimer(each!);\n },\n undefined,\n undefined,\n () => {\n if (!timerSubscription?.closed) {\n timerSubscription?.unsubscribe();\n }\n // Be sure not to hold the last value in memory after unsubscription\n // it could be quite large.\n lastValue = null;\n }\n )\n );\n\n // Intentionally terse code.\n // If we've `seen` a value, that means the \"first\" clause was met already, if it existed.\n // it also means that a timer was already started for \"each\" (in the next handler above).\n // If `first` was provided, and it's a number, then use it.\n // If `first` was provided and it's not a number, it's a Date, and we get the difference between it and \"now\".\n // If `first` was not provided at all, then our first timer will be the value from `each`.\n !seen && startTimer(first != null ? (typeof first === 'number' ? first : +first - scheduler!.now()) : each!);\n });\n}\n\n/**\n * The default function to use to emit an error when timeout occurs and a `with` function\n * is not specified.\n * @param info The information about the timeout to pass along to the error\n */\nfunction timeoutErrorFactory(info: TimeoutInfo<any>): Observable<never> {\n throw new TimeoutError(info);\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function map<T, R>(project: (value: T, index: number) => R): OperatorFunction<T, R>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function map<T, R, A>(project: (this: A, value: T, index: number) => R, thisArg: A): OperatorFunction<T, R>;\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 *\n * Map every click to the `clientX` position of that click\n *\n * ```ts\n * import { fromEvent, map } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const positions = clicks.pipe(map(ev => ev.clientX));\n *\n * positions.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mapTo}\n * @see {@link pluck}\n *\n * @param project The function to apply to each `value` emitted by the source\n * Observable. The `index` parameter is the number `i` for the i-th emission\n * that has happened since the subscription, starting from the number `0`.\n * @param thisArg An optional argument to define what `this` is in the\n * `project` function.\n * @return A function that returns an Observable that emits the values from the\n * source Observable transformed by the given `project` function.\n */\nexport function map<T, R>(project: (value: T, index: number) => R, thisArg?: any): OperatorFunction<T, R> {\n return operate((source, subscriber) => {\n // The index of the value from the source. Used with projection.\n let index = 0;\n // Subscribe to the source, all errors and completions are sent along\n // to the consumer.\n source.subscribe(\n createOperatorSubscriber(subscriber, (value: T) => {\n // Call the projection function with the appropriate this context,\n // and send the resulting value to the consumer.\n subscriber.next(project.call(thisArg, value, index++));\n })\n );\n });\n}\n","import { OperatorFunction } from \"../types\";\nimport { map } from \"../operators/map\";\n\nconst { isArray } = Array;\n\nfunction callOrApply<T, R>(fn: ((...values: T[]) => R), args: T|T[]): R {\n return isArray(args) ? fn(...args) : fn(args);\n}\n\n/**\n * Used in several -- mostly deprecated -- situations where we need to \n * apply a list of arguments or a single argument to a result selector.\n */\nexport function mapOneOrManyArgs<T, R>(fn: ((...values: T[]) => R)): OperatorFunction<T|T[], R> {\n return map(args => callOrApply(fn, args))\n}","import { SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { Observable } from '../Observable';\nimport { subscribeOn } from '../operators/subscribeOn';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { observeOn } from '../operators/observeOn';\nimport { AsyncSubject } from '../AsyncSubject';\n\nexport function bindCallbackInternals(\n isNodeStyle: boolean,\n callbackFunc: any,\n resultSelector?: any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<unknown> {\n if (resultSelector) {\n if (isScheduler(resultSelector)) {\n scheduler = resultSelector;\n } else {\n // The user provided a result selector.\n return function (this: any, ...args: any[]) {\n return (bindCallbackInternals(isNodeStyle, callbackFunc, scheduler) as any)\n .apply(this, args)\n .pipe(mapOneOrManyArgs(resultSelector as any));\n };\n }\n }\n\n // If a scheduler was passed, use our `subscribeOn` and `observeOn` operators\n // to compose that behavior for the user.\n if (scheduler) {\n return function (this: any, ...args: any[]) {\n return (bindCallbackInternals(isNodeStyle, callbackFunc) as any)\n .apply(this, args)\n .pipe(subscribeOn(scheduler!), observeOn(scheduler!));\n };\n }\n\n return function (this: any, ...args: any[]): Observable<any> {\n // We're using AsyncSubject, because it emits when it completes,\n // and it will play the value to all late-arriving subscribers.\n const subject = new AsyncSubject<any>();\n\n // If this is true, then we haven't called our function yet.\n let uninitialized = true;\n return new Observable((subscriber) => {\n // Add our subscriber to the subject.\n const subs = subject.subscribe(subscriber);\n\n if (uninitialized) {\n uninitialized = false;\n // We're going to execute the bound function\n // This bit is to signal that we are hitting the callback asynchronously.\n // Because we don't have any anti-\"Zalgo\" guarantees with whatever\n // function we are handed, we use this bit to figure out whether or not\n // we are getting hit in a callback synchronously during our call.\n let isAsync = false;\n\n // This is used to signal that the callback completed synchronously.\n let isComplete = false;\n\n // Call our function that has a callback. If at any time during this\n // call, an error is thrown, it will be caught by the Observable\n // subscription process and sent to the consumer.\n callbackFunc.apply(\n // Pass the appropriate `this` context.\n this,\n [\n // Pass the arguments.\n ...args,\n // And our callback handler.\n (...results: any[]) => {\n if (isNodeStyle) {\n // If this is a node callback, shift the first value off of the\n // results and check it, as it is the error argument. By shifting,\n // we leave only the argument(s) we want to pass to the consumer.\n const err = results.shift();\n if (err != null) {\n subject.error(err);\n // If we've errored, we can stop processing this function\n // as there's nothing else to do. Just return to escape.\n return;\n }\n }\n // If we have one argument, notify the consumer\n // of it as a single value, otherwise, if there's more than one, pass\n // them as an array. Note that if there are no arguments, `undefined`\n // will be emitted.\n subject.next(1 < results.length ? results : results[0]);\n // Flip this flag, so we know we can complete it in the synchronous\n // case below.\n isComplete = true;\n // If we're not asynchronous, we need to defer the `complete` call\n // until after the call to the function is over. This is because an\n // error could be thrown in the function after it calls our callback,\n // and if that is the case, if we complete here, we are unable to notify\n // the consumer than an error occurred.\n if (isAsync) {\n subject.complete();\n }\n },\n ]\n );\n // If we flipped `isComplete` during the call, we resolved synchronously,\n // notify complete, because we skipped it in the callback to wait\n // to make sure there were no errors during the call.\n if (isComplete) {\n subject.complete();\n }\n\n // We're no longer synchronous. If the callback is called at this point\n // we can notify complete on the spot.\n isAsync = true;\n }\n\n // Return the subscription from adding our subscriber to the subject.\n return subs;\n });\n };\n}\n","/* @prettier */\nimport { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { bindCallbackInternals } from './bindCallbackInternals';\n\nexport function bindCallback(\n callbackFunc: (...args: any[]) => void,\n resultSelector: (...args: any[]) => any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any>;\n\n// args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list\nexport function bindCallback<A extends readonly unknown[], R extends readonly unknown[]>(\n callbackFunc: (...args: [...A, (...res: R) => void]) => void,\n schedulerLike?: SchedulerLike\n): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;\n\n/**\n * Converts a callback API to a function that returns an Observable.\n *\n * <span class=\"informal\">Give it a function `f` of type `f(x, callback)` and\n * it will return a function `g` that when called as `g(x)` will output an\n * Observable.</span>\n *\n * `bindCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters. The\n * last parameter must be a callback function that `func` calls when it is\n * done.\n *\n * The output of `bindCallback` is a function that takes the same parameters\n * as `func`, except the last one (the callback). When the output function\n * is called with arguments it will return an Observable. If function `func`\n * calls its callback with one argument, the Observable will emit that value.\n * If on the other hand the callback is called with multiple values the resulting\n * Observable will emit an array with said values as arguments.\n *\n * It is **very important** to remember that input function `func` is not called\n * when the output function is, but rather when the Observable returned by the output\n * function is subscribed. This means if `func` makes an AJAX request, that request\n * will be made every time someone subscribes to the resulting Observable, but not before.\n *\n * The last optional parameter - `scheduler` - can be used to control when the call\n * to `func` happens after someone subscribes to Observable, as well as when results\n * passed to callback will be emitted. By default, the subscription to an Observable calls `func`\n * synchronously, but using {@link asyncScheduler} as the last parameter will defer the call to `func`,\n * just like wrapping the call in `setTimeout` with a timeout of `0` would. If you were to use the async Scheduler\n * and call `subscribe` on the output Observable, all function calls that are currently executing\n * will end before `func` is invoked.\n *\n * By default, results passed to the callback are emitted immediately after `func` invokes the callback.\n * In particular, if the callback is called synchronously, then the subscription of the resulting Observable\n * will call the `next` function synchronously as well. If you want to defer that call,\n * you may use {@link asyncScheduler} just as before. This means that by using `Scheduler.async` you can\n * ensure that `func` always calls its callback asynchronously, thus avoiding terrifying Zalgo.\n *\n * Note that the Observable created by the output function will always emit a single value\n * and then complete immediately. If `func` calls the callback multiple times, values from subsequent\n * calls will not appear in the stream. If you need to listen for multiple calls,\n * you probably want to use {@link fromEvent} or {@link fromEventPattern} instead.\n *\n * If `func` depends on some context (`this` property) and is not already bound, the context of `func`\n * will be the context that the output function has at call time. In particular, if `func`\n * is called as a method of some object and if `func` is not already bound, in order to preserve the context\n * it is recommended that the context of the output function is set to that object as well.\n *\n * If the input function calls its callback in the \"node style\" (i.e. first argument to callback is\n * optional error parameter signaling whether the call failed or not), {@link bindNodeCallback}\n * provides convenient error handling and probably is a better choice.\n * `bindCallback` will treat such functions the same as any other and error parameters\n * (whether passed or not) will always be interpreted as regular callback argument.\n *\n * ## Examples\n *\n * Convert jQuery's getJSON to an Observable API\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n * import * as jQuery from 'jquery';\n *\n * // Suppose we have jQuery.getJSON('/my/url', callback)\n * const getJSONAsObservable = bindCallback(jQuery.getJSON);\n * const result = getJSONAsObservable('/my/url');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * Receive an array of arguments passed to a callback\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const someFunction = (n, s, cb) => {\n * cb(n, s, { someProperty: 'someValue' });\n * };\n *\n * const boundSomeFunction = bindCallback(someFunction);\n * boundSomeFunction(5, 'some string').subscribe((values) => {\n * console.log(values); // [5, 'some string', {someProperty: 'someValue'}]\n * });\n * ```\n *\n * Compare behaviour with and without `asyncScheduler`\n *\n * ```ts\n * import { bindCallback, asyncScheduler } from 'rxjs';\n *\n * function iCallMyCallbackSynchronously(cb) {\n * cb();\n * }\n *\n * const boundSyncFn = bindCallback(iCallMyCallbackSynchronously);\n * const boundAsyncFn = bindCallback(iCallMyCallbackSynchronously, null, asyncScheduler);\n *\n * boundSyncFn().subscribe(() => console.log('I was sync!'));\n * boundAsyncFn().subscribe(() => console.log('I was async!'));\n * console.log('This happened...');\n *\n * // Logs:\n * // I was sync!\n * // This happened...\n * // I was async!\n * ```\n *\n * Use `bindCallback` on an object method\n *\n * ```ts\n * import { bindCallback } from 'rxjs';\n *\n * const boundMethod = bindCallback(someObject.methodWithCallback);\n * boundMethod\n * .call(someObject) // make sure methodWithCallback has access to someObject\n * .subscribe(subscriber);\n * ```\n *\n * @see {@link bindNodeCallback}\n * @see {@link from}\n *\n * @param callbackFunc A function with a callback as the last parameter.\n * @param resultSelector A mapping function used to transform callback events.\n * @param scheduler The scheduler on which to schedule the callbacks.\n * @return A function which returns the Observable that delivers the same\n * values the callback would deliver.\n */\nexport function bindCallback(\n callbackFunc: (...args: [...any[], (...res: any) => void]) => void,\n resultSelector?: ((...args: any[]) => any) | SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<unknown> {\n return bindCallbackInternals(false, callbackFunc, resultSelector, scheduler);\n}\n","/* @prettier */\nimport { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { bindCallbackInternals } from './bindCallbackInternals';\n\nexport function bindNodeCallback(\n callbackFunc: (...args: any[]) => void,\n resultSelector: (...args: any[]) => any,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any>;\n\n// args is the arguments array and we push the callback on the rest tuple since the rest parameter must be last (only item) in a parameter list\nexport function bindNodeCallback<A extends readonly unknown[], R extends readonly unknown[]>(\n callbackFunc: (...args: [...A, (err: any, ...res: R) => void]) => void,\n schedulerLike?: SchedulerLike\n): (...arg: A) => Observable<R extends [] ? void : R extends [any] ? R[0] : R>;\n\n/**\n * Converts a Node.js-style callback API to a function that returns an\n * Observable.\n *\n * <span class=\"informal\">It's just like {@link bindCallback}, but the\n * callback is expected to be of type `callback(error, result)`.</span>\n *\n * `bindNodeCallback` is not an operator because its input and output are not\n * Observables. The input is a function `func` with some parameters, but the\n * last parameter must be a callback function that `func` calls when it is\n * done. The callback function is expected to follow Node.js conventions,\n * where the first argument to the callback is an error object, signaling\n * whether call was successful. If that object is passed to callback, it means\n * something went wrong.\n *\n * The output of `bindNodeCallback` is a function that takes the same\n * parameters as `func`, except the last one (the callback). When the output\n * function is called with arguments, it will return an Observable.\n * If `func` calls its callback with error parameter present, Observable will\n * error with that value as well. If error parameter is not passed, Observable will emit\n * second parameter. If there are more parameters (third and so on),\n * Observable will emit an array with all arguments, except first error argument.\n *\n * Note that `func` will not be called at the same time output function is,\n * but rather whenever resulting Observable is subscribed. By default call to\n * `func` will happen synchronously after subscription, but that can be changed\n * with proper `scheduler` provided as optional third parameter. {@link SchedulerLike}\n * can also control when values from callback will be emitted by Observable.\n * To find out more, check out documentation for {@link bindCallback}, where\n * {@link SchedulerLike} works exactly the same.\n *\n * As in {@link bindCallback}, context (`this` property) of input function will be set to context\n * of returned function, when it is called.\n *\n * After Observable emits value, it will complete immediately. This means\n * even if `func` calls callback again, values from second and consecutive\n * calls will never appear on the stream. If you need to handle functions\n * that call callbacks multiple times, check out {@link fromEvent} or\n * {@link fromEventPattern} instead.\n *\n * Note that `bindNodeCallback` can be used in non-Node.js environments as well.\n * \"Node.js-style\" callbacks are just a convention, so if you write for\n * browsers or any other environment and API you use implements that callback style,\n * `bindNodeCallback` can be safely used on that API functions as well.\n *\n * Remember that Error object passed to callback does not have to be an instance\n * of JavaScript built-in `Error` object. In fact, it does not even have to an object.\n * Error parameter of callback function is interpreted as \"present\", when value\n * of that parameter is truthy. It could be, for example, non-zero number, non-empty\n * string or boolean `true`. In all of these cases resulting Observable would error\n * with that value. This means usually regular style callbacks will fail very often when\n * `bindNodeCallback` is used. If your Observable errors much more often then you\n * would expect, check if callback really is called in Node.js-style and, if not,\n * switch to {@link bindCallback} instead.\n *\n * Note that even if error parameter is technically present in callback, but its value\n * is falsy, it still won't appear in array emitted by Observable.\n *\n * ## Examples\n *\n * Read a file from the filesystem and get the data as an Observable\n *\n * ```ts\n * import * as fs from 'fs';\n * const readFileAsObservable = bindNodeCallback(fs.readFile);\n * const result = readFileAsObservable('./roadNames.txt', 'utf8');\n * result.subscribe(x => console.log(x), e => console.error(e));\n * ```\n *\n * Use on function calling callback with multiple arguments\n *\n * ```ts\n * someFunction((err, a, b) => {\n * console.log(err); // null\n * console.log(a); // 5\n * console.log(b); // \"some string\"\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(value => {\n * console.log(value); // [5, \"some string\"]\n * });\n * ```\n *\n * Use on function calling callback in regular style\n *\n * ```ts\n * someFunction(a => {\n * console.log(a); // 5\n * });\n * const boundSomeFunction = bindNodeCallback(someFunction);\n * boundSomeFunction()\n * .subscribe(\n * value => {} // never gets called\n * err => console.log(err) // 5\n * );\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link from}\n *\n * @param callbackFunc Function with a Node.js-style callback as the last parameter.\n * @param resultSelector A mapping function used to transform callback events.\n * @param scheduler The scheduler on which to schedule the callbacks.\n * @return A function which returns the Observable that delivers the same values the\n * Node.js callback would deliver.\n */\nexport function bindNodeCallback(\n callbackFunc: (...args: [...any[], (err: any, ...res: any) => void]) => void,\n resultSelector?: ((...args: any[]) => any) | SchedulerLike,\n scheduler?: SchedulerLike\n): (...args: any[]) => Observable<any> {\n return bindCallbackInternals(true, callbackFunc, resultSelector, scheduler);\n}\n","const { isArray } = Array;\nconst { getPrototypeOf, prototype: objectProto, keys: getKeys } = Object;\n\n/**\n * Used in functions where either a list of arguments, a single array of arguments, or a\n * dictionary of arguments can be returned. Returns an object with an `args` property with\n * the arguments in an array, if it is a dictionary, it will also return the `keys` in another\n * property.\n */\nexport function argsArgArrayOrObject<T, O extends Record<string, T>>(args: T[] | [O] | [T[]]): { args: T[]; keys: string[] | null } {\n if (args.length === 1) {\n const first = args[0];\n if (isArray(first)) {\n return { args: first, keys: null };\n }\n if (isPOJO(first)) {\n const keys = getKeys(first);\n return {\n args: keys.map((key) => first[key]),\n keys,\n };\n }\n }\n\n return { args: args as T[], keys: null };\n}\n\nfunction isPOJO(obj: any): obj is object {\n return obj && typeof obj === 'object' && getPrototypeOf(obj) === objectProto;\n}\n","export function createObject(keys: string[], values: any[]) {\n return keys.reduce((result, key, i) => ((result[key] = values[i]), result), {} as any);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, SchedulerLike, ObservedValueOf, ObservableInputTuple } from '../types';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { Subscriber } from '../Subscriber';\nimport { from } from './from';\nimport { identity } from '../util/identity';\nimport { Subscription } from '../Subscription';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { popResultSelector, popScheduler } from '../util/args';\nimport { createObject } from '../util/createObject';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { AnyCatcher } from '../AnyCatcher';\nimport { executeSchedule } from '../util/executeSchedule';\n\n// combineLatest(any)\n// We put this first because we need to catch cases where the user has supplied\n// _exactly `any`_ as the argument. Since `any` literally matches _anything_,\n// we don't want it to randomly hit one of the other type signatures below,\n// as we have no idea at build-time what type we should be returning when given an any.\n\n/**\n * You have passed `any` here, we can't figure out if it is\n * an array or an object, so you're getting `unknown`. Use better types.\n * @param arg Something typed as `any`\n */\nexport function combineLatest<T extends AnyCatcher>(arg: T): Observable<unknown>;\n\n// combineLatest([a, b, c])\nexport function combineLatest(sources: []): Observable<never>;\nexport function combineLatest<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R,\n scheduler: SchedulerLike\n): Observable<R>;\nexport function combineLatest<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[]>(\n sources: readonly [...ObservableInputTuple<A>],\n scheduler: SchedulerLike\n): Observable<A>;\n\n// combineLatest(a, b, c)\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function combineLatest<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n ...sourcesAndResultSelectorAndScheduler: [...ObservableInputTuple<A>, (...values: A) => R, SchedulerLike]\n): Observable<R>;\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function combineLatest<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `combineLatestAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function combineLatest<A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): Observable<A>;\n\n// combineLatest({a, b, c})\nexport function combineLatest(sourcesObject: { [K in any]: never }): Observable<never>;\nexport function combineLatest<T extends Record<string, ObservableInput<any>>>(\n sourcesObject: T\n): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;\n\n/**\n * Combines multiple Observables to create an Observable whose values are\n * calculated from the latest values of each of its input Observables.\n *\n * <span class=\"informal\">Whenever any input Observable emits a value, it\n * computes a formula using the latest values from all the inputs, then emits\n * the output of that formula.</span>\n *\n * ![](combineLatest.png)\n *\n * `combineLatest` combines the values from all the Observables passed in the\n * observables array. This is done by subscribing to each Observable in order and,\n * whenever any Observable emits, collecting an array of the most recent\n * values from each Observable. So if you pass `n` Observables to this operator,\n * the returned Observable will always emit an array of `n` values, in an order\n * corresponding to the order of the passed Observables (the value from the first Observable\n * will be at index 0 of the array and so on).\n *\n * Static version of `combineLatest` accepts an array of Observables. Note that an array of\n * Observables is a good choice, if you don't know beforehand how many Observables\n * you will combine. Passing an empty array will result in an Observable that\n * completes immediately.\n *\n * To ensure the output array always has the same length, `combineLatest` will\n * actually wait for all input Observables to emit at least once,\n * before it starts emitting results. This means if some Observable emits\n * values before other Observables started emitting, all these values but the last\n * will be lost. On the other hand, if some Observable does not emit a value but\n * completes, resulting Observable will complete at the same moment without\n * emitting anything, since it will now be impossible to include a value from the\n * completed Observable in the resulting array. Also, if some input Observable does\n * not emit any value and never completes, `combineLatest` will also never emit\n * and never complete, since, again, it will wait for all streams to emit some\n * value.\n *\n * If at least one Observable was passed to `combineLatest` and all passed Observables\n * emitted something, the resulting Observable will complete when all combined\n * streams complete. So even if some Observable completes, the result of\n * `combineLatest` will still emit values when other Observables do. In case\n * of a completed Observable, its value from now on will always be the last\n * emitted value. On the other hand, if any Observable errors, `combineLatest`\n * will error immediately as well, and all other Observables will be unsubscribed.\n *\n * ## Examples\n *\n * Combine two timer Observables\n *\n * ```ts\n * import { timer, combineLatest } from 'rxjs';\n *\n * const firstTimer = timer(0, 1000); // emit 0, 1, 2... after every second, starting from now\n * const secondTimer = timer(500, 1000); // emit 0, 1, 2... after every second, starting 0,5s from now\n * const combinedTimers = combineLatest([firstTimer, secondTimer]);\n * combinedTimers.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0] after 0.5s\n * // [1, 0] after 1s\n * // [1, 1] after 1.5s\n * // [2, 1] after 2s\n * ```\n *\n * Combine a dictionary of Observables\n *\n * ```ts\n * import { of, delay, startWith, combineLatest } from 'rxjs';\n *\n * const observables = {\n * a: of(1).pipe(delay(1000), startWith(0)),\n * b: of(5).pipe(delay(5000), startWith(0)),\n * c: of(10).pipe(delay(10000), startWith(0))\n * };\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // { a: 0, b: 0, c: 0 } immediately\n * // { a: 1, b: 0, c: 0 } after 1s\n * // { a: 1, b: 5, c: 0 } after 5s\n * // { a: 1, b: 5, c: 10 } after 10s\n * ```\n *\n * Combine an array of Observables\n *\n * ```ts\n * import { of, delay, startWith, combineLatest } from 'rxjs';\n *\n * const observables = [1, 5, 10].map(\n * n => of(n).pipe(\n * delay(n * 1000), // emit 0 and then emit n after n seconds\n * startWith(0)\n * )\n * );\n * const combined = combineLatest(observables);\n * combined.subscribe(value => console.log(value));\n * // Logs\n * // [0, 0, 0] immediately\n * // [1, 0, 0] after 1s\n * // [1, 5, 0] after 5s\n * // [1, 5, 10] after 10s\n * ```\n *\n * Use map operator to dynamically calculate the Body-Mass Index\n *\n * ```ts\n * import { of, combineLatest, map } from 'rxjs';\n *\n * const weight = of(70, 72, 76, 79, 75);\n * const height = of(1.76, 1.77, 1.78);\n * const bmi = combineLatest([weight, height]).pipe(\n * map(([w, h]) => w / (h * h)),\n * );\n * bmi.subscribe(x => console.log('BMI is ' + x));\n *\n * // With output to console:\n * // BMI is 24.212293388429753\n * // BMI is 23.93948099205209\n * // BMI is 23.671253629592222\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link merge}\n * @see {@link withLatestFrom}\n *\n * @param args Any number of `ObservableInput`s provided either as an array or as an object\n * to combine with each other. If the last parameter is the function, it will be used to project the\n * values from the combined latest values into a new value on the output Observable.\n * @return An Observable of projected values from the most recent values from each `ObservableInput`,\n * or an array of the most recent values from each `ObservableInput`.\n */\nexport function combineLatest<O extends ObservableInput<any>, R>(...args: any[]): Observable<R> | Observable<ObservedValueOf<O>[]> {\n const scheduler = popScheduler(args);\n const resultSelector = popResultSelector(args);\n\n const { args: observables, keys } = argsArgArrayOrObject(args);\n\n if (observables.length === 0) {\n // If no observables are passed, or someone has passed an empty array\n // of observables, or even an empty object POJO, we need to just\n // complete (EMPTY), but we have to honor the scheduler provided if any.\n return from([], scheduler as any);\n }\n\n const result = new Observable<ObservedValueOf<O>[]>(\n combineLatestInit(\n observables as ObservableInput<ObservedValueOf<O>>[],\n scheduler,\n keys\n ? // A handler for scrubbing the array of args into a dictionary.\n (values) => createObject(keys, values)\n : // A passthrough to just return the array\n identity\n )\n );\n\n return resultSelector ? (result.pipe(mapOneOrManyArgs(resultSelector)) as Observable<R>) : result;\n}\n\nexport function combineLatestInit(\n observables: ObservableInput<any>[],\n scheduler?: SchedulerLike,\n valueTransform: (values: any[]) => any = identity\n) {\n return (subscriber: Subscriber<any>) => {\n // The outer subscription. We're capturing this in a function\n // because we may have to schedule it.\n maybeSchedule(\n scheduler,\n () => {\n const { length } = observables;\n // A store for the values each observable has emitted so far. We match observable to value on index.\n const values = new Array(length);\n // The number of currently active subscriptions, as they complete, we decrement this number to see if\n // we are all done combining values, so we can complete the result.\n let active = length;\n // The number of inner sources that still haven't emitted the first value\n // We need to track this because all sources need to emit one value in order\n // to start emitting values.\n let remainingFirstValues = length;\n // The loop to kick off subscription. We're keying everything on index `i` to relate the observables passed\n // in to the slot in the output array or the key in the array of keys in the output dictionary.\n for (let i = 0; i < length; i++) {\n maybeSchedule(\n scheduler,\n () => {\n const source = from(observables[i], scheduler as any);\n let hasFirstValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // When we get a value, record it in our set of values.\n values[i] = value;\n if (!hasFirstValue) {\n // If this is our first value, record that.\n hasFirstValue = true;\n remainingFirstValues--;\n }\n if (!remainingFirstValues) {\n // We're not waiting for any more\n // first values, so we can emit!\n subscriber.next(valueTransform(values.slice()));\n }\n },\n () => {\n if (!--active) {\n // We only complete the result if we have no more active\n // inner observables.\n subscriber.complete();\n }\n }\n )\n );\n },\n subscriber\n );\n }\n },\n subscriber\n );\n };\n}\n\n/**\n * A small utility to handle the couple of locations where we want to schedule if a scheduler was provided,\n * but we don't if there was no scheduler.\n */\nfunction maybeSchedule(scheduler: SchedulerLike | undefined, execute: () => void, subscription: Subscription) {\n if (scheduler) {\n executeSchedule(subscription, scheduler, execute);\n } else {\n execute();\n }\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { executeSchedule } from '../util/executeSchedule';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * A process embodying the general \"merge\" strategy. This is used in\n * `mergeMap` and `mergeScan` because the logic is otherwise nearly identical.\n * @param source The original source observable\n * @param subscriber The consumer subscriber\n * @param project The projection function to get our inner sources\n * @param concurrent The number of concurrent inner subscriptions\n * @param onBeforeNext Additional logic to apply before nexting to our consumer\n * @param expand If `true` this will perform an \"expand\" strategy, which differs only\n * in that it recurses, and the inner subscription must be schedule-able.\n * @param innerSubScheduler A scheduler to use to schedule inner subscriptions,\n * this is to support the expand strategy, mostly, and should be deprecated\n */\nexport function mergeInternals<T, R>(\n source: Observable<T>,\n subscriber: Subscriber<R>,\n project: (value: T, index: number) => ObservableInput<R>,\n concurrent: number,\n onBeforeNext?: (innerValue: R) => void,\n expand?: boolean,\n innerSubScheduler?: SchedulerLike,\n additionalFinalizer?: () => void\n) {\n // Buffered values, in the event of going over our concurrency limit\n const buffer: T[] = [];\n // The number of active inner subscriptions.\n let active = 0;\n // An index to pass to our accumulator function\n let index = 0;\n // Whether or not the outer source has completed.\n let isComplete = false;\n\n /**\n * Checks to see if we can complete our result or not.\n */\n const checkComplete = () => {\n // If the outer has completed, and nothing is left in the buffer,\n // and we don't have any active inner subscriptions, then we can\n // Emit the state and complete.\n if (isComplete && !buffer.length && !active) {\n subscriber.complete();\n }\n };\n\n // If we're under our concurrency limit, just start the inner subscription, otherwise buffer and wait.\n const outerNext = (value: T) => (active < concurrent ? doInnerSub(value) : buffer.push(value));\n\n const doInnerSub = (value: T) => {\n // If we're expanding, we need to emit the outer values and the inner values\n // as the inners will \"become outers\" in a way as they are recursively fed\n // back to the projection mechanism.\n expand && subscriber.next(value as any);\n\n // Increment the number of active subscriptions so we can track it\n // against our concurrency limit later.\n active++;\n\n // A flag used to show that the inner observable completed.\n // This is checked during finalization to see if we should\n // move to the next item in the buffer, if there is on.\n let innerComplete = false;\n\n // Start our inner subscription.\n innerFrom(project(value, index++)).subscribe(\n createOperatorSubscriber(\n subscriber,\n (innerValue) => {\n // `mergeScan` has additional handling here. For example\n // taking the inner value and updating state.\n onBeforeNext?.(innerValue);\n\n if (expand) {\n // If we're expanding, then just recurse back to our outer\n // handler. It will emit the value first thing.\n outerNext(innerValue as any);\n } else {\n // Otherwise, emit the inner value.\n subscriber.next(innerValue);\n }\n },\n () => {\n // Flag that we have completed, so we know to check the buffer\n // during finalization.\n innerComplete = true;\n },\n // Errors are passed to the destination.\n undefined,\n () => {\n // During finalization, if the inner completed (it wasn't errored or\n // cancelled), then we want to try the next item in the buffer if\n // there is one.\n if (innerComplete) {\n // We have to wrap this in a try/catch because it happens during\n // finalization, possibly asynchronously, and we want to pass\n // any errors that happen (like in a projection function) to\n // the outer Subscriber.\n try {\n // INNER SOURCE COMPLETE\n // Decrement the active count to ensure that the next time\n // we try to call `doInnerSub`, the number is accurate.\n active--;\n // If we have more values in the buffer, try to process those\n // Note that this call will increment `active` ahead of the\n // next conditional, if there were any more inner subscriptions\n // to start.\n while (buffer.length && active < concurrent) {\n const bufferedValue = buffer.shift()!;\n // Particularly for `expand`, we need to check to see if a scheduler was provided\n // for when we want to start our inner subscription. Otherwise, we just start\n // are next inner subscription.\n if (innerSubScheduler) {\n executeSchedule(subscriber, innerSubScheduler, () => doInnerSub(bufferedValue));\n } else {\n doInnerSub(bufferedValue);\n }\n }\n // Check to see if we can complete, and complete if so.\n checkComplete();\n } catch (err) {\n subscriber.error(err);\n }\n }\n }\n )\n );\n };\n\n // Subscribe to our source observable.\n source.subscribe(\n createOperatorSubscriber(subscriber, outerNext, () => {\n // Outer completed, make a note of it, and check to see if we can complete everything.\n isComplete = true;\n checkComplete();\n })\n );\n\n // Additional finalization (for when the destination is torn down).\n // Other finalization is added implicitly via subscription above.\n return () => {\n additionalFinalizer?.();\n };\n}\n","import { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function mergeMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined,\n concurrent?: number\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\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,\n concurrent?: number\n): 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 *\n * Map and flatten each letter to an Observable ticking every 1 second\n *\n * ```ts\n * import { of, mergeMap, interval, map } from 'rxjs';\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 *\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 every second 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 project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @param concurrent Maximum number of `ObservableInput`s being subscribed to concurrently.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and merging\n * the results of the Observables 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 = Infinity\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (isFunction(resultSelector)) {\n // DEPRECATED PATH\n return mergeMap((a, i) => map((b: any, ii: number) => resultSelector(a, b, i, ii))(innerFrom(project(a, i))), concurrent);\n } else if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n\n return operate((source, subscriber) => mergeInternals(source, subscriber, project, concurrent));\n}\n","import { mergeMap } from './mergeMap';\nimport { identity } from '../util/identity';\nimport { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable which\n * concurrently delivers all values that are emitted on the inner Observables.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](mergeAll.png)\n *\n * `mergeAll` subscribes to an Observable that emits Observables, also known as\n * a higher-order Observable. Each time it observes one of these emitted inner\n * Observables, it subscribes to that and delivers all the values from the\n * inner Observable on the output Observable. The output Observable only\n * completes once all inner Observables have completed. Any error delivered by\n * a inner Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n *\n * Spawn a new interval Observable for each click event, and blend their outputs as one Observable\n *\n * ```ts\n * import { fromEvent, map, interval, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(map(() => interval(1000)));\n * const firstOrder = higherOrder.pipe(mergeAll());\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * Count from 0 to 9 every second for each click, but only allow 2 concurrent timers\n *\n * ```ts\n * import { fromEvent, map, interval, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(10)))\n * );\n * const firstOrder = higherOrder.pipe(mergeAll(2));\n *\n * firstOrder.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link exhaustAll}\n * @see {@link merge}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @param concurrent Maximum number of inner Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable that emits values coming from\n * all the inner Observables emitted by the source Observable.\n */\nexport function mergeAll<O extends ObservableInput<any>>(concurrent: number = Infinity): OperatorFunction<O, ObservedValueOf<O>> {\n return mergeMap(identity, concurrent);\n}\n","import { mergeAll } from './mergeAll';\nimport { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\n\n/**\n * Converts a higher-order Observable into a first-order Observable by\n * concatenating the inner Observables in order.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by putting one\n * inner Observable after the other.</span>\n *\n * ![](concatAll.svg)\n *\n * Joins every Observable emitted by the source (a higher-order Observable), in\n * a serial fashion. It subscribes to each inner Observable only after the\n * previous inner Observable has completed, and merges all of their values into\n * the returned observable.\n *\n * __Warning:__ If the source Observable emits Observables quickly and\n * endlessly, and the inner Observables it emits generally complete slower than\n * the source emits, you can run into memory issues as the incoming Observables\n * collect in an unbounded buffer.\n *\n * Note: `concatAll` is equivalent to `mergeAll` with concurrency parameter set\n * to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, map, interval, take, concatAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(4)))\n * );\n * const firstOrder = higherOrder.pipe(concatAll());\n * firstOrder.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 combineLatestAll}\n * @see {@link concat}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link exhaustAll}\n * @see {@link mergeAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link zipAll}\n *\n * @return A function that returns an Observable emitting values from all the\n * inner Observables concatenated.\n */\nexport function concatAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return mergeAll(1);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple, SchedulerLike } from '../types';\nimport { concatAll } from '../operators/concatAll';\nimport { popScheduler } from '../util/args';\nimport { from } from './from';\n\nexport function concat<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\nexport function concat<T extends readonly unknown[]>(\n ...inputsAndScheduler: [...ObservableInputTuple<T>, SchedulerLike]\n): Observable<T[number]>;\n\n/**\n * Creates an output Observable which sequentially emits all values from the first given\n * Observable and then moves on to the next.\n *\n * <span class=\"informal\">Concatenates multiple Observables together by\n * sequentially emitting their values, one Observable after the other.</span>\n *\n * ![](concat.png)\n *\n * `concat` joins multiple Observables together, by subscribing to them one at a time and\n * merging their results into the output Observable. You can pass either an array of\n * Observables, or put them directly as arguments. Passing an empty array will result\n * in Observable that completes immediately.\n *\n * `concat` will subscribe to first input Observable and emit all its values, without\n * changing or affecting them in any way. When that Observable completes, it will\n * subscribe to then next Observable passed and, again, emit its values. This will be\n * repeated, until the operator runs out of Observables. When last input Observable completes,\n * `concat` will complete as well. At any given moment only one Observable passed to operator\n * emits values. If you would like to emit values from passed Observables concurrently, check out\n * {@link merge} instead, especially with optional `concurrent` parameter. As a matter of fact,\n * `concat` is an equivalent of `merge` operator with `concurrent` parameter set to `1`.\n *\n * Note that if some input Observable never completes, `concat` will also never complete\n * and Observables following the one that did not complete will never be subscribed. On the other\n * hand, if some Observable simply completes immediately after it is subscribed, it will be\n * invisible for `concat`, which will just move on to the next Observable.\n *\n * If any Observable in chain errors, instead of passing control to the next Observable,\n * `concat` will error immediately as well. Observables that would be subscribed after\n * the one that emitted error, never will.\n *\n * If you pass to `concat` the same Observable many times, its stream of values\n * will be \"replayed\" on every subscription, which means you can repeat given Observable\n * as many times as you like. If passing the same Observable to `concat` 1000 times becomes tedious,\n * you can always use {@link repeat}.\n *\n * ## Examples\n *\n * Concatenate a timer counting from 0 to 3 with a synchronous sequence from 1 to 10\n *\n * ```ts\n * import { interval, take, range, concat } from 'rxjs';\n *\n * const timer = interval(1000).pipe(take(4));\n * const sequence = range(1, 10);\n * const result = concat(timer, sequence);\n * result.subscribe(x => console.log(x));\n *\n * // results in:\n * // 0 -1000ms-> 1 -1000ms-> 2 -1000ms-> 3 -immediate-> 1 ... 10\n * ```\n *\n * Concatenate 3 Observables\n *\n * ```ts\n * import { interval, take, concat } from 'rxjs';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const result = concat(timer1, timer2, timer3);\n * result.subscribe(x => console.log(x));\n *\n * // results in the following:\n * // (Prints to console sequentially)\n * // -1000ms-> 0 -1000ms-> 1 -1000ms-> ... 9\n * // -2000ms-> 0 -2000ms-> 1 -2000ms-> ... 5\n * // -500ms-> 0 -500ms-> 1 -500ms-> ... 9\n * ```\n *\n * Concatenate the same Observable to repeat it\n *\n * ```ts\n * import { interval, take, concat } from 'rxjs';\n *\n * const timer = interval(1000).pipe(take(2));\n *\n * concat(timer, timer) // concatenating the same Observable!\n * .subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('...and it is done!')\n * });\n *\n * // Logs:\n * // 0 after 1s\n * // 1 after 2s\n * // 0 after 3s\n * // 1 after 4s\n * // '...and it is done!' also after 4s\n * ```\n *\n * @see {@link concatAll}\n * @see {@link concatMap}\n * @see {@link concatMapTo}\n * @see {@link startWith}\n * @see {@link endWith}\n *\n * @param args `ObservableInput`s to concatenate.\n */\nexport function concat(...args: any[]): Observable<unknown> {\n return concatAll()(from(args, popScheduler(args)));\n}\n","import { Observable } from '../Observable';\nimport { ObservedValueOf, ObservableInput } from '../types';\nimport { innerFrom } from './innerFrom';\n\n/**\n * Creates an Observable that, on subscribe, calls an Observable factory to\n * make an Observable for each new Observer.\n *\n * <span class=\"informal\">Creates the Observable lazily, that is, only when it\n * is subscribed.\n * </span>\n *\n * ![](defer.png)\n *\n * `defer` allows you to create an Observable only when the Observer\n * subscribes. It waits until an Observer subscribes to it, calls the given\n * factory function to get an Observable -- where a factory function typically\n * generates a new Observable -- and subscribes the Observer to this Observable.\n * In case the factory function returns a falsy value, then EMPTY is used as\n * Observable instead. Last but not least, an exception during the factory\n * function call is transferred to the Observer by calling `error`.\n *\n * ## Example\n *\n * Subscribe to either an Observable of clicks or an Observable of interval, at random\n *\n * ```ts\n * import { defer, fromEvent, interval } from 'rxjs';\n *\n * const clicksOrInterval = defer(() => {\n * return Math.random() > 0.5\n * ? fromEvent(document, 'click')\n * : interval(1000);\n * });\n * clicksOrInterval.subscribe(x => console.log(x));\n *\n * // Results in the following behavior:\n * // If the result of Math.random() is greater than 0.5 it will listen\n * // for clicks anywhere on the \"document\"; when document is clicked it\n * // will log a MouseEvent object to the console. If the result is less\n * // than 0.5 it will emit ascending numbers, one every second(1000ms).\n * ```\n *\n * @see {@link Observable}\n *\n * @param observableFactory The Observable factory function to invoke for each\n * Observer that subscribes to the output Observable. May also return any\n * `ObservableInput`, which will be converted on the fly to an Observable.\n * @return An Observable whose Observers' subscriptions trigger an invocation of the\n * given Observable factory function.\n */\nexport function defer<R extends ObservableInput<any>>(observableFactory: () => R): Observable<ObservedValueOf<R>> {\n return new Observable<ObservedValueOf<R>>((subscriber) => {\n innerFrom(observableFactory()).subscribe(subscriber);\n });\n}\n","import { Connectable, ObservableInput, SubjectLike } from '../types';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { Observable } from '../Observable';\nimport { defer } from './defer';\n\nexport interface ConnectableConfig<T> {\n /**\n * A factory function used to create the Subject through which the source\n * is multicast. By default this creates a {@link Subject}.\n */\n connector: () => SubjectLike<T>;\n /**\n * If true, the resulting observable will reset internal state upon disconnection\n * and return to a \"cold\" state. This allows the resulting observable to be\n * reconnected.\n * If false, upon disconnection, the connecting subject will remain the\n * connecting subject, meaning the resulting observable will not go \"cold\" again,\n * and subsequent repeats or resubscriptions will resubscribe to that same subject.\n */\n resetOnDisconnect?: boolean;\n}\n\n/**\n * The default configuration for `connectable`.\n */\nconst DEFAULT_CONFIG: ConnectableConfig<unknown> = {\n connector: () => new Subject<unknown>(),\n resetOnDisconnect: true,\n};\n\n/**\n * Creates an observable that multicasts once `connect()` is called on it.\n *\n * @param source The observable source to make connectable.\n * @param config The configuration object for `connectable`.\n * @returns A \"connectable\" observable, that has a `connect()` method, that you must call to\n * connect the source to all consumers through the subject provided as the connector.\n */\nexport function connectable<T>(source: ObservableInput<T>, config: ConnectableConfig<T> = DEFAULT_CONFIG): Connectable<T> {\n // The subscription representing the connection.\n let connection: Subscription | null = null;\n const { connector, resetOnDisconnect = true } = config;\n let subject = connector();\n\n const result: any = new Observable<T>((subscriber) => {\n return subject.subscribe(subscriber);\n });\n\n // Define the `connect` function. This is what users must call\n // in order to \"connect\" the source to the subject that is\n // multicasting it.\n result.connect = () => {\n if (!connection || connection.closed) {\n connection = defer(() => source).subscribe(subject);\n if (resetOnDisconnect) {\n connection.add(() => (subject = connector()));\n }\n }\n return connection;\n };\n\n return result;\n}\n","import { Observable } from '../Observable';\nimport { ObservedValueOf, ObservableInputTuple, ObservableInput } from '../types';\nimport { argsArgArrayOrObject } from '../util/argsArgArrayOrObject';\nimport { innerFrom } from './innerFrom';\nimport { popResultSelector } from '../util/args';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { createObject } from '../util/createObject';\nimport { AnyCatcher } from '../AnyCatcher';\n\n// forkJoin(any)\n// We put this first because we need to catch cases where the user has supplied\n// _exactly `any`_ as the argument. Since `any` literally matches _anything_,\n// we don't want it to randomly hit one of the other type signatures below,\n// as we have no idea at build-time what type we should be returning when given an any.\n\n/**\n * You have passed `any` here, we can't figure out if it is\n * an array or an object, so you're getting `unknown`. Use better types.\n * @param arg Something typed as `any`\n */\nexport function forkJoin<T extends AnyCatcher>(arg: T): Observable<unknown>;\n\n// forkJoin(null | undefined)\nexport function forkJoin(scheduler: null | undefined): Observable<never>;\n\n// forkJoin([a, b, c])\nexport function forkJoin(sources: readonly []): Observable<never>;\nexport function forkJoin<A extends readonly unknown[]>(sources: readonly [...ObservableInputTuple<A>]): Observable<A>;\nexport function forkJoin<A extends readonly unknown[], R>(\n sources: readonly [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\n\n// forkJoin(a, b, c)\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function forkJoin<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\n/** @deprecated Pass an array of sources instead. The rest-parameters signature will be removed in v8. Details: https://rxjs.dev/deprecations/array-argument */\nexport function forkJoin<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n\n// forkJoin({a, b, c})\nexport function forkJoin(sourcesObject: { [K in any]: never }): Observable<never>;\nexport function forkJoin<T extends Record<string, ObservableInput<any>>>(\n sourcesObject: T\n): Observable<{ [K in keyof T]: ObservedValueOf<T[K]> }>;\n\n/**\n * Accepts an `Array` of {@link ObservableInput} or a dictionary `Object` of {@link ObservableInput} and returns\n * an {@link Observable} that emits either an array of values in the exact same order as the passed array,\n * or a dictionary of values in the same shape as the passed dictionary.\n *\n * <span class=\"informal\">Wait for Observables to complete and then combine last values they emitted;\n * complete immediately if an empty array is passed.</span>\n *\n * ![](forkJoin.png)\n *\n * `forkJoin` is an operator that takes any number of input observables which can be passed either as an array\n * or a dictionary of input observables. If no input observables are provided (e.g. an empty array is passed),\n * then the resulting stream will complete immediately.\n *\n * `forkJoin` will wait for all passed observables to emit and complete and then it will emit an array or an object with last\n * values from corresponding observables.\n *\n * If you pass an array of `n` observables to the operator, then the resulting\n * array will have `n` values, where the first value is the last one emitted by the first observable,\n * second value is the last one emitted by the second observable and so on.\n *\n * If you pass a dictionary of observables to the operator, then the resulting\n * objects will have the same keys as the dictionary passed, with their last values they have emitted\n * located at the corresponding key.\n *\n * That means `forkJoin` will not emit more than once and it will complete after that. If you need to emit combined\n * values not only at the end of the lifecycle of passed observables, but also throughout it, try out {@link combineLatest}\n * or {@link zip} instead.\n *\n * In order for the resulting array to have the same length as the number of input observables, whenever any of\n * the given observables completes without emitting any value, `forkJoin` will complete at that moment as well\n * and it will not emit anything either, even if it already has some last values from other observables.\n * Conversely, if there is an observable that never completes, `forkJoin` will never complete either,\n * unless at any point some other observable completes without emitting a value, which brings us back to\n * the previous case. Overall, in order for `forkJoin` to emit a value, all given observables\n * have to emit something at least once and complete.\n *\n * If any given observable errors at some point, `forkJoin` will error as well and immediately unsubscribe\n * from the other observables.\n *\n * Optionally `forkJoin` accepts a `resultSelector` function, that will be called with values which normally\n * would land in the emitted array. Whatever is returned by the `resultSelector`, will appear in the output\n * observable instead. This means that the default `resultSelector` can be thought of as a function that takes\n * all its arguments and puts them into an array. Note that the `resultSelector` will be called only\n * when `forkJoin` is supposed to emit a result.\n *\n * ## Examples\n *\n * Use `forkJoin` with a dictionary of observable inputs\n *\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin({\n * foo: of(1, 2, 3, 4),\n * bar: Promise.resolve(8),\n * baz: timer(4000)\n * });\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // { foo: 4, bar: 8, baz: 0 } after 4 seconds\n * // 'This is how it ends!' immediately after\n * ```\n *\n * Use `forkJoin` with an array of observable inputs\n *\n * ```ts\n * import { forkJoin, of, timer } from 'rxjs';\n *\n * const observable = forkJoin([\n * of(1, 2, 3, 4),\n * Promise.resolve(8),\n * timer(4000)\n * ]);\n * observable.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('This is how it ends!'),\n * });\n *\n * // Logs:\n * // [4, 8, 0] after 4 seconds\n * // 'This is how it ends!' immediately after\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n *\n * @param args Any number of `ObservableInput`s provided either as an array, as an object\n * or as arguments passed directly to the operator.\n * @return Observable emitting either an array of last values emitted by passed Observables\n * or value from project function.\n */\nexport function forkJoin(...args: any[]): Observable<any> {\n const resultSelector = popResultSelector(args);\n const { args: sources, keys } = argsArgArrayOrObject(args);\n const result = new Observable((subscriber) => {\n const { length } = sources;\n if (!length) {\n subscriber.complete();\n return;\n }\n const values = new Array(length);\n let remainingCompletions = length;\n let remainingEmissions = length;\n for (let sourceIndex = 0; sourceIndex < length; sourceIndex++) {\n let hasValue = false;\n innerFrom(sources[sourceIndex]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n if (!hasValue) {\n hasValue = true;\n remainingEmissions--;\n }\n values[sourceIndex] = value;\n },\n () => remainingCompletions--,\n undefined,\n () => {\n if (!remainingCompletions || !hasValue) {\n if (!remainingEmissions) {\n subscriber.next(keys ? createObject(keys, values) : values);\n }\n subscriber.complete();\n }\n }\n )\n );\n }\n });\n return resultSelector ? result.pipe(mapOneOrManyArgs(resultSelector)) : result;\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Observable } from '../Observable';\nimport { mergeMap } from '../operators/mergeMap';\nimport { isArrayLike } from '../util/isArrayLike';\nimport { isFunction } from '../util/isFunction';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\n\n// These constants are used to create handler registry functions using array mapping below.\nconst nodeEventEmitterMethods = ['addListener', 'removeListener'] as const;\nconst eventTargetMethods = ['addEventListener', 'removeEventListener'] as const;\nconst jqueryMethods = ['on', 'off'] as const;\n\nexport interface NodeStyleEventEmitter {\n addListener(eventName: string | symbol, handler: NodeEventHandler): this;\n removeListener(eventName: string | symbol, handler: NodeEventHandler): this;\n}\n\nexport type NodeEventHandler = (...args: any[]) => void;\n\n// For APIs that implement `addListener` and `removeListener` methods that may\n// not use the same arguments or return EventEmitter values\n// such as React Native\nexport interface NodeCompatibleEventEmitter {\n addListener(eventName: string, handler: NodeEventHandler): void | {};\n removeListener(eventName: string, handler: NodeEventHandler): void | {};\n}\n\n// Use handler types like those in @types/jquery. See:\n// https://github.com/DefinitelyTyped/DefinitelyTyped/blob/847731ba1d7fa6db6b911c0e43aa0afe596e7723/types/jquery/misc.d.ts#L6395\nexport interface JQueryStyleEventEmitter<TContext, T> {\n on(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;\n off(eventName: string, handler: (this: TContext, t: T, ...args: any[]) => any): void;\n}\n\nexport interface EventListenerObject<E> {\n handleEvent(evt: E): void;\n}\n\nexport interface HasEventTargetAddRemove<E> {\n addEventListener(\n type: string,\n listener: ((evt: E) => void) | EventListenerObject<E> | null,\n options?: boolean | AddEventListenerOptions\n ): void;\n removeEventListener(\n type: string,\n listener: ((evt: E) => void) | EventListenerObject<E> | null,\n options?: EventListenerOptions | boolean\n ): void;\n}\n\nexport interface EventListenerOptions {\n capture?: boolean;\n passive?: boolean;\n once?: boolean;\n}\n\nexport interface AddEventListenerOptions extends EventListenerOptions {\n once?: boolean;\n passive?: boolean;\n}\n\nexport function fromEvent<T>(target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>, eventName: string): Observable<T>;\nexport function fromEvent<T, R>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n resultSelector: (event: T) => R\n): Observable<R>;\nexport function fromEvent<T>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n options: EventListenerOptions\n): Observable<T>;\nexport function fromEvent<T, R>(\n target: HasEventTargetAddRemove<T> | ArrayLike<HasEventTargetAddRemove<T>>,\n eventName: string,\n options: EventListenerOptions,\n resultSelector: (event: T) => R\n): Observable<R>;\n\nexport function fromEvent(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<unknown>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function fromEvent<T>(target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>, eventName: string): Observable<T>;\nexport function fromEvent<R>(\n target: NodeStyleEventEmitter | ArrayLike<NodeStyleEventEmitter>,\n eventName: string,\n resultSelector: (...args: any[]) => R\n): Observable<R>;\n\nexport function fromEvent(\n target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,\n eventName: string\n): Observable<unknown>;\n/** @deprecated Do not specify explicit type parameters. Signatures with type parameters that cannot be inferred will be removed in v8. */\nexport function fromEvent<T>(target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>, eventName: string): Observable<T>;\nexport function fromEvent<R>(\n target: NodeCompatibleEventEmitter | ArrayLike<NodeCompatibleEventEmitter>,\n eventName: string,\n resultSelector: (...args: any[]) => R\n): Observable<R>;\n\nexport function fromEvent<T>(\n target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,\n eventName: string\n): Observable<T>;\nexport function fromEvent<T, R>(\n target: JQueryStyleEventEmitter<any, T> | ArrayLike<JQueryStyleEventEmitter<any, T>>,\n eventName: string,\n resultSelector: (value: T, ...args: any[]) => R\n): Observable<R>;\n\n/**\n * Creates an Observable that emits events of a specific type coming from the\n * given event target.\n *\n * <span class=\"informal\">Creates an Observable from DOM events, or Node.js\n * EventEmitter events or others.</span>\n *\n * ![](fromEvent.png)\n *\n * `fromEvent` accepts as a first argument event target, which is an object with methods\n * for registering event handler functions. As a second argument it takes string that indicates\n * type of event we want to listen for. `fromEvent` supports selected types of event targets,\n * which are described in detail below. If your event target does not match any of the ones listed,\n * you should use {@link fromEventPattern}, which can be used on arbitrary APIs.\n * When it comes to APIs supported by `fromEvent`, their methods for adding and removing event\n * handler functions have different names, but they all accept a string describing event type\n * and function itself, which will be called whenever said event happens.\n *\n * Every time resulting Observable is subscribed, event handler function will be registered\n * to event target on given event type. When that event fires, value\n * passed as a first argument to registered function will be emitted by output Observable.\n * When Observable is unsubscribed, function will be unregistered from event target.\n *\n * Note that if event target calls registered function with more than one argument, second\n * and following arguments will not appear in resulting stream. In order to get access to them,\n * you can pass to `fromEvent` optional project function, which will be called with all arguments\n * passed to event handler. Output Observable will then emit value returned by project function,\n * instead of the usual value.\n *\n * Remember that event targets listed below are checked via duck typing. It means that\n * no matter what kind of object you have and no matter what environment you work in,\n * you can safely use `fromEvent` on that object if it exposes described methods (provided\n * of course they behave as was described above). So for example if Node.js library exposes\n * event target which has the same method names as DOM EventTarget, `fromEvent` is still\n * a good choice.\n *\n * If the API you use is more callback then event handler oriented (subscribed\n * callback function fires only once and thus there is no need to manually\n * unregister it), you should use {@link bindCallback} or {@link bindNodeCallback}\n * instead.\n *\n * `fromEvent` supports following types of event targets:\n *\n * **DOM EventTarget**\n *\n * This is an object with `addEventListener` and `removeEventListener` methods.\n *\n * In the browser, `addEventListener` accepts - apart from event type string and event\n * handler function arguments - optional third parameter, which is either an object or boolean,\n * both used for additional configuration how and when passed function will be called. When\n * `fromEvent` is used with event target of that type, you can provide this values\n * as third parameter as well.\n *\n * **Node.js EventEmitter**\n *\n * An object with `addListener` and `removeListener` methods.\n *\n * **JQuery-style event target**\n *\n * An object with `on` and `off` methods\n *\n * **DOM NodeList**\n *\n * List of DOM Nodes, returned for example by `document.querySelectorAll` or `Node.childNodes`.\n *\n * Although this collection is not event target in itself, `fromEvent` will iterate over all Nodes\n * it contains and install event handler function in every of them. When returned Observable\n * is unsubscribed, function will be removed from all Nodes.\n *\n * **DOM HtmlCollection**\n *\n * Just as in case of NodeList it is a collection of DOM nodes. Here as well event handler function is\n * installed and removed in each of elements.\n *\n *\n * ## Examples\n *\n * Emit clicks happening on the DOM document\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * clicks.subscribe(x => console.log(x));\n *\n * // Results in:\n * // MouseEvent object logged to console every time a click\n * // occurs on the document.\n * ```\n *\n * Use `addEventListener` with capture option\n *\n * ```ts\n * import { fromEvent } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * // note optional configuration parameter which will be passed to addEventListener\n * const clicksInDocument = fromEvent(document, 'click', { capture: true });\n * const clicksInDiv = fromEvent(div, 'click');\n *\n * clicksInDocument.subscribe(() => console.log('document'));\n * clicksInDiv.subscribe(() => console.log('div'));\n *\n * // By default events bubble UP in DOM tree, so normally\n * // when we would click on div in document\n * // \"div\" would be logged first and then \"document\".\n * // Since we specified optional `capture` option, document\n * // will catch event when it goes DOWN DOM tree, so console\n * // will log \"document\" and then \"div\".\n * ```\n *\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n * @see {@link fromEventPattern}\n *\n * @param target The DOM EventTarget, Node.js EventEmitter, JQuery-like event target,\n * NodeList or HTMLCollection to attach the event handler to.\n * @param eventName The event name of interest, being emitted by the `target`.\n * @param options Options to pass through to the underlying `addListener`,\n * `addEventListener` or `on` functions.\n * @param resultSelector A mapping function used to transform events. It takes the\n * arguments from the event handler and should return a single value.\n * @return An Observable emitting events registered through `target`'s\n * listener handlers.\n */\nexport function fromEvent<T>(\n target: any,\n eventName: string,\n options?: EventListenerOptions | ((...args: any[]) => T),\n resultSelector?: (...args: any[]) => T\n): Observable<T> {\n if (isFunction(options)) {\n resultSelector = options;\n options = undefined;\n }\n if (resultSelector) {\n return fromEvent<T>(target, eventName, options as EventListenerOptions).pipe(mapOneOrManyArgs(resultSelector));\n }\n\n // Figure out our add and remove methods. In order to do this,\n // we are going to analyze the target in a preferred order, if\n // the target matches a given signature, we take the two \"add\" and \"remove\"\n // method names and apply them to a map to create opposite versions of the\n // same function. This is because they all operate in duplicate pairs,\n // `addListener(name, handler)`, `removeListener(name, handler)`, for example.\n // The call only differs by method name, as to whether or not you're adding or removing.\n const [add, remove] =\n // If it is an EventTarget, we need to use a slightly different method than the other two patterns.\n isEventTarget(target)\n ? eventTargetMethods.map((methodName) => (handler: any) => target[methodName](eventName, handler, options as EventListenerOptions))\n : // In all other cases, the call pattern is identical with the exception of the method names.\n isNodeStyleEventEmitter(target)\n ? nodeEventEmitterMethods.map(toCommonHandlerRegistry(target, eventName))\n : isJQueryStyleEventEmitter(target)\n ? jqueryMethods.map(toCommonHandlerRegistry(target, eventName))\n : [];\n\n // If add is falsy, it's because we didn't match a pattern above.\n // Check to see if it is an ArrayLike, because if it is, we want to\n // try to apply fromEvent to all of it's items. We do this check last,\n // because there are may be some types that are both ArrayLike *and* implement\n // event registry points, and we'd rather delegate to that when possible.\n if (!add) {\n if (isArrayLike(target)) {\n return mergeMap((subTarget: any) => fromEvent(subTarget, eventName, options as EventListenerOptions))(\n innerFrom(target)\n ) as Observable<T>;\n }\n }\n\n // If add is falsy and we made it here, it's because we didn't\n // match any valid target objects above.\n if (!add) {\n throw new TypeError('Invalid event target');\n }\n\n return new Observable<T>((subscriber) => {\n // The handler we are going to register. Forwards the event object, by itself, or\n // an array of arguments to the event handler, if there is more than one argument,\n // to the consumer.\n const handler = (...args: any[]) => subscriber.next(1 < args.length ? args : args[0]);\n // Do the work of adding the handler to the target.\n add(handler);\n // When we finalize, we want to remove the handler and free up memory.\n return () => remove!(handler);\n });\n}\n\n/**\n * Used to create `add` and `remove` functions to register and unregister event handlers\n * from a target in the most common handler pattern, where there are only two arguments.\n * (e.g. `on(name, fn)`, `off(name, fn)`, `addListener(name, fn)`, or `removeListener(name, fn)`)\n * @param target The target we're calling methods on\n * @param eventName The event name for the event we're creating register or unregister functions for\n */\nfunction toCommonHandlerRegistry(target: any, eventName: string) {\n return (methodName: string) => (handler: any) => target[methodName](eventName, handler);\n}\n\n/**\n * Checks to see if the target implements the required node-style EventEmitter methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isNodeStyleEventEmitter(target: any): target is NodeStyleEventEmitter {\n return isFunction(target.addListener) && isFunction(target.removeListener);\n}\n\n/**\n * Checks to see if the target implements the required jQuery-style EventEmitter methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isJQueryStyleEventEmitter(target: any): target is JQueryStyleEventEmitter<any, any> {\n return isFunction(target.on) && isFunction(target.off);\n}\n\n/**\n * Checks to see if the target implements the required EventTarget methods\n * for adding and removing event handlers.\n * @param target the object to check\n */\nfunction isEventTarget(target: any): target is HasEventTargetAddRemove<any> {\n return isFunction(target.addEventListener) && isFunction(target.removeEventListener);\n}\n","import { Observable } from '../Observable';\nimport { isFunction } from '../util/isFunction';\nimport { NodeEventHandler } from './fromEvent';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\n\n/* tslint:disable:max-line-length */\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void\n): Observable<T>;\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n resultSelector?: (...args: any[]) => T\n): Observable<T>;\n/* tslint:enable:max-line-length */\n\n/**\n * Creates an Observable from an arbitrary API for registering event handlers.\n *\n * <span class=\"informal\">When that method for adding event handler was something {@link fromEvent}\n * was not prepared for.</span>\n *\n * ![](fromEventPattern.png)\n *\n * `fromEventPattern` allows you to convert into an Observable any API that supports registering handler functions\n * for events. It is similar to {@link fromEvent}, but far\n * more flexible. In fact, all use cases of {@link fromEvent} could be easily handled by\n * `fromEventPattern` (although in slightly more verbose way).\n *\n * This operator accepts as a first argument an `addHandler` function, which will be injected with\n * handler parameter. That handler is actually an event handler function that you now can pass\n * to API expecting it. `addHandler` will be called whenever Observable\n * returned by the operator is subscribed, so registering handler in API will not\n * necessarily happen when `fromEventPattern` is called.\n *\n * After registration, every time an event that we listen to happens,\n * Observable returned by `fromEventPattern` will emit value that event handler\n * function was called with. Note that if event handler was called with more\n * than one argument, second and following arguments will not appear in the Observable.\n *\n * If API you are using allows to unregister event handlers as well, you can pass to `fromEventPattern`\n * another function - `removeHandler` - as a second parameter. It will be injected\n * with the same handler function as before, which now you can use to unregister\n * it from the API. `removeHandler` will be called when consumer of resulting Observable\n * unsubscribes from it.\n *\n * In some APIs unregistering is actually handled differently. Method registering an event handler\n * returns some kind of token, which is later used to identify which function should\n * be unregistered or it itself has method that unregisters event handler.\n * If that is the case with your API, make sure token returned\n * by registering method is returned by `addHandler`. Then it will be passed\n * as a second argument to `removeHandler`, where you will be able to use it.\n *\n * If you need access to all event handler parameters (not only the first one),\n * or you need to transform them in any way, you can call `fromEventPattern` with optional\n * third parameter - project function which will accept all arguments passed to\n * event handler when it is called. Whatever is returned from project function will appear on\n * resulting stream instead of usual event handlers first argument. This means\n * that default project can be thought of as function that takes its first parameter\n * and ignores the rest.\n *\n * ## Examples\n *\n * Emits clicks happening on the DOM document\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * function addClickHandler(handler) {\n * document.addEventListener('click', handler);\n * }\n *\n * function removeClickHandler(handler) {\n * document.removeEventListener('click', handler);\n * }\n *\n * const clicks = fromEventPattern(\n * addClickHandler,\n * removeClickHandler\n * );\n * clicks.subscribe(x => console.log(x));\n *\n * // Whenever you click anywhere in the browser, DOM MouseEvent\n * // object will be logged.\n * ```\n *\n * Use with API that returns cancellation token\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * const token = someAPI.registerEventHandler(function() {});\n * someAPI.unregisterEventHandler(token); // this APIs cancellation method accepts\n * // not handler itself, but special token.\n *\n * const someAPIObservable = fromEventPattern(\n * function(handler) { return someAPI.registerEventHandler(handler); }, // Note that we return the token here...\n * function(handler, token) { someAPI.unregisterEventHandler(token); } // ...to then use it here.\n * );\n * ```\n *\n * Use with project function\n *\n * ```ts\n * import { fromEventPattern } from 'rxjs';\n *\n * someAPI.registerEventHandler((eventType, eventMessage) => {\n * console.log(eventType, eventMessage); // Logs 'EVENT_TYPE' 'EVENT_MESSAGE' to console.\n * });\n *\n * const someAPIObservable = fromEventPattern(\n * handler => someAPI.registerEventHandler(handler),\n * handler => someAPI.unregisterEventHandler(handler)\n * (eventType, eventMessage) => eventType + ' --- ' + eventMessage // without that function only 'EVENT_TYPE'\n * ); // would be emitted by the Observable\n *\n * someAPIObservable.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'EVENT_TYPE --- EVENT_MESSAGE'\n * ```\n *\n * @see {@link fromEvent}\n * @see {@link bindCallback}\n * @see {@link bindNodeCallback}\n *\n * @param addHandler A function that takes a `handler` function as argument and attaches it\n * somehow to the actual source of events.\n * @param removeHandler A function that takes a `handler` function as an argument and removes\n * it from the event source. If `addHandler` returns some kind of token, `removeHandler` function\n * will have it as a second parameter.\n * @param resultSelector A function to transform results. It takes the arguments from the event\n * handler and should return a single value.\n * @return Observable which, when an event happens, emits first parameter passed to registered\n * event handler. Alternatively it emits whatever project function returns at that moment.\n */\nexport function fromEventPattern<T>(\n addHandler: (handler: NodeEventHandler) => any,\n removeHandler?: (handler: NodeEventHandler, signal?: any) => void,\n resultSelector?: (...args: any[]) => T\n): Observable<T | T[]> {\n if (resultSelector) {\n return fromEventPattern<T>(addHandler, removeHandler).pipe(mapOneOrManyArgs(resultSelector));\n }\n\n return new Observable<T | T[]>((subscriber) => {\n const handler = (...e: T[]) => subscriber.next(e.length === 1 ? e[0] : e);\n const retValue = addHandler(handler);\n return isFunction(removeHandler) ? () => removeHandler(handler, retValue) : undefined;\n });\n}\n","import { Observable } from '../Observable';\nimport { identity } from '../util/identity';\nimport { ObservableInput, SchedulerLike } from '../types';\nimport { isScheduler } from '../util/isScheduler';\nimport { defer } from './defer';\nimport { scheduleIterable } from '../scheduled/scheduleIterable';\n\ntype ConditionFunc<S> = (state: S) => boolean;\ntype IterateFunc<S> = (state: S) => S;\ntype ResultFunc<S, T> = (state: S) => T;\n\nexport interface GenerateBaseOptions<S> {\n /**\n * Initial state.\n */\n initialState: S;\n /**\n * Condition function that accepts state and returns boolean.\n * When it returns false, the generator stops.\n * If not specified, a generator never stops.\n */\n condition?: ConditionFunc<S>;\n /**\n * Iterate function that accepts state and returns new state.\n */\n iterate: IterateFunc<S>;\n /**\n * SchedulerLike to use for generation process.\n * By default, a generator starts immediately.\n */\n scheduler?: SchedulerLike;\n}\n\nexport interface GenerateOptions<T, S> extends GenerateBaseOptions<S> {\n /**\n * Result selection function that accepts state and returns a value to emit.\n */\n resultSelector: ResultFunc<S, T>;\n}\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n *\n * ![](generate.png)\n *\n * ## Examples\n *\n * Produces sequence of numbers\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1, x => x);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * ```\n *\n * Use `asapScheduler`\n *\n * ```ts\n * import { generate, asapScheduler } from 'rxjs';\n *\n * const result = generate(1, x => x < 5, x => x * 2, x => x + 1, asapScheduler);\n *\n * result.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 2\n * // 3\n * // 5\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param initialState Initial state.\n * @param condition Condition to terminate generation (upon returning false).\n * @param iterate Iteration step function.\n * @param resultSelector Selector function for results produced in the sequence.\n * @param scheduler A {@link SchedulerLike} on which to run the generator loop.\n * If not provided, defaults to emit immediately.\n * @returns The generated sequence.\n * @deprecated Instead of passing separate arguments, use the options argument.\n * Signatures taking separate arguments will be removed in v8.\n */\nexport function generate<T, S>(\n initialState: S,\n condition: ConditionFunc<S>,\n iterate: IterateFunc<S>,\n resultSelector: ResultFunc<S, T>,\n scheduler?: SchedulerLike\n): Observable<T>;\n\n/**\n * Generates an Observable by running a state-driven loop\n * that emits an element on each iteration.\n *\n * <span class=\"informal\">Use it instead of nexting values in a for loop.</span>\n *\n * ![](generate.png)\n *\n * `generate` allows you to create a stream of values generated with a loop very similar to\n * a traditional for loop. The first argument of `generate` is a beginning value. The second argument\n * is a function that accepts this value and tests if some condition still holds. If it does,\n * then the loop continues, if not, it stops. The third value is a function which takes the\n * previously defined value and modifies it in some way on each iteration. Note how these three parameters\n * are direct equivalents of three expressions in a traditional for loop: the first expression\n * initializes some state (for example, a numeric index), the second tests if the loop can perform the next\n * iteration (for example, if the index is lower than 10) and the third states how the defined value\n * will be modified on every step (for example, the index will be incremented by one).\n *\n * Return value of a `generate` operator is an Observable that on each loop iteration\n * emits a value. First of all, the condition function is ran. If it returns true, then the Observable\n * emits the currently stored value (initial value at the first iteration) and finally updates\n * that value with iterate function. If at some point the condition returns false, then the Observable\n * completes at that moment.\n *\n * Optionally you can pass a fourth parameter to `generate` - a result selector function which allows you\n * to immediately map the value that would normally be emitted by an Observable.\n *\n * If you find three anonymous functions in `generate` call hard to read, you can provide\n * a single object to the operator instead where the object has the properties: `initialState`,\n * `condition`, `iterate` and `resultSelector`, which should have respective values that you\n * would normally pass to `generate`. `resultSelector` is still optional, but that form\n * of calling `generate` allows you to omit `condition` as well. If you omit it, that means\n * condition always holds, or in other words the resulting Observable will never complete.\n *\n * Both forms of `generate` can optionally accept a scheduler. In case of a multi-parameter call,\n * scheduler simply comes as a last argument (no matter if there is a `resultSelector`\n * function or not). In case of a single-parameter call, you can provide it as a\n * `scheduler` property on the object passed to the operator. In both cases, a scheduler decides when\n * the next iteration of the loop will happen and therefore when the next value will be emitted\n * by the Observable. For example, to ensure that each value is pushed to the Observer\n * on a separate task in the event loop, you could use the `async` scheduler. Note that\n * by default (when no scheduler is passed) values are simply emitted synchronously.\n *\n *\n * ## Examples\n *\n * Use with condition and iterate functions\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1);\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * Use with condition, iterate and resultSelector functions\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate(0, x => x < 3, x => x + 1, x => x * 1000);\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 'Complete!'\n * ```\n *\n * Use with options object\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition(value) { return value < 3; },\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 'Complete!'\n * ```\n *\n * Use options object without condition function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * iterate(value) { return value + 1; },\n * resultSelector(value) { return value * 1000; }\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!') // This will never run\n * });\n *\n * // Logs:\n * // 0\n * // 1000\n * // 2000\n * // 3000\n * // ...and never stops.\n * ```\n *\n * @see {@link from}\n *\n * @param initialState Initial state.\n * @param condition Condition to terminate generation (upon returning false).\n * @param iterate Iteration step function.\n * @param scheduler A {@link Scheduler} on which to run the generator loop. If not\n * provided, defaults to emitting immediately.\n * @return The generated sequence.\n * @deprecated Instead of passing separate arguments, use the options argument.\n * Signatures taking separate arguments will be removed in v8.\n */\nexport function generate<S>(\n initialState: S,\n condition: ConditionFunc<S>,\n iterate: IterateFunc<S>,\n scheduler?: SchedulerLike\n): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition and scheduler.\n *\n * ![](generate.png)\n *\n * ## Examples\n *\n * Use options object with condition function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition: x => x < 3,\n * iterate: x => x + 1\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param options Object that must contain initialState, iterate and might contain condition and scheduler.\n * @returns The generated sequence.\n */\nexport function generate<S>(options: GenerateBaseOptions<S>): Observable<S>;\n\n/**\n * Generates an observable sequence by running a state-driven loop\n * producing the sequence's elements, using the specified scheduler\n * to send out observer messages.\n * The overload accepts options object that might contain initial state, iterate,\n * condition, result selector and scheduler.\n *\n * ![](generate.png)\n *\n * ## Examples\n *\n * Use options object with condition and iterate function\n *\n * ```ts\n * import { generate } from 'rxjs';\n *\n * const result = generate({\n * initialState: 0,\n * condition: x => x < 3,\n * iterate: x => x + 1,\n * resultSelector: x => x\n * });\n *\n * result.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 'Complete!'\n * ```\n *\n * @see {@link from}\n * @see {@link Observable}\n *\n * @param options Object that must contain initialState, iterate, resultSelector and might contain condition and scheduler.\n * @returns The generated sequence.\n */\nexport function generate<T, S>(options: GenerateOptions<T, S>): Observable<T>;\n\nexport function generate<T, S>(\n initialStateOrOptions: S | GenerateOptions<T, S>,\n condition?: ConditionFunc<S>,\n iterate?: IterateFunc<S>,\n resultSelectorOrScheduler?: ResultFunc<S, T> | SchedulerLike,\n scheduler?: SchedulerLike\n): Observable<T> {\n let resultSelector: ResultFunc<S, T>;\n let initialState: S;\n\n // TODO: Remove this as we move away from deprecated signatures\n // and move towards a configuration object argument.\n if (arguments.length === 1) {\n // If we only have one argument, we can assume it is a configuration object.\n // Note that folks not using TypeScript may trip over this.\n ({\n initialState,\n condition,\n iterate,\n resultSelector = identity as ResultFunc<S, T>,\n scheduler,\n } = initialStateOrOptions as GenerateOptions<T, S>);\n } else {\n // Deprecated arguments path. Figure out what the user\n // passed and set it here.\n initialState = initialStateOrOptions as S;\n if (!resultSelectorOrScheduler || isScheduler(resultSelectorOrScheduler)) {\n resultSelector = identity as ResultFunc<S, T>;\n scheduler = resultSelectorOrScheduler as SchedulerLike;\n } else {\n resultSelector = resultSelectorOrScheduler as ResultFunc<S, T>;\n }\n }\n\n // The actual generator used to \"generate\" values.\n function* gen() {\n for (let state = initialState; !condition || condition(state); state = iterate!(state)) {\n yield resultSelector(state);\n }\n }\n\n // We use `defer` because we want to defer the creation of the iterator from the iterable.\n return defer(\n (scheduler\n ? // If a scheduler was provided, use `scheduleIterable` to ensure that iteration/generation\n // happens on the scheduler.\n () => scheduleIterable(gen(), scheduler!)\n : // Otherwise, if there's no scheduler, we can just use the generator function directly in\n // `defer` and executing it will return the generator (which is iterable).\n gen) as () => ObservableInput<T>\n );\n}\n","import { Observable } from '../Observable';\nimport { defer } from './defer';\nimport { ObservableInput } from '../types';\n\n/**\n * Checks a boolean at subscription time, and chooses between one of two observable sources\n *\n * `iif` expects a function that returns a boolean (the `condition` function), and two sources,\n * the `trueResult` and the `falseResult`, and returns an Observable.\n *\n * At the moment of subscription, the `condition` function is called. If the result is `true`, the\n * subscription will be to the source passed as the `trueResult`, otherwise, the subscription will be\n * to the source passed as the `falseResult`.\n *\n * If you need to check more than two options to choose between more than one observable, have a look at the {@link defer} creation method.\n *\n * ## Examples\n *\n * Change at runtime which Observable will be subscribed\n *\n * ```ts\n * import { iif, of } from 'rxjs';\n *\n * let subscribeToFirst;\n * const firstOrSecond = iif(\n * () => subscribeToFirst,\n * of('first'),\n * of('second')\n * );\n *\n * subscribeToFirst = true;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'first'\n *\n * subscribeToFirst = false;\n * firstOrSecond.subscribe(value => console.log(value));\n *\n * // Logs:\n * // 'second'\n * ```\n *\n * Control access to an Observable\n *\n * ```ts\n * import { iif, of, EMPTY } from 'rxjs';\n *\n * let accessGranted;\n * const observableIfYouHaveAccess = iif(\n * () => accessGranted,\n * of('It seems you have an access...'),\n * EMPTY\n * );\n *\n * accessGranted = true;\n * observableIfYouHaveAccess.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('The end')\n * });\n *\n * // Logs:\n * // 'It seems you have an access...'\n * // 'The end'\n *\n * accessGranted = false;\n * observableIfYouHaveAccess.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('The end')\n * });\n *\n * // Logs:\n * // 'The end'\n * ```\n *\n * @see {@link defer}\n *\n * @param condition Condition which Observable should be chosen.\n * @param trueResult An Observable that will be subscribed if condition is true.\n * @param falseResult An Observable that will be subscribed if condition is false.\n * @return An observable that proxies to `trueResult` or `falseResult`, depending on the result of the `condition` function.\n */\nexport function iif<T, F>(condition: () => boolean, trueResult: ObservableInput<T>, falseResult: ObservableInput<F>): Observable<T | F> {\n return defer(() => (condition() ? trueResult : falseResult));\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { async as asyncScheduler } from '../scheduler/async';\nimport { isScheduler } from '../util/isScheduler';\nimport { isValidDate } from '../util/isDate';\n\n/**\n * Creates an observable that will wait for a specified time period, or exact date, before\n * emitting the number 0.\n *\n * <span class=\"informal\">Used to emit a notification after a delay.</span>\n *\n * This observable is useful for creating delays in code, or racing against other values\n * for ad-hoc timeouts.\n *\n * The `delay` is specified by default in milliseconds, however providing a custom scheduler could\n * create a different behavior.\n *\n * ## Examples\n *\n * Wait 3 seconds and start another observable\n *\n * You might want to use `timer` to delay subscription to an\n * observable by a set amount of time. Here we use a timer with\n * {@link concatMapTo} or {@link concatMap} in order to wait\n * a few seconds and start a subscription to a source.\n *\n * ```ts\n * import { of, timer, concatMap } from 'rxjs';\n *\n * // This could be any observable\n * const source = of(1, 2, 3);\n *\n * timer(3000)\n * .pipe(concatMap(() => source))\n * .subscribe(console.log);\n * ```\n *\n * Take all values until the start of the next minute\n *\n * Using a `Date` as the trigger for the first emission, you can\n * do things like wait until midnight to fire an event, or in this case,\n * wait until a new minute starts (chosen so the example wouldn't take\n * too long to run) in order to stop watching a stream. Leveraging\n * {@link takeUntil}.\n *\n * ```ts\n * import { interval, takeUntil, timer } from 'rxjs';\n *\n * // Build a Date object that marks the\n * // next minute.\n * const currentDate = new Date();\n * const startOfNextMinute = new Date(\n * currentDate.getFullYear(),\n * currentDate.getMonth(),\n * currentDate.getDate(),\n * currentDate.getHours(),\n * currentDate.getMinutes() + 1\n * );\n *\n * // This could be any observable stream\n * const source = interval(1000);\n *\n * const result = source.pipe(\n * takeUntil(timer(startOfNextMinute))\n * );\n *\n * result.subscribe(console.log);\n * ```\n *\n * ### Known Limitations\n *\n * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.\n *\n * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and\n * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission\n * should occur will be incorrect. In this case, it would be best to do your own calculations\n * ahead of time, and pass a `number` in as the `dueTime`.\n *\n * @param due If a `number`, the amount of time in milliseconds to wait before emitting.\n * If a `Date`, the exact time at which to emit.\n * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.\n */\nexport function timer(due: number | Date, scheduler?: SchedulerLike): Observable<0>;\n\n/**\n * Creates an observable that starts an interval after a specified delay, emitting incrementing numbers -- starting at `0` --\n * on each interval after words.\n *\n * The `delay` and `intervalDuration` are specified by default in milliseconds, however providing a custom scheduler could\n * create a different behavior.\n *\n * ## Example\n *\n * ### Start an interval that starts right away\n *\n * Since {@link interval} waits for the passed delay before starting,\n * sometimes that's not ideal. You may want to start an interval immediately.\n * `timer` works well for this. Here we have both side-by-side so you can\n * see them in comparison.\n *\n * Note that this observable will never complete.\n *\n * ```ts\n * import { timer, interval } from 'rxjs';\n *\n * timer(0, 1000).subscribe(n => console.log('timer', n));\n * interval(1000).subscribe(n => console.log('interval', n));\n * ```\n *\n * ### Known Limitations\n *\n * - The {@link asyncScheduler} uses `setTimeout` which has limitations for how far in the future it can be scheduled.\n *\n * - If a `scheduler` is provided that returns a timestamp other than an epoch from `now()`, and\n * a `Date` object is passed to the `dueTime` argument, the calculation for when the first emission\n * should occur will be incorrect. In this case, it would be best to do your own calculations\n * ahead of time, and pass a `number` in as the `startDue`.\n * @param startDue If a `number`, is the time to wait before starting the interval.\n * If a `Date`, is the exact time at which to start the interval.\n * @param intervalDuration The delay between each value emitted in the interval. Passing a\n * negative number here will result in immediate completion after the first value is emitted, as though\n * no `intervalDuration` was passed at all.\n * @param scheduler The scheduler to use to schedule the delay. Defaults to {@link asyncScheduler}.\n */\nexport function timer(startDue: number | Date, intervalDuration: number, scheduler?: SchedulerLike): Observable<number>;\n\n/**\n * @deprecated The signature allowing `undefined` to be passed for `intervalDuration` will be removed in v8. Use the `timer(dueTime, scheduler?)` signature instead.\n */\nexport function timer(dueTime: number | Date, unused: undefined, scheduler?: SchedulerLike): Observable<0>;\n\nexport function timer(\n dueTime: number | Date = 0,\n intervalOrScheduler?: number | SchedulerLike,\n scheduler: SchedulerLike = asyncScheduler\n): Observable<number> {\n // Since negative intervalDuration is treated as though no\n // interval was specified at all, we start with a negative number.\n let intervalDuration = -1;\n\n if (intervalOrScheduler != null) {\n // If we have a second argument, and it's a scheduler,\n // override the scheduler we had defaulted. Otherwise,\n // it must be an interval.\n if (isScheduler(intervalOrScheduler)) {\n scheduler = intervalOrScheduler;\n } else {\n // Note that this *could* be negative, in which case\n // it's like not passing an intervalDuration at all.\n intervalDuration = intervalOrScheduler;\n }\n }\n\n return new Observable((subscriber) => {\n // If a valid date is passed, calculate how long to wait before\n // executing the first value... otherwise, if it's a number just schedule\n // that many milliseconds (or scheduler-specified unit size) in the future.\n let due = isValidDate(dueTime) ? +dueTime - scheduler!.now() : dueTime;\n\n if (due < 0) {\n // Ensure we don't schedule in the future.\n due = 0;\n }\n\n // The incrementing value we emit.\n let n = 0;\n\n // Start the timer.\n return scheduler.schedule(function () {\n if (!subscriber.closed) {\n // Emit the next value and increment.\n subscriber.next(n++);\n\n if (0 <= intervalDuration) {\n // If we have a interval after the initial timer,\n // reschedule with the period.\n this.schedule(undefined, intervalDuration);\n } else {\n // We didn't have an interval. So just complete.\n subscriber.complete();\n }\n }\n }, due);\n });\n}\n","import { Observable } from '../Observable';\nimport { asyncScheduler } from '../scheduler/async';\nimport { SchedulerLike } from '../types';\nimport { timer } from './timer';\n\n/**\n * Creates an Observable that emits sequential numbers every specified\n * interval of time, on a specified {@link SchedulerLike}.\n *\n * <span class=\"informal\">Emits incremental numbers periodically in time.</span>\n *\n * ![](interval.png)\n *\n * `interval` returns an Observable that emits an infinite sequence of\n * ascending integers, with a constant interval of time of your choosing\n * between those emissions. The first emission is not sent immediately, but\n * only after the first period has passed. By default, this operator uses the\n * `async` {@link SchedulerLike} to provide a notion of time, but you may pass any\n * {@link SchedulerLike} to it.\n *\n * ## Example\n *\n * Emits ascending numbers, one every second (1000ms) up to the number 3\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const numbers = interval(1000);\n *\n * const takeFourNumbers = numbers.pipe(take(4));\n *\n * takeFourNumbers.subscribe(x => console.log('Next: ', x));\n *\n * // Logs:\n * // Next: 0\n * // Next: 1\n * // Next: 2\n * // Next: 3\n * ```\n *\n * @see {@link timer}\n * @see {@link delay}\n *\n * @param period The interval size in milliseconds (by default) or the time unit determined\n * by the scheduler's clock.\n * @param scheduler The {@link SchedulerLike} to use for scheduling the emission of values,\n * and providing a notion of \"time\".\n * @return An Observable that emits a sequential number each time interval.\n */\nexport function interval(period = 0, scheduler: SchedulerLike = asyncScheduler): Observable<number> {\n if (period < 0) {\n // We cannot schedule an interval in the past.\n period = 0;\n }\n\n return timer(period, period, scheduler);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, ObservableInputTuple, SchedulerLike } from '../types';\nimport { mergeAll } from '../operators/mergeAll';\nimport { innerFrom } from './innerFrom';\nimport { EMPTY } from './empty';\nimport { popNumber, popScheduler } from '../util/args';\nimport { from } from './from';\n\nexport function merge<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\nexport function merge<A extends readonly unknown[]>(...sourcesAndConcurrency: [...ObservableInputTuple<A>, number?]): Observable<A[number]>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function merge<A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike?]\n): Observable<A[number]>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `mergeAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function merge<A extends readonly unknown[]>(\n ...sourcesAndConcurrencyAndScheduler: [...ObservableInputTuple<A>, number?, SchedulerLike?]\n): Observable<A[number]>;\n\n/**\n * Creates an output Observable which concurrently emits all values from every\n * given input Observable.\n *\n * <span class=\"informal\">Flattens multiple Observables together by blending\n * their values into one Observable.</span>\n *\n * ![](merge.png)\n *\n * `merge` subscribes to each given input Observable (as arguments), and simply\n * forwards (without doing any transformation) all the values from all the input\n * Observables to the output Observable. The output Observable only completes\n * once all input Observables have completed. Any error delivered by an input\n * Observable will be immediately emitted on the output Observable.\n *\n * ## Examples\n *\n * Merge together two Observables: 1s interval and clicks\n *\n * ```ts\n * import { merge, fromEvent, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const clicksOrTimer = merge(clicks, timer);\n * clicksOrTimer.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // timer will emit ascending values, one every second(1000ms) to console\n * // clicks logs MouseEvents to console every time the \"document\" is clicked\n * // Since the two streams are merged you see these happening\n * // as they occur.\n * ```\n *\n * Merge together 3 Observables, but run only 2 concurrently\n *\n * ```ts\n * import { interval, take, merge } from 'rxjs';\n *\n * const timer1 = interval(1000).pipe(take(10));\n * const timer2 = interval(2000).pipe(take(6));\n * const timer3 = interval(500).pipe(take(10));\n *\n * const concurrent = 2; // the argument\n * const merged = merge(timer1, timer2, timer3, concurrent);\n * merged.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - First timer1 and timer2 will run concurrently\n * // - timer1 will emit a value every 1000ms for 10 iterations\n * // - timer2 will emit a value every 2000ms for 6 iterations\n * // - after timer1 hits its max iteration, timer2 will\n * // continue, and timer3 will start to run concurrently with timer2\n * // - when timer2 hits its max iteration it terminates, and\n * // timer3 will continue to emit a value every 500ms until it is complete\n * ```\n *\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeMapTo}\n * @see {@link mergeScan}\n *\n * @param args `ObservableInput`s to merge together. If the last parameter\n * is of type number, `merge` will use it to limit number of concurrently\n * subscribed `ObservableInput`s. If the last parameter is {@link SchedulerLike},\n * it will be used for scheduling the emission of values.\n * @return An Observable that emits items that are the result of every input Observable.\n */\nexport function merge(...args: (ObservableInput<unknown> | number | SchedulerLike)[]): Observable<unknown> {\n const scheduler = popScheduler(args);\n const concurrent = popNumber(args, Infinity);\n const sources = args as ObservableInput<unknown>[];\n return !sources.length\n ? // No source provided\n EMPTY\n : sources.length === 1\n ? // One source? Just return it.\n innerFrom(sources[0])\n : // Merge all sources\n mergeAll(concurrent)(from(sources, scheduler));\n}\n","import { Observable } from '../Observable';\nimport { noop } from '../util/noop';\n\n/**\n * An Observable that emits no items to the Observer and never completes.\n *\n * ![](never.png)\n *\n * A simple Observable that emits neither values nor errors nor the completion\n * notification. It can be used for testing purposes or for composing with other\n * Observables. Please note that by never emitting a complete notification, this\n * Observable keeps the subscription from being disposed automatically.\n * Subscriptions need to be manually disposed.\n *\n * ## Example\n *\n * Emit the number 7, then never emit anything else (not even complete)\n *\n * ```ts\n * import { NEVER, startWith } from 'rxjs';\n *\n * const info = () => console.log('Will not be called');\n *\n * const result = NEVER.pipe(startWith(7));\n * result.subscribe({\n * next: x => console.log(x),\n * error: info,\n * complete: info\n * });\n * ```\n *\n * @see {@link Observable}\n * @see {@link EMPTY}\n * @see {@link of}\n * @see {@link throwError}\n */\nexport const NEVER = new Observable<never>(noop);\n\n/**\n * @deprecated Replaced with the {@link NEVER} constant. Will be removed in v8.\n */\nexport function never() {\n return NEVER;\n}\n","const { isArray } = Array;\n\n/**\n * Used in operators and functions that accept either a list of arguments, or an array of arguments\n * as a single argument.\n */\nexport function argsOrArgArray<T>(args: (T | T[])[]): T[] {\n return args.length === 1 && isArray(args[0]) ? args[0] : (args as T[]);\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { OperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from './innerFrom';\n\nexport function onErrorResumeNext<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\nexport function onErrorResumeNext<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A[number]>;\n\n/**\n * When any of the provided Observable emits a complete or an error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables no matter what, even if it means swallowing errors.</span>\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` will subscribe to each observable source it is provided, in order.\n * If the source it's subscribed to emits an error or completes, it will move to the next source\n * without error.\n *\n * If `onErrorResumeNext` is provided no arguments, or a single, empty array, it will return {@link EMPTY}.\n *\n * `onErrorResumeNext` is basically {@link concat}, only it will continue, even if one of its\n * sources emits an error.\n *\n * Note that there is no way to handle any errors thrown by sources via the result of\n * `onErrorResumeNext`. If you want to handle errors thrown in any given source, you can\n * always use the {@link catchError} operator on them before passing them into `onErrorResumeNext`.\n *\n * ## Example\n *\n * Subscribe to the next Observable after map fails\n *\n * ```ts\n * import { onErrorResumeNext, of, map } from 'rxjs';\n *\n * onErrorResumeNext(\n * of(1, 2, 3, 0).pipe(\n * map(x => {\n * if (x === 0) {\n * throw Error();\n * }\n * return 10 / x;\n * })\n * ),\n * of(1, 2, 3)\n * )\n * .subscribe({\n * next: value => console.log(value),\n * error: err => console.log(err), // Will never be called.\n * complete: () => console.log('done')\n * });\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // 'done'\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param sources `ObservableInput`s passed either directly or as an array.\n * @return An Observable that concatenates all sources, one after the other,\n * ignoring all errors, such that any error causes it to move on to the next source.\n */\nexport function onErrorResumeNext<A extends readonly unknown[]>(\n ...sources: [[...ObservableInputTuple<A>]] | [...ObservableInputTuple<A>]\n): Observable<A[number]> {\n const nextSources: ObservableInputTuple<A> = argsOrArgArray(sources) as any;\n\n return new Observable((subscriber) => {\n let sourceIndex = 0;\n const subscribeNext = () => {\n if (sourceIndex < nextSources.length) {\n let nextSource: Observable<A[number]>;\n try {\n nextSource = innerFrom(nextSources[sourceIndex++]);\n } catch (err) {\n subscribeNext();\n return;\n }\n const innerSubscriber = new OperatorSubscriber(subscriber, undefined, noop, noop);\n nextSource.subscribe(innerSubscriber);\n innerSubscriber.add(subscribeNext);\n } else {\n subscriber.complete();\n }\n };\n subscribeNext();\n });\n}\n","import { Observable } from '../Observable';\nimport { SchedulerLike } from '../types';\nimport { from } from './from';\n\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<T>(arr: readonly T[], scheduler?: SchedulerLike): Observable<[string, T]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<O extends Record<string, unknown>>(obj: O, scheduler?: SchedulerLike): Observable<[keyof O, O[keyof O]]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs<T>(iterable: Iterable<T>, scheduler?: SchedulerLike): Observable<[string, T]>;\n/**\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs(\n n: number | bigint | boolean | ((...args: any[]) => any) | symbol,\n scheduler?: SchedulerLike\n): Observable<[never, never]>;\n\n/**\n * Convert an object into an Observable of `[key, value]` pairs.\n *\n * <span class=\"informal\">Turn entries of an object into a stream.</span>\n *\n * ![](pairs.png)\n *\n * `pairs` takes an arbitrary object and returns an Observable that emits arrays. Each\n * emitted array has exactly two elements - the first is a key from the object\n * and the second is a value corresponding to that key. Keys are extracted from\n * an object via `Object.keys` function, which means that they will be only\n * enumerable keys that are present on an object directly - not ones inherited\n * via prototype chain.\n *\n * By default, these arrays are emitted synchronously. To change that you can\n * pass a {@link SchedulerLike} as a second argument to `pairs`.\n *\n * ## Example\n *\n * Converts an object to an Observable\n *\n * ```ts\n * import { pairs } from 'rxjs';\n *\n * const obj = {\n * foo: 42,\n * bar: 56,\n * baz: 78\n * };\n *\n * pairs(obj).subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // ['foo', 42]\n * // ['bar', 56]\n * // ['baz', 78]\n * // 'Complete!'\n * ```\n *\n * ### Object.entries required\n *\n * In IE, you will need to polyfill `Object.entries` in order to use this.\n * [MDN has a polyfill here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries)\n *\n * @param obj The object to inspect and turn into an Observable sequence.\n * @param scheduler An optional IScheduler to schedule when resulting\n * Observable will emit values.\n * @returns An observable sequence of [key, value] pairs from the object.\n * @deprecated Use `from(Object.entries(obj))` instead. Will be removed in v8.\n */\nexport function pairs(obj: any, scheduler?: SchedulerLike) {\n return from(Object.entries(obj), scheduler as any);\n}\n","export function not<T>(pred: (value: T, index: number) => boolean, thisArg: any): (value: T, index: number) => boolean {\n return (value: T, index: number) => !pred.call(thisArg, value, index); \n}","import { OperatorFunction, MonoTypeOperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function filter<T, S extends T, A>(predicate: (this: A, value: T, index: number) => value is S, thisArg: A): OperatorFunction<T, S>;\nexport function filter<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;\nexport function filter<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function filter<T, A>(predicate: (this: A, value: T, index: number) => boolean, thisArg: A): MonoTypeOperatorFunction<T>;\nexport function filter<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Filter items emitted by the source Observable by only emitting those that\n * satisfy a specified predicate.\n *\n * <span class=\"informal\">Like\n * [Array.prototype.filter()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter),\n * it only emits a value from the source if it passes a criterion function.</span>\n *\n * ![](filter.png)\n *\n * Similar to the well-known `Array.prototype.filter` method, this operator\n * takes values from the source Observable, passes them through a `predicate`\n * function and only emits those values that yielded `true`.\n *\n * ## Example\n *\n * Emit only click events whose target was a DIV element\n *\n * ```ts\n * import { fromEvent, filter } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksOnDivs = clicks.pipe(filter(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * clicksOnDivs.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n * @see {@link ignoreElements}\n * @see {@link partition}\n * @see {@link skip}\n *\n * @param predicate A function that\n * evaluates each value emitted by the source Observable. If it returns `true`,\n * the value is emitted, if `false` the value is not passed to the output\n * Observable. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number\n * `0`.\n * @param thisArg An optional argument to determine the value of `this`\n * in the `predicate` function.\n * @return A function that returns an Observable that emits items from the\n * source Observable that satisfy the specified `predicate`.\n */\nexport function filter<T>(predicate: (value: T, index: number) => boolean, thisArg?: any): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n // An index passed to our predicate function on each call.\n let index = 0;\n\n // Subscribe to the source, all errors and completions are\n // forwarded to the consumer.\n source.subscribe(\n // Call the predicate with the appropriate `this` context,\n // if the predicate returns `true`, then send the value\n // to the consumer.\n createOperatorSubscriber(subscriber, (value) => predicate.call(thisArg, value, index++) && subscriber.next(value))\n );\n });\n}\n","import { not } from '../util/not';\nimport { filter } from '../operators/filter';\nimport { ObservableInput } from '../types';\nimport { Observable } from '../Observable';\nimport { innerFrom } from './innerFrom';\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function partition<T, U extends T, A>(\n source: ObservableInput<T>,\n predicate: (this: A, value: T, index: number) => value is U,\n thisArg: A\n): [Observable<U>, Observable<Exclude<T, U>>];\nexport function partition<T, U extends T>(\n source: ObservableInput<T>,\n predicate: (value: T, index: number) => value is U\n): [Observable<U>, Observable<Exclude<T, U>>];\n\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function partition<T, A>(\n source: ObservableInput<T>,\n predicate: (this: A, value: T, index: number) => boolean,\n thisArg: A\n): [Observable<T>, Observable<T>];\nexport function partition<T>(source: ObservableInput<T>, predicate: (value: T, index: number) => boolean): [Observable<T>, Observable<T>];\n\n/**\n * Splits the source Observable into two, one with values that satisfy a\n * predicate, and another with values that don't satisfy the predicate.\n *\n * <span class=\"informal\">It's like {@link filter}, but returns two Observables:\n * one like the output of {@link filter}, and the other with values that did not\n * pass the condition.</span>\n *\n * ![](partition.png)\n *\n * `partition` outputs an array with two Observables that partition the values\n * from the source Observable through the given `predicate` function. The first\n * Observable in that array emits source values for which the predicate argument\n * returns true. The second Observable emits source values for which the\n * predicate returns false. The first behaves like {@link filter} and the second\n * behaves like {@link filter} with the predicate negated.\n *\n * ## Example\n *\n * Partition a set of numbers into odds and evens observables\n *\n * ```ts\n * import { of, partition } from 'rxjs';\n *\n * const observableValues = of(1, 2, 3, 4, 5, 6);\n * const [evens$, odds$] = partition(observableValues, value => value % 2 === 0);\n *\n * odds$.subscribe(x => console.log('odds', x));\n * evens$.subscribe(x => console.log('evens', x));\n *\n * // Logs:\n * // odds 1\n * // odds 3\n * // odds 5\n * // evens 2\n * // evens 4\n * // evens 6\n * ```\n *\n * @see {@link filter}\n *\n * @param source The source `ObservableInput` that will be split into a tuple of\n * two Observable elements.\n * @param predicate A function that evaluates each value emitted by the source\n * Observable. If it returns `true`, the value is emitted on the first Observable\n * in the returned array, if `false` the value is emitted on the second Observable\n * in the array. The `index` parameter is the number `i` for the i-th source\n * emission that has happened since the subscription, starting from the number `0`.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return An array with two Observables: one with values that passed the\n * predicate, and another with values that did not pass the predicate.\n */\nexport function partition<T>(\n source: ObservableInput<T>,\n predicate: (this: any, value: T, index: number) => boolean,\n thisArg?: any\n): [Observable<T>, Observable<T>] {\n return [filter(predicate, thisArg)(innerFrom(source)), filter(not(predicate, thisArg))(innerFrom(source))] as [\n Observable<T>,\n Observable<T>\n ];\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from './innerFrom';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, ObservableInputTuple } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { Subscriber } from '../Subscriber';\n\nexport function race<T extends readonly unknown[]>(inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\nexport function race<T extends readonly unknown[]>(...inputs: [...ObservableInputTuple<T>]): Observable<T[number]>;\n\n/**\n * Returns an observable that mirrors the first source observable to emit an item.\n *\n * ![](race.png)\n *\n * `race` returns an observable, that when subscribed to, subscribes to all source observables immediately.\n * As soon as one of the source observables emits a value, the result unsubscribes from the other sources.\n * The resulting observable will forward all notifications, including error and completion, from the \"winning\"\n * source observable.\n *\n * If one of the used source observable throws an errors before a first notification\n * the race operator will also throw an error, no matter if another source observable\n * could potentially win the race.\n *\n * `race` can be useful for selecting the response from the fastest network connection for\n * HTTP or WebSockets. `race` can also be useful for switching observable context based on user\n * input.\n *\n * ## Example\n *\n * Subscribes to the observable that was the first to start emitting.\n *\n * ```ts\n * import { interval, map, race } from 'rxjs';\n *\n * const obs1 = interval(7000).pipe(map(() => 'slow one'));\n * const obs2 = interval(3000).pipe(map(() => 'fast one'));\n * const obs3 = interval(5000).pipe(map(() => 'medium one'));\n *\n * race(obs1, obs2, obs3)\n * .subscribe(winner => console.log(winner));\n *\n * // Outputs\n * // a series of 'fast one'\n * ```\n *\n * @param sources Used to race for which `ObservableInput` emits first.\n * @return An Observable that mirrors the output of the first Observable to emit an item.\n */\nexport function race<T>(...sources: (ObservableInput<T> | ObservableInput<T>[])[]): Observable<any> {\n sources = argsOrArgArray(sources);\n // If only one source was passed, just return it. Otherwise return the race.\n return sources.length === 1 ? innerFrom(sources[0] as ObservableInput<T>) : new Observable<T>(raceInit(sources as ObservableInput<T>[]));\n}\n\n/**\n * An observable initializer function for both the static version and the\n * operator version of race.\n * @param sources The sources to race\n */\nexport function raceInit<T>(sources: ObservableInput<T>[]) {\n return (subscriber: Subscriber<T>) => {\n let subscriptions: Subscription[] = [];\n\n // Subscribe to all of the sources. Note that we are checking `subscriptions` here\n // Is is an array of all actively \"racing\" subscriptions, and it is `null` after the\n // race has been won. So, if we have racer that synchronously \"wins\", this loop will\n // stop before it subscribes to any more.\n for (let i = 0; subscriptions && !subscriber.closed && i < sources.length; i++) {\n subscriptions.push(\n innerFrom(sources[i] as ObservableInput<T>).subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n if (subscriptions) {\n // We're still racing, but we won! So unsubscribe\n // all other subscriptions that we have, except this one.\n for (let s = 0; s < subscriptions.length; s++) {\n s !== i && subscriptions[s].unsubscribe();\n }\n subscriptions = null!;\n }\n subscriber.next(value);\n })\n )\n );\n }\n };\n}\n","import { SchedulerLike } from '../types';\nimport { Observable } from '../Observable';\nimport { EMPTY } from './empty';\n\nexport function range(start: number, count?: number): Observable<number>;\n\n/**\n * @deprecated The `scheduler` parameter will be removed in v8. Use `range(start, count).pipe(observeOn(scheduler))` instead. Details: Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function range(start: number, count: number | undefined, scheduler: SchedulerLike): Observable<number>;\n\n/**\n * Creates an Observable that emits a sequence of numbers within a specified\n * range.\n *\n * <span class=\"informal\">Emits a sequence of numbers in a range.</span>\n *\n * ![](range.png)\n *\n * `range` operator emits a range of sequential integers, in order, where you\n * select the `start` of the range and its `length`. By default, uses no\n * {@link SchedulerLike} and just delivers the notifications synchronously, but may use\n * an optional {@link SchedulerLike} to regulate those deliveries.\n *\n * ## Example\n *\n * Produce a range of numbers\n *\n * ```ts\n * import { range } from 'rxjs';\n *\n * const numbers = range(1, 3);\n *\n * numbers.subscribe({\n * next: value => console.log(value),\n * complete: () => console.log('Complete!')\n * });\n *\n * // Logs:\n * // 1\n * // 2\n * // 3\n * // 'Complete!'\n * ```\n *\n * @see {@link timer}\n * @see {@link interval}\n *\n * @param start The value of the first integer in the sequence.\n * @param count The number of sequential integers to generate.\n * @param scheduler A {@link SchedulerLike} to use for scheduling the emissions\n * of the notifications.\n * @return An Observable of numbers that emits a finite range of sequential integers.\n */\nexport function range(start: number, count?: number, scheduler?: SchedulerLike): Observable<number> {\n if (count == null) {\n // If one argument was passed, it's the count, not the start.\n count = start;\n start = 0;\n }\n\n if (count <= 0) {\n // No count? We're going nowhere. Return EMPTY.\n return EMPTY;\n }\n\n // Where the range should stop.\n const end = count + start;\n\n return new Observable(\n scheduler\n ? // The deprecated scheduled path.\n (subscriber) => {\n let n = start;\n return scheduler.schedule(function () {\n if (n < end) {\n subscriber.next(n++);\n this.schedule();\n } else {\n subscriber.complete();\n }\n });\n }\n : // Standard synchronous range.\n (subscriber) => {\n let n = start;\n while (n < end && !subscriber.closed) {\n subscriber.next(n++);\n }\n subscriber.complete();\n }\n );\n}\n","import { Observable } from '../Observable';\nimport { Unsubscribable, ObservableInput, ObservedValueOf } from '../types';\nimport { innerFrom } from './innerFrom';\nimport { EMPTY } from './empty';\n\n/**\n * Creates an Observable that uses a resource which will be disposed at the same time as the Observable.\n *\n * <span class=\"informal\">Use it when you catch yourself cleaning up after an Observable.</span>\n *\n * `using` is a factory operator, which accepts two functions. First function returns a disposable resource.\n * It can be an arbitrary object that implements `unsubscribe` method. Second function will be injected with\n * that object and should return an Observable. That Observable can use resource object during its execution.\n * Both functions passed to `using` will be called every time someone subscribes - neither an Observable nor\n * resource object will be shared in any way between subscriptions.\n *\n * When Observable returned by `using` is subscribed, Observable returned from the second function will be subscribed\n * as well. All its notifications (nexted values, completion and error events) will be emitted unchanged by the output\n * Observable. If however someone unsubscribes from the Observable or source Observable completes or errors by itself,\n * the `unsubscribe` method on resource object will be called. This can be used to do any necessary clean up, which\n * otherwise would have to be handled by hand. Note that complete or error notifications are not emitted when someone\n * cancels subscription to an Observable via `unsubscribe`, so `using` can be used as a hook, allowing you to make\n * sure that all resources which need to exist during an Observable execution will be disposed at appropriate time.\n *\n * @see {@link defer}\n *\n * @param resourceFactory A function which creates any resource object that implements `unsubscribe` method.\n * @param observableFactory A function which creates an Observable, that can use injected resource object.\n * @return An Observable that behaves the same as Observable returned by `observableFactory`, but\n * which - when completed, errored or unsubscribed - will also call `unsubscribe` on created resource object.\n */\nexport function using<T extends ObservableInput<any>>(\n resourceFactory: () => Unsubscribable | void,\n observableFactory: (resource: Unsubscribable | void) => T | void\n): Observable<ObservedValueOf<T>> {\n return new Observable<ObservedValueOf<T>>((subscriber) => {\n const resource = resourceFactory();\n const result = observableFactory(resource);\n const source = result ? innerFrom(result) : EMPTY;\n source.subscribe(subscriber);\n return () => {\n // NOTE: Optional chaining did not work here.\n // Related TS Issue: https://github.com/microsoft/TypeScript/issues/40818\n if (resource) {\n resource.unsubscribe();\n }\n };\n });\n}\n","import { Observable } from '../Observable';\nimport { ObservableInputTuple } from '../types';\nimport { innerFrom } from './innerFrom';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { EMPTY } from './empty';\nimport { createOperatorSubscriber } from '../operators/OperatorSubscriber';\nimport { popResultSelector } from '../util/args';\n\nexport function zip<A extends readonly unknown[]>(sources: [...ObservableInputTuple<A>]): Observable<A>;\nexport function zip<A extends readonly unknown[], R>(\n sources: [...ObservableInputTuple<A>],\n resultSelector: (...values: A) => R\n): Observable<R>;\nexport function zip<A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): Observable<A>;\nexport function zip<A extends readonly unknown[], R>(\n ...sourcesAndResultSelector: [...ObservableInputTuple<A>, (...values: A) => R]\n): Observable<R>;\n\n/**\n * Combines multiple Observables to create an Observable whose values are calculated from the values, in order, of each\n * of its input Observables.\n *\n * If the last parameter is a function, this function is used to compute the created value from the input values.\n * Otherwise, an array of the input values is returned.\n *\n * ## Example\n *\n * Combine age and name from different sources\n *\n * ```ts\n * import { of, zip, map } from 'rxjs';\n *\n * const age$ = of(27, 25, 29);\n * const name$ = of('Foo', 'Bar', 'Beer');\n * const isDev$ = of(true, true, false);\n *\n * zip(age$, name$, isDev$).pipe(\n * map(([age, name, isDev]) => ({ age, name, isDev }))\n * )\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // { age: 27, name: 'Foo', isDev: true }\n * // { age: 25, name: 'Bar', isDev: true }\n * // { age: 29, name: 'Beer', isDev: false }\n * ```\n *\n * @param args Any number of `ObservableInput`s provided either as an array or as an object\n * to combine with each other.\n * @return An Observable of array values of the values emitted at the same index from each\n * individual `ObservableInput`.\n */\nexport function zip(...args: unknown[]): Observable<unknown> {\n const resultSelector = popResultSelector(args);\n\n const sources = argsOrArgArray(args) as Observable<unknown>[];\n\n return sources.length\n ? new Observable<unknown[]>((subscriber) => {\n // A collection of buffers of values from each source.\n // Keyed by the same index with which the sources were passed in.\n let buffers: unknown[][] = sources.map(() => []);\n\n // An array of flags of whether or not the sources have completed.\n // This is used to check to see if we should complete the result.\n // Keyed by the same index with which the sources were passed in.\n let completed = sources.map(() => false);\n\n // When everything is done, release the arrays above.\n subscriber.add(() => {\n buffers = completed = null!;\n });\n\n // Loop over our sources and subscribe to each one. The index `i` is\n // especially important here, because we use it in closures below to\n // access the related buffers and completion properties\n for (let sourceIndex = 0; !subscriber.closed && sourceIndex < sources.length; sourceIndex++) {\n innerFrom(sources[sourceIndex]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n buffers[sourceIndex].push(value);\n // if every buffer has at least one value in it, then we\n // can shift out the oldest value from each buffer and emit\n // them as an array.\n if (buffers.every((buffer) => buffer.length)) {\n const result: any = buffers.map((buffer) => buffer.shift()!);\n // Emit the array. If theres' a result selector, use that.\n subscriber.next(resultSelector ? resultSelector(...result) : result);\n // If any one of the sources is both complete and has an empty buffer\n // then we complete the result. This is because we cannot possibly have\n // any more values to zip together.\n if (buffers.some((buffer, i) => !buffer.length && completed[i])) {\n subscriber.complete();\n }\n }\n },\n () => {\n // This source completed. Mark it as complete so we can check it later\n // if we have to.\n completed[sourceIndex] = true;\n // But, if this complete source has nothing in its buffer, then we\n // can complete the result, because we can't possibly have any more\n // values from this to zip together with the other values.\n !buffers[sourceIndex].length && subscriber.complete();\n }\n )\n );\n }\n\n // When everything is done, release the arrays above.\n return () => {\n buffers = completed = null!;\n };\n })\n : EMPTY;\n}\n","\"use strict\";\nObject.defineProperty(exports, \"__esModule\", { value: true });\n//# sourceMappingURL=types.js.map","import { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\n\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Ignores source values for a duration determined by another Observable, then\n * emits the most recent value from the source Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link auditTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * ![](audit.svg)\n *\n * `audit` is similar to `throttle`, but emits the last value from the silenced\n * time window, instead of the first value. `audit` emits the most recent value\n * from the source Observable on the output Observable as soon as its internal\n * timer becomes disabled, and ignores source values while the timer is enabled.\n * Initially, the timer is disabled. As soon as the first source value arrives,\n * the timer is enabled by calling the `durationSelector` function with the\n * source value, which returns the \"duration\" Observable. When the duration\n * Observable emits a value, the timer is disabled, then the most\n * recent source value is emitted on the output Observable, and this process\n * repeats for the next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, audit, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(audit(ev => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttle}\n *\n * @param durationSelector A function\n * that receives a value from the source Observable, for computing the silencing\n * duration, returned as an Observable or a Promise.\n * @return A function that returns an Observable that performs rate-limiting of\n * emissions from the source Observable.\n */\nexport function audit<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n let durationSubscriber: Subscriber<any> | null = null;\n let isComplete = false;\n\n const endDuration = () => {\n durationSubscriber?.unsubscribe();\n durationSubscriber = null;\n if (hasValue) {\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n isComplete && subscriber.complete();\n };\n\n const cleanupDuration = () => {\n durationSubscriber = null;\n isComplete && subscriber.complete();\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n lastValue = value;\n if (!durationSubscriber) {\n innerFrom(durationSelector(value)).subscribe(\n (durationSubscriber = createOperatorSubscriber(subscriber, endDuration, cleanupDuration))\n );\n }\n },\n () => {\n isComplete = true;\n (!hasValue || !durationSubscriber || durationSubscriber.closed) && subscriber.complete();\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { audit } from './audit';\nimport { timer } from '../observable/timer';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\n\n/**\n * Ignores source values for `duration` milliseconds, then emits the most recent\n * value from the source Observable, then repeats this process.\n *\n * <span class=\"informal\">When it sees a source value, it ignores that plus\n * the next ones for `duration` milliseconds, and then it emits the most recent\n * value from the source.</span>\n *\n * ![](auditTime.png)\n *\n * `auditTime` is similar to `throttleTime`, but emits the last value from the\n * silenced time window, instead of the first value. `auditTime` emits the most\n * recent value from the source Observable on the output Observable as soon as\n * its internal timer becomes disabled, and ignores source values while the\n * timer is enabled. Initially, the timer is disabled. As soon as the first\n * source value arrives, the timer is enabled. After `duration` milliseconds (or\n * the time unit determined internally by the optional `scheduler`) has passed,\n * the timer is disabled, then the most recent source value is emitted on the\n * output Observable, and this process repeats for the next source value.\n * Optionally takes a {@link SchedulerLike} for managing timers.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, auditTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(auditTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttleTime}\n *\n * @param duration Time to wait before emitting the most recent source value,\n * measured in milliseconds or the time unit determined internally by the\n * optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the rate-limiting behavior.\n * @return A function that returns an Observable that performs rate-limiting of\n * emissions from the source Observable.\n */\nexport function auditTime<T>(duration: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return audit(() => timer(duration, scheduler));\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Buffers the source Observable values until `closingNotifier` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when another Observable emits.</span>\n *\n * ![](buffer.png)\n *\n * Buffers the incoming Observable values until the given `closingNotifier`\n * `ObservableInput` (that internally gets converted to an Observable)\n * emits a value, at which point it emits the buffer on the output\n * Observable and starts a new buffer internally, awaiting the next time\n * `closingNotifier` emits.\n *\n * ## Example\n *\n * On every click, emit array of most recent interval events\n *\n * ```ts\n * import { fromEvent, interval, buffer } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const intervalEvents = interval(1000);\n * const buffered = intervalEvents.pipe(buffer(clicks));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link window}\n *\n * @param closingNotifier An `ObservableInput` that signals the\n * buffer to be emitted on the output Observable.\n * @return A function that returns an Observable of buffers, which are arrays\n * of values.\n */\nexport function buffer<T>(closingNotifier: ObservableInput<any>): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n // The current buffered values.\n let currentBuffer: T[] = [];\n\n // Subscribe to our source.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => currentBuffer.push(value),\n () => {\n subscriber.next(currentBuffer);\n subscriber.complete();\n }\n )\n );\n\n // Subscribe to the closing notifier.\n innerFrom(closingNotifier).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n // Start a new buffer and emit the previous one.\n const b = currentBuffer;\n currentBuffer = [];\n subscriber.next(b);\n },\n noop\n )\n );\n\n return () => {\n // Ensure buffered values are released on finalization.\n currentBuffer = null!;\n };\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Buffers the source Observable values until the size hits the maximum\n * `bufferSize` given.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * that array only when its size reaches `bufferSize`.</span>\n *\n * ![](bufferCount.png)\n *\n * Buffers a number of values from the source Observable by `bufferSize` then\n * emits the buffer and clears it, and starts a new buffer each\n * `startBufferEvery` values. If `startBufferEvery` is not provided or is\n * `null`, then new buffers are started immediately at the start of the source\n * and when each buffer closes and is emitted.\n *\n * ## Examples\n *\n * Emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent, bufferCount } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * On every click, emit the last two click events as an array\n *\n * ```ts\n * import { fromEvent, bufferCount } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferCount(2, 1));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link pairwise}\n * @see {@link windowCount}\n *\n * @param bufferSize The maximum size of the buffer emitted.\n * @param startBufferEvery Interval at which to start a new buffer.\n * For example if `startBufferEvery` is `2`, then a new buffer will be started\n * on every other value from the source. A new buffer is started at the\n * beginning of the source by default.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferCount<T>(bufferSize: number, startBufferEvery: number | null = null): OperatorFunction<T, T[]> {\n // If no `startBufferEvery` value was supplied, then we're\n // opening and closing on the bufferSize itself.\n startBufferEvery = startBufferEvery ?? bufferSize;\n\n return operate((source, subscriber) => {\n let buffers: T[][] = [];\n let count = 0;\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n let toEmit: T[][] | null = null;\n\n // Check to see if we need to start a buffer.\n // This will start one at the first value, and then\n // a new one every N after that.\n if (count++ % startBufferEvery! === 0) {\n buffers.push([]);\n }\n\n // Push our value into our active buffers.\n for (const buffer of buffers) {\n buffer.push(value);\n // Check to see if we're over the bufferSize\n // if we are, record it so we can emit it later.\n // If we emitted it now and removed it, it would\n // mutate the `buffers` array while we're looping\n // over it.\n if (bufferSize <= buffer.length) {\n toEmit = toEmit ?? [];\n toEmit.push(buffer);\n }\n }\n\n if (toEmit) {\n // We have found some buffers that are over the\n // `bufferSize`. Emit them, and remove them from our\n // buffers list.\n for (const buffer of toEmit) {\n arrRemove(buffers, buffer);\n subscriber.next(buffer);\n }\n }\n },\n () => {\n // When the source completes, emit all of our\n // active buffers.\n for (const buffer of buffers) {\n subscriber.next(buffer);\n }\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n () => {\n // Clean up our memory when we finalize\n buffers = null!;\n }\n )\n );\n });\n}\n","import { Subscription } from '../Subscription';\nimport { OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\nimport { asyncScheduler } from '../scheduler/async';\nimport { popScheduler } from '../util/args';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function bufferTime<T>(bufferTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(\n bufferTimeSpan: number,\n bufferCreationInterval: number | null | undefined,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T[]>;\nexport function bufferTime<T>(\n bufferTimeSpan: number,\n bufferCreationInterval: number | null | undefined,\n maxBufferSize: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T[]>;\n\n/**\n * Buffers the source Observable values for a specific time period.\n *\n * <span class=\"informal\">Collects values from the past as an array, and emits\n * those arrays periodically in time.</span>\n *\n * ![](bufferTime.png)\n *\n * Buffers values from the source for a specific time duration `bufferTimeSpan`.\n * Unless the optional argument `bufferCreationInterval` is given, it emits and\n * resets the buffer every `bufferTimeSpan` milliseconds. If\n * `bufferCreationInterval` is given, this operator opens the buffer every\n * `bufferCreationInterval` milliseconds and closes (emits and resets) the\n * buffer every `bufferTimeSpan` milliseconds. When the optional argument\n * `maxBufferSize` is specified, the buffer will be closed either after\n * `bufferTimeSpan` milliseconds or when it contains `maxBufferSize` elements.\n *\n * ## Examples\n *\n * Every second, emit an array of the recent click events\n *\n * ```ts\n * import { fromEvent, bufferTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(1000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds, emit the click events from the next 2 seconds\n *\n * ```ts\n * import { fromEvent, bufferTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(bufferTime(2000, 5000));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferToggle}\n * @see {@link bufferWhen}\n * @see {@link windowTime}\n *\n * @param bufferTimeSpan The amount of time to fill each buffer array.\n * @param otherArgs Other configuration arguments such as:\n * - `bufferCreationInterval` - the interval at which to start new buffers;\n * - `maxBufferSize` - the maximum buffer size;\n * - `scheduler` - the scheduler on which to schedule the intervals that determine buffer boundaries.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferTime<T>(bufferTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, T[]> {\n const scheduler = popScheduler(otherArgs) ?? asyncScheduler;\n const bufferCreationInterval = (otherArgs[0] as number) ?? null;\n const maxBufferSize = (otherArgs[1] as number) || Infinity;\n\n return operate((source, subscriber) => {\n // The active buffers, their related subscriptions, and removal functions.\n let bufferRecords: { buffer: T[]; subs: Subscription }[] | null = [];\n // If true, it means that every time we emit a buffer, we want to start a new buffer\n // this is only really used for when *just* the buffer time span is passed.\n let restartOnEmit = false;\n\n /**\n * Does the work of emitting the buffer from the record, ensuring that the\n * record is removed before the emission so reentrant code (from some custom scheduling, perhaps)\n * does not alter the buffer. Also checks to see if a new buffer needs to be started\n * after the emit.\n */\n const emit = (record: { buffer: T[]; subs: Subscription }) => {\n const { buffer, subs } = record;\n subs.unsubscribe();\n arrRemove(bufferRecords, record);\n subscriber.next(buffer);\n restartOnEmit && startBuffer();\n };\n\n /**\n * Called every time we start a new buffer. This does\n * the work of scheduling a job at the requested bufferTimeSpan\n * that will emit the buffer (if it's not unsubscribed before then).\n */\n const startBuffer = () => {\n if (bufferRecords) {\n const subs = new Subscription();\n subscriber.add(subs);\n const buffer: T[] = [];\n const record = {\n buffer,\n subs,\n };\n bufferRecords.push(record);\n executeSchedule(subs, scheduler, () => emit(record), bufferTimeSpan);\n }\n };\n\n if (bufferCreationInterval !== null && bufferCreationInterval >= 0) {\n // The user passed both a bufferTimeSpan (required), and a creation interval\n // That means we need to start new buffers on the interval, and those buffers need\n // to wait the required time span before emitting.\n executeSchedule(subscriber, scheduler, startBuffer, bufferCreationInterval, true);\n } else {\n restartOnEmit = true;\n }\n\n startBuffer();\n\n const bufferTimeSubscriber = createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Copy the records, so if we need to remove one we\n // don't mutate the array. It's hard, but not impossible to\n // set up a buffer time that could mutate the array and\n // cause issues here.\n const recordsCopy = bufferRecords!.slice();\n for (const record of recordsCopy) {\n // Loop over all buffers and\n const { buffer } = record;\n buffer.push(value);\n // If the buffer is over the max size, we need to emit it.\n maxBufferSize <= buffer.length && emit(record);\n }\n },\n () => {\n // The source completed, emit all of the active\n // buffers we have before we complete.\n while (bufferRecords?.length) {\n subscriber.next(bufferRecords.shift()!.buffer);\n }\n bufferTimeSubscriber?.unsubscribe();\n subscriber.complete();\n subscriber.unsubscribe();\n },\n // Pass all errors through to consumer.\n undefined,\n // Clean up\n () => (bufferRecords = null)\n );\n\n source.subscribe(bufferTimeSubscriber);\n });\n}\n","import { Subscription } from '../Subscription';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Buffers the source Observable values starting from an emission from\n * `openings` and ending when the output of `closingSelector` emits.\n *\n * <span class=\"informal\">Collects values from the past as an array. Starts\n * collecting only when `opening` emits, and calls the `closingSelector`\n * function to get an Observable that tells when to close the buffer.</span>\n *\n * ![](bufferToggle.png)\n *\n * Buffers values from the source by opening the buffer via signals from an\n * Observable provided to `openings`, and closing and sending the buffers when\n * a Subscribable or Promise returned by the `closingSelector` function emits.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, bufferToggle, EMPTY } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const buffered = clicks.pipe(bufferToggle(openings, i =>\n * i % 2 ? interval(500) : EMPTY\n * ));\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferWhen}\n * @see {@link windowToggle}\n *\n * @param openings A Subscribable or Promise of notifications to start new\n * buffers.\n * @param closingSelector A function that takes\n * the value emitted by the `openings` observable and returns a Subscribable or Promise,\n * which, when it emits, signals that the associated buffer should be emitted\n * and cleared.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferToggle<T, O>(\n openings: ObservableInput<O>,\n closingSelector: (value: O) => ObservableInput<any>\n): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n const buffers: T[][] = [];\n\n // Subscribe to the openings notifier first\n innerFrom(openings).subscribe(\n createOperatorSubscriber(\n subscriber,\n (openValue) => {\n const buffer: T[] = [];\n buffers.push(buffer);\n // We use this composite subscription, so that\n // when the closing notifier emits, we can tear it down.\n const closingSubscription = new Subscription();\n\n const emitBuffer = () => {\n arrRemove(buffers, buffer);\n subscriber.next(buffer);\n closingSubscription.unsubscribe();\n };\n\n // The line below will add the subscription to the parent subscriber *and* the closing subscription.\n closingSubscription.add(innerFrom(closingSelector(openValue)).subscribe(createOperatorSubscriber(subscriber, emitBuffer, noop)));\n },\n noop\n )\n );\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Value from our source. Add it to all pending buffers.\n for (const buffer of buffers) {\n buffer.push(value);\n }\n },\n () => {\n // Source complete. Emit all pending buffers.\n while (buffers.length > 0) {\n subscriber.next(buffers.shift()!);\n }\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Buffers the source Observable values, using a factory function of closing\n * Observables to determine when to close, emit, and reset the buffer.\n *\n * <span class=\"informal\">Collects values from the past as an array. When it\n * starts collecting values, it calls a function that returns an Observable that\n * tells when to close the buffer and restart collecting.</span>\n *\n * ![](bufferWhen.svg)\n *\n * Opens a buffer immediately, then closes the buffer when the observable\n * returned by calling `closingSelector` function emits a value. When it closes\n * the buffer, it immediately opens a new buffer and repeats the process.\n *\n * ## Example\n *\n * Emit an array of the last clicks every [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, bufferWhen, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const buffered = clicks.pipe(\n * bufferWhen(() => interval(1000 + Math.random() * 4000))\n * );\n * buffered.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n * @see {@link bufferTime}\n * @see {@link bufferToggle}\n * @see {@link windowWhen}\n *\n * @param closingSelector A function that takes no arguments and returns an\n * Observable that signals buffer closure.\n * @return A function that returns an Observable of arrays of buffered values.\n */\nexport function bufferWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, T[]> {\n return operate((source, subscriber) => {\n // The buffer we keep and emit.\n let buffer: T[] | null = null;\n // A reference to the subscriber used to subscribe to\n // the closing notifier. We need to hold this so we can\n // end the subscription after the first notification.\n let closingSubscriber: Subscriber<T> | null = null;\n\n // Ends the previous closing notifier subscription, so it\n // terminates after the first emission, then emits\n // the current buffer if there is one, starts a new buffer, and starts a\n // new closing notifier.\n const openBuffer = () => {\n // Make sure to finalize the closing subscription, we only cared\n // about one notification.\n closingSubscriber?.unsubscribe();\n // emit the buffer if we have one, and start a new buffer.\n const b = buffer;\n buffer = [];\n b && subscriber.next(b);\n\n // Get a new closing notifier and subscribe to it.\n innerFrom(closingSelector()).subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openBuffer, noop)));\n };\n\n // Start the first buffer.\n openBuffer();\n\n // Subscribe to our source.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n // Add every new value to the current buffer.\n (value) => buffer?.push(value),\n // When we complete, emit the buffer if we have one,\n // then complete the result.\n () => {\n buffer && subscriber.next(buffer);\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n // Release memory on finalization\n () => (buffer = closingSubscriber = null!)\n )\n );\n });\n}\n","import { Observable } from '../Observable';\n\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { Subscription } from '../Subscription';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { operate } from '../util/lift';\n\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>>;\n\n/**\n * Catches errors on the observable to be handled by returning a new observable or throwing an error.\n *\n * <span class=\"informal\">\n * It only listens to the error channel and ignores notifications.\n * Handles errors from the source observable, and maps them to a new observable.\n * The error may also be rethrown, or a new error can be thrown to emit an error from the result.\n * </span>\n *\n * ![](catch.png)\n *\n * This operator handles errors, but forwards along all other events to the resulting observable.\n * If the source observable terminates with an error, it will map that error to a new observable,\n * subscribe to it, and forward all of its events to the resulting observable.\n *\n * ## Examples\n *\n * Continue with a different Observable when there's an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => of('I', 'II', 'III', 'IV', 'V'))\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, I, II, III, IV, V\n * ```\n *\n * Retry the caught source Observable again in case of error, similar to `retry()` operator\n *\n * ```ts\n * import { of, map, catchError, take } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError((err, caught) => caught),\n * take(30)\n * )\n * .subscribe(x => console.log(x));\n * // 1, 2, 3, 1, 2, 3, ...\n * ```\n *\n * Throw a new error when the source Observable throws an error\n *\n * ```ts\n * import { of, map, catchError } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5)\n * .pipe(\n * map(n => {\n * if (n === 4) {\n * throw 'four!';\n * }\n * return n;\n * }),\n * catchError(err => {\n * throw 'error in source. Details: ' + err;\n * })\n * )\n * .subscribe({\n * next: x => console.log(x),\n * error: err => console.log(err)\n * });\n * // 1, 2, 3, error in source. Details: four!\n * ```\n *\n * @see {@link onErrorResumeNext}\n * @see {@link repeat}\n * @see {@link repeatWhen}\n * @see {@link retry }\n * @see {@link retryWhen}\n *\n * @param selector A function that takes as arguments `err`, which is the error, and `caught`, which\n * is the source observable, in case you'd like to \"retry\" that observable by returning it again.\n * Whatever observable is returned by the `selector` will be used to continue the observable chain.\n * @return A function that returns an Observable that originates from either\n * the source or the Observable returned by the `selector` function.\n */\nexport function catchError<T, O extends ObservableInput<any>>(\n selector: (err: any, caught: Observable<T>) => O\n): OperatorFunction<T, T | ObservedValueOf<O>> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null = null;\n let syncUnsub = false;\n let handledResult: Observable<ObservedValueOf<O>>;\n\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, undefined, (err) => {\n handledResult = innerFrom(selector(err, catchError(selector)(source)));\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n handledResult.subscribe(subscriber);\n } else {\n // We don't have an innerSub yet, that means the error was synchronous\n // because the subscribe call hasn't returned yet.\n syncUnsub = true;\n }\n })\n );\n\n if (syncUnsub) {\n // We have a synchronous error, we need to make sure to\n // finalize right away. This ensures that callbacks in the `finalize` operator are called\n // at the right time, and that finalization occurs at the expected\n // time between the source error and the subscription to the\n // next observable.\n innerSub.unsubscribe();\n innerSub = null;\n handledResult!.subscribe(subscriber);\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * A basic scan operation. This is used for `scan` and `reduce`.\n * @param accumulator The accumulator to use\n * @param seed The seed value for the state to accumulate\n * @param hasSeed Whether or not a seed was provided\n * @param emitOnNext Whether or not to emit the state on next\n * @param emitBeforeComplete Whether or not to emit the before completion\n */\n\nexport function scanInternals<V, A, S>(\n accumulator: (acc: V | A | S, value: V, index: number) => A,\n seed: S,\n hasSeed: boolean,\n emitOnNext: boolean,\n emitBeforeComplete?: undefined | true\n) {\n return (source: Observable<V>, subscriber: Subscriber<any>) => {\n // Whether or not we have state yet. This will only be\n // false before the first value arrives if we didn't get\n // a seed value.\n let hasState = hasSeed;\n // The state that we're tracking, starting with the seed,\n // if there is one, and then updated by the return value\n // from the accumulator on each emission.\n let state: any = seed;\n // An index to pass to the accumulator function.\n let index = 0;\n\n // Subscribe to our source. All errors and completions are passed through.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Always increment the index.\n const i = index++;\n // Set the state\n state = hasState\n ? // We already have state, so we can get the new state from the accumulator\n accumulator(state, value, i)\n : // We didn't have state yet, a seed value was not provided, so\n\n // we set the state to the first value, and mark that we have state now\n ((hasState = true), value);\n\n // Maybe send it to the consumer.\n emitOnNext && subscriber.next(state);\n },\n // If an onComplete was given, call it, otherwise\n // just pass through the complete notification to the consumer.\n emitBeforeComplete &&\n (() => {\n hasState && subscriber.next(state);\n subscriber.complete();\n })\n )\n );\n };\n}\n","import { scanInternals } from './scanInternals';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\nexport function reduce<V, A = V>(accumulator: (acc: A | V, value: V, index: number) => A): OperatorFunction<V, V | A>;\nexport function reduce<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;\nexport function reduce<V, A, S = A>(accumulator: (acc: A | S, value: V, index: number) => A, seed: S): OperatorFunction<V, A>;\n\n/**\n * Applies an accumulator function over the source Observable, and returns the\n * accumulated result when the source completes, given an optional seed value.\n *\n * <span class=\"informal\">Combines together all values emitted on the source,\n * using an accumulator function that knows how to join a new source value into\n * the accumulation from the past.</span>\n *\n * ![](reduce.png)\n *\n * Like\n * [Array.prototype.reduce()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce),\n * `reduce` applies an `accumulator` function against an accumulation and each\n * value of the source Observable (from the past) to reduce it to a single\n * value, emitted on the output Observable. Note that `reduce` will only emit\n * one value, only when the source Observable completes. It is equivalent to\n * applying operator {@link scan} followed by operator {@link last}.\n *\n * Returns an Observable that applies a specified `accumulator` function to each\n * item emitted by the source Observable. If a `seed` value is specified, then\n * that value will be used as the initial value for the accumulator. If no seed\n * value is specified, the first item of the source is used as the seed.\n *\n * ## Example\n *\n * Count the number of click events that happened in 5 seconds\n *\n * ```ts\n * import { fromEvent, takeUntil, interval, map, reduce } from 'rxjs';\n *\n * const clicksInFiveSeconds = fromEvent(document, 'click')\n * .pipe(takeUntil(interval(5000)));\n *\n * const ones = clicksInFiveSeconds.pipe(map(() => 1));\n * const seed = 0;\n * const count = ones.pipe(reduce((acc, one) => acc + one, seed));\n *\n * count.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link count}\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link scan}\n *\n * @param accumulator The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @return A function that returns an Observable that emits a single value that\n * is the result of accumulating the values emitted by the source Observable.\n */\nexport function reduce<V, A>(accumulator: (acc: V | A, value: V, index: number) => A, seed?: any): OperatorFunction<V, V | A> {\n return operate(scanInternals(accumulator, seed, arguments.length >= 2, false, true));\n}\n","import { reduce } from './reduce';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\nconst arrReducer = (arr: any[], value: any) => (arr.push(value), arr);\n\n/**\n * Collects all source emissions and emits them as an array when the source completes.\n *\n * <span class=\"informal\">Get all values inside an array when the source completes</span>\n *\n * ![](toArray.png)\n *\n * `toArray` will wait until the source Observable completes before emitting\n * the array containing all emissions. When the source Observable errors no\n * array will be emitted.\n *\n * ## Example\n *\n * ```ts\n * import { interval, take, toArray } from 'rxjs';\n *\n * const source = interval(1000);\n * const example = source.pipe(\n * take(10),\n * toArray()\n * );\n *\n * example.subscribe(value => console.log(value));\n *\n * // output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n * ```\n *\n * @return A function that returns an Observable that emits an array of items\n * emitted by the source Observable when source completes.\n */\nexport function toArray<T>(): OperatorFunction<T, T[]> {\n // Because arrays are mutable, and we're mutating the array in this\n // reducer process, we have to encapsulate the creation of the initial\n // array within this `operate` function.\n return operate((source, subscriber) => {\n reduce(arrReducer, [] as T[])(source).subscribe(subscriber);\n });\n}\n","import { Observable } from '../Observable';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { pipe } from '../util/pipe';\nimport { mergeMap } from './mergeMap';\nimport { toArray } from './toArray';\n\n/**\n * Collects all of the inner sources from source observable. Then, once the\n * source completes, joins the values using the given static.\n *\n * This is used for {@link combineLatestAll} and {@link zipAll} which both have the\n * same behavior of collecting all inner observables, then operating on them.\n *\n * @param joinFn The type of static join to apply to the sources collected\n * @param project The projection function to apply to the values, if any\n */\nexport function joinAllInternals<T, R>(joinFn: (sources: ObservableInput<T>[]) => Observable<T>, project?: (...args: any[]) => R) {\n return pipe(\n // Collect all inner sources into an array, and emit them when the\n // source completes.\n toArray() as OperatorFunction<ObservableInput<T>, ObservableInput<T>[]>,\n // Run the join function on the collected array of inner sources.\n mergeMap((sources) => joinFn(sources)),\n // If a projection function was supplied, apply it to each result.\n project ? mapOneOrManyArgs(project) : (identity as any)\n );\n}\n","import { combineLatest } from '../observable/combineLatest';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { joinAllInternals } from './joinAllInternals';\n\nexport function combineLatestAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function combineLatestAll<T>(): OperatorFunction<any, T[]>;\nexport function combineLatestAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function combineLatestAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n\n/**\n * Flattens an Observable-of-Observables by applying {@link combineLatest} when the Observable-of-Observables completes.\n *\n * `combineLatestAll` takes an Observable of Observables, and collects all Observables from it. Once the outer Observable completes,\n * it subscribes to all collected Observables and combines their values using the {@link combineLatest} strategy, such that:\n *\n * * Every time an inner Observable emits, the output Observable emits\n * * When the returned observable emits, it emits all of the latest values by:\n * * If a `project` function is provided, it is called with each recent value from each inner Observable in whatever order they\n * arrived, and the result of the `project` function is what is emitted by the output Observable.\n * * If there is no `project` function, an array of all the most recent values is emitted by the output Observable.\n *\n * ## Example\n *\n * Map two click events to a finite interval Observable, then apply `combineLatestAll`\n *\n * ```ts\n * import { fromEvent, map, interval, take, combineLatestAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(Math.random() * 2000).pipe(take(3))),\n * take(2)\n * );\n * const result = higherOrder.pipe(combineLatestAll());\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link combineLatestWith}\n * @see {@link mergeAll}\n *\n * @param project optional function to map the most recent values from each inner Observable into a new result.\n * Takes each of the most recent values from each collected inner Observable as arguments, in order.\n * @return A function that returns an Observable that flattens Observables\n * emitted by the source Observable.\n */\nexport function combineLatestAll<R>(project?: (...values: Array<any>) => R) {\n return joinAllInternals(combineLatest, project);\n}\n","import { combineLatestAll } from './combineLatestAll';\n\n/**\n * @deprecated Renamed to {@link combineLatestAll}. Will be removed in v8.\n */\nexport const combineAll = combineLatestAll;\n","import { combineLatestInit } from '../observable/combineLatest';\nimport { ObservableInput, ObservableInputTuple, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { mapOneOrManyArgs } from '../util/mapOneOrManyArgs';\nimport { pipe } from '../util/pipe';\nimport { popResultSelector } from '../util/args';\n\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(\n sources: [...ObservableInputTuple<A>],\n project: (...values: [T, ...A]) => R\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;\n\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(\n ...sourcesAndProject: [...ObservableInputTuple<A>, (...values: [T, ...A]) => R]\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8. */\nexport function combineLatest<T, A extends readonly unknown[], R>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, [T, ...A]>;\n\n/**\n * @deprecated Replaced with {@link combineLatestWith}. Will be removed in v8.\n */\nexport function combineLatest<T, R>(...args: (ObservableInput<any> | ((...values: any[]) => R))[]): OperatorFunction<T, unknown> {\n const resultSelector = popResultSelector(args);\n return resultSelector\n ? pipe(combineLatest(...(args as Array<ObservableInput<any>>)), mapOneOrManyArgs(resultSelector))\n : operate((source, subscriber) => {\n combineLatestInit([source, ...argsOrArgArray(args)])(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { combineLatest } from './combineLatest';\n\n/**\n * Create an observable that combines the latest values from all passed observables and the source\n * into arrays and emits them.\n *\n * Returns an observable, that when subscribed to, will subscribe to the source observable and all\n * sources provided as arguments. Once all sources emit at least one value, all of the latest values\n * will be emitted as an array. After that, every time any source emits a value, all of the latest values\n * will be emitted as an array.\n *\n * This is a useful operator for eagerly calculating values based off of changed inputs.\n *\n * ## Example\n *\n * Simple concatenation of values from two inputs\n *\n * ```ts\n * import { fromEvent, combineLatestWith, map } from 'rxjs';\n *\n * // Setup: Add two inputs to the page\n * const input1 = document.createElement('input');\n * document.body.appendChild(input1);\n * const input2 = document.createElement('input');\n * document.body.appendChild(input2);\n *\n * // Get streams of changes\n * const input1Changes$ = fromEvent(input1, 'change');\n * const input2Changes$ = fromEvent(input2, 'change');\n *\n * // Combine the changes by adding them together\n * input1Changes$.pipe(\n * combineLatestWith(input2Changes$),\n * map(([e1, e2]) => (<HTMLInputElement>e1.target).value + ' - ' + (<HTMLInputElement>e2.target).value)\n * )\n * .subscribe(x => console.log(x));\n * ```\n *\n * @param otherSources the other sources to subscribe to.\n * @return A function that returns an Observable that emits the latest\n * emissions from both source and provided Observables.\n */\nexport function combineLatestWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, Cons<T, A>> {\n return combineLatest(...otherSources);\n}\n","import { mergeMap } from './mergeMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/* tslint:disable:max-line-length */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\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, 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 *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, concatMap, interval, take } from 'rxjs';\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 project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * values from each projected inner Observable sequentially.\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 isFunction(resultSelector) ? mergeMap(project, resultSelector, 1) : mergeMap(project, 1);\n}\n","import { concatMap } from './concatMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)` */\nexport function concatMapTo<O extends ObservableInput<unknown>>(observable: O): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMapTo<O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: undefined\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function concatMapTo<T, R, O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in a serialized fashion on the output Observable.\n *\n * <span class=\"informal\">It's like {@link concatMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * ![](concatMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. Each new `innerObservable`\n * instance emitted on the output Observable is concatenated with the previous\n * `innerObservable` instance.\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: `concatMapTo` is equivalent to `mergeMapTo` with concurrency parameter\n * set to `1`.\n *\n * ## Example\n *\n * For each click event, tick every second from 0 to 3, with no concurrency\n *\n * ```ts\n * import { fromEvent, concatMapTo, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * concatMapTo(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 concatMap}\n * @see {@link mergeMapTo}\n * @see {@link switchMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @return A function that returns an Observable of values merged together by\n * joining the passed Observable with itself, one after the other, for each\n * value emitted from the source.\n * @deprecated Will be removed in v9. Use {@link concatMap} instead: `concatMap(() => result)`\n */\nexport function concatMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? concatMap(() => innerObservable, resultSelector) : concatMap(() => innerObservable);\n}\n","import { ObservableInputTuple, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { concatAll } from './concatAll';\nimport { popScheduler } from '../util/args';\nimport { from } from '../observable/from';\n\n/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */\nexport function concat<T, A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link concatWith}. Will be removed in v8. */\nexport function concat<T, A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n\n/**\n * @deprecated Replaced with {@link concatWith}. Will be removed in v8.\n */\nexport function concat<T, R>(...args: any[]): OperatorFunction<T, R> {\n const scheduler = popScheduler(args);\n return operate((source, subscriber) => {\n concatAll()(from([source, ...args], scheduler)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { concat } from './concat';\n\n/**\n * Emits all of the values from the source observable, then, once it completes, subscribes\n * to each observable source provided, one at a time, emitting all of their values, and not subscribing\n * to the next one until it completes.\n *\n * `concat(a$, b$, c$)` is the same as `a$.pipe(concatWith(b$, c$))`.\n *\n * ## Example\n *\n * Listen for one mouse click, then listen for all mouse moves.\n *\n * ```ts\n * import { fromEvent, map, take, concatWith } from 'rxjs';\n *\n * const clicks$ = fromEvent(document, 'click');\n * const moves$ = fromEvent(document, 'mousemove');\n *\n * clicks$.pipe(\n * map(() => 'click'),\n * take(1),\n * concatWith(\n * moves$.pipe(\n * map(() => 'move')\n * )\n * )\n * )\n * .subscribe(x => console.log(x));\n *\n * // 'click'\n * // 'move'\n * // 'move'\n * // 'move'\n * // ...\n * ```\n *\n * @param otherSources Other observable sources to subscribe to, in sequence, after the original source is complete.\n * @return A function that returns an Observable that concatenates\n * subscriptions to the source and provided Observables subscribing to the next\n * only once the current subscription completes.\n */\nexport function concatWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return concat(...otherSources);\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { Subscribable } from '../types';\n\n/**\n * Used to convert a subscribable to an observable.\n *\n * Currently, this is only used within internals.\n *\n * TODO: Discuss ObservableInput supporting \"Subscribable\".\n * https://github.com/ReactiveX/rxjs/issues/5909\n *\n * @param subscribable A subscribable\n */\nexport function fromSubscribable<T>(subscribable: Subscribable<T>) {\n return new Observable((subscriber: Subscriber<T>) => subscribable.subscribe(subscriber));\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf, SubjectLike } from '../types';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { fromSubscribable } from '../observable/fromSubscribable';\n\n/**\n * An object used to configure {@link connect} operator.\n */\nexport interface ConnectConfig<T> {\n /**\n * A factory function used to create the Subject through which the source\n * is multicast. By default, this creates a {@link Subject}.\n */\n connector: () => SubjectLike<T>;\n}\n\n/**\n * The default configuration for `connect`.\n */\nconst DEFAULT_CONFIG: ConnectConfig<unknown> = {\n connector: () => new Subject<unknown>(),\n};\n\n/**\n * Creates an observable by multicasting the source within a function that\n * allows the developer to define the usage of the multicast prior to connection.\n *\n * This is particularly useful if the observable source you wish to multicast could\n * be synchronous or asynchronous. This sets it apart from {@link share}, which, in the\n * case of totally synchronous sources will fail to share a single subscription with\n * multiple consumers, as by the time the subscription to the result of {@link share}\n * has returned, if the source is synchronous its internal reference count will jump from\n * 0 to 1 back to 0 and reset.\n *\n * To use `connect`, you provide a `selector` function that will give you\n * a multicast observable that is not yet connected. You then use that multicast observable\n * to create a resulting observable that, when subscribed, will set up your multicast. This is\n * generally, but not always, accomplished with {@link merge}.\n *\n * Note that using a {@link takeUntil} inside of `connect`'s `selector` _might_ mean you were looking\n * to use the {@link takeWhile} operator instead.\n *\n * When you subscribe to the result of `connect`, the `selector` function will be called. After\n * the `selector` function returns, the observable it returns will be subscribed to, _then_ the\n * multicast will be connected to the source.\n *\n * ## Example\n *\n * Sharing a totally synchronous observable\n *\n * ```ts\n * import { of, tap, connect, merge, map, filter } from 'rxjs';\n *\n * const source$ = of(1, 2, 3, 4, 5).pipe(\n * tap({\n * subscribe: () => console.log('subscription started'),\n * next: n => console.log(`source emitted ${ n }`)\n * })\n * );\n *\n * source$.pipe(\n * // Notice in here we're merging 3 subscriptions to `shared$`.\n * connect(shared$ => merge(\n * shared$.pipe(map(n => `all ${ n }`)),\n * shared$.pipe(filter(n => n % 2 === 0), map(n => `even ${ n }`)),\n * shared$.pipe(filter(n => n % 2 === 1), map(n => `odd ${ n }`))\n * ))\n * )\n * .subscribe(console.log);\n *\n * // Expected output: (notice only one subscription)\n * 'subscription started'\n * 'source emitted 1'\n * 'all 1'\n * 'odd 1'\n * 'source emitted 2'\n * 'all 2'\n * 'even 2'\n * 'source emitted 3'\n * 'all 3'\n * 'odd 3'\n * 'source emitted 4'\n * 'all 4'\n * 'even 4'\n * 'source emitted 5'\n * 'all 5'\n * 'odd 5'\n * ```\n *\n * @param selector A function used to set up the multicast. Gives you a multicast observable\n * that is not yet connected. With that, you're expected to create and return\n * and Observable, that when subscribed to, will utilize the multicast observable.\n * After this function is executed -- and its return value subscribed to -- the\n * operator will subscribe to the source, and the connection will be made.\n * @param config The configuration object for `connect`.\n */\nexport function connect<T, O extends ObservableInput<unknown>>(\n selector: (shared: Observable<T>) => O,\n config: ConnectConfig<T> = DEFAULT_CONFIG\n): OperatorFunction<T, ObservedValueOf<O>> {\n const { connector } = config;\n return operate((source, subscriber) => {\n const subject = connector();\n innerFrom(selector(fromSubscribable(subject))).subscribe(subscriber);\n subscriber.add(source.subscribe(subject));\n });\n}\n","import { OperatorFunction } from '../types';\nimport { reduce } from './reduce';\n\n/**\n * Counts the number of emissions on the source and emits that number when the\n * source completes.\n *\n * <span class=\"informal\">Tells how many values were emitted, when the source\n * completes.</span>\n *\n * ![](count.png)\n *\n * `count` transforms an Observable that emits values into an Observable that\n * emits a single value that represents the number of values emitted by the\n * source Observable. If the source Observable terminates with an error, `count`\n * will pass this error notification along without emitting a value first. If\n * the source Observable does not terminate at all, `count` will neither emit\n * a value nor terminate. This operator takes an optional `predicate` function\n * as argument, in which case the output emission will represent the number of\n * source values that matched `true` with the `predicate`.\n *\n * ## Examples\n *\n * Counts how many seconds have passed before the first click happened\n *\n * ```ts\n * import { interval, fromEvent, takeUntil, count } from 'rxjs';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const secondsBeforeClick = seconds.pipe(takeUntil(clicks));\n * const result = secondsBeforeClick.pipe(count());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Counts how many odd numbers are there between 1 and 7\n *\n * ```ts\n * import { range, count } from 'rxjs';\n *\n * const numbers = range(1, 7);\n * const result = numbers.pipe(count(i => i % 2 === 1));\n * result.subscribe(x => console.log(x));\n * // Results in:\n * // 4\n * ```\n *\n * @see {@link max}\n * @see {@link min}\n * @see {@link reduce}\n *\n * @param predicate A function that is used to analyze the value and the index and\n * determine whether or not to increment the count. Return `true` to increment the count,\n * and return `false` to keep the count the same.\n * If the predicate is not provided, every value will be counted.\n * @return A function that returns an Observable that emits one number that\n * represents the count of emissions.\n */\nexport function count<T>(predicate?: (value: T, index: number) => boolean): OperatorFunction<T, number> {\n return reduce((total, value, i) => (!predicate || predicate(value, i) ? total + 1 : total), 0);\n}\n","import { Subscriber } from '../Subscriber';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Emits a notification from the source Observable only after a particular time span\n * determined by another Observable has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link debounceTime}, but the time span of\n * emission silence is determined by a second Observable.</span>\n *\n * ![](debounce.svg)\n *\n * `debounce` delays notifications emitted by the source Observable, but drops previous\n * pending delayed emissions if a new notification arrives on the source Observable.\n * This operator keeps track of the most recent notification from the source\n * Observable, and spawns a duration Observable by calling the\n * `durationSelector` function. The notification is emitted only when the duration\n * Observable emits a next notification, and if no other notification was emitted on\n * the source Observable since the duration Observable was spawned. If a new\n * notification appears before the duration Observable emits, the previous notification will\n * not be emitted and a new duration is scheduled from `durationSelector` is scheduled.\n * If the completing event happens during the scheduled duration the last cached notification\n * is emitted before the completion event is forwarded to the output observable.\n * If the error event happens during the scheduled duration or after it only the error event is\n * forwarded to the output observable. The cache notification is not emitted in this case.\n *\n * Like {@link debounceTime}, this is a rate-limiting operator, and also a\n * delay-like operator since output emissions do not necessarily occur at the\n * same time as they did on the source Observable.\n *\n * ## Example\n *\n * Emit the most recent click after a burst of clicks\n *\n * ```ts\n * import { fromEvent, scan, debounce, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * scan(i => ++i, 1),\n * debounce(i => interval(200 * i))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link throttle}\n * @see {@link throttleTime}\n *\n * @param durationSelector A function\n * that receives a value from the source Observable, for computing the timeout\n * duration for each source value, returned as an Observable or a Promise.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified duration Observable returned by\n * `durationSelector`, and may drop some values if they occur too frequently.\n */\nexport function debounce<T>(durationSelector: (value: T) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n // The subscriber/subscription for the current debounce, if there is one.\n let durationSubscriber: Subscriber<any> | null = null;\n\n const emit = () => {\n // Unsubscribe any current debounce subscription we have,\n // we only cared about the first notification from it, and we\n // want to clean that subscription up as soon as possible.\n durationSubscriber?.unsubscribe();\n durationSubscriber = null;\n if (hasValue) {\n // We have a value! Free up memory first, then emit the value.\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Cancel any pending debounce duration. We don't\n // need to null it out here yet tho, because we're just going\n // to create another one in a few lines.\n durationSubscriber?.unsubscribe();\n hasValue = true;\n lastValue = value;\n // Capture our duration subscriber, so we can unsubscribe it when we're notified\n // and we're going to emit the value.\n durationSubscriber = createOperatorSubscriber(subscriber, emit, noop);\n // Subscribe to the duration.\n innerFrom(durationSelector(value)).subscribe(durationSubscriber);\n },\n () => {\n // Source completed.\n // Emit any pending debounced values then complete\n emit();\n subscriber.complete();\n },\n // Pass all errors through to consumer\n undefined,\n () => {\n // Finalization.\n lastValue = durationSubscriber = null;\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SchedulerAction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits a notification from the source Observable only after a particular time span\n * has passed without another source emission.\n *\n * <span class=\"informal\">It's like {@link delay}, but passes only the most\n * recent notification from each burst of emissions.</span>\n *\n * ![](debounceTime.png)\n *\n * `debounceTime` delays notifications emitted by the source Observable, but drops\n * previous pending delayed emissions if a new notification arrives on the source\n * Observable. This operator keeps track of the most recent notification from the\n * source Observable, and emits that only when `dueTime` has passed\n * without any other notification appearing on the source Observable. If a new value\n * appears before `dueTime` silence occurs, the previous notification will be dropped\n * and will not be emitted and a new `dueTime` is scheduled.\n * If the completing event happens during `dueTime` the last cached notification\n * is emitted before the completion event is forwarded to the output observable.\n * If the error event happens during `dueTime` or after it only the error event is\n * forwarded to the output observable. The cache notification is not emitted in this case.\n *\n * This is a rate-limiting operator, because it is impossible for more than one\n * notification to be emitted in any time window of duration `dueTime`, but it is also\n * a delay-like operator since output emissions do not occur at the same time as\n * they did on the source Observable. Optionally takes a {@link SchedulerLike} for\n * managing timers.\n *\n * ## Example\n *\n * Emit the most recent click after a burst of clicks\n *\n * ```ts\n * import { fromEvent, debounceTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(debounceTime(1000));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link auditTime}\n * @see {@link debounce}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link throttle}\n * @see {@link throttleTime}\n *\n * @param dueTime The timeout duration in milliseconds (or the time unit determined\n * internally by the optional `scheduler`) for the window of time required to wait\n * for emission silence before emitting the most recent source value.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers that\n * handle the timeout for each value.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified `dueTime`, and may drop some values\n * if they occur too frequently.\n */\nexport function debounceTime<T>(dueTime: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let activeTask: Subscription | null = null;\n let lastValue: T | null = null;\n let lastTime: number | null = null;\n\n const emit = () => {\n if (activeTask) {\n // We have a value! Free up memory first, then emit the value.\n activeTask.unsubscribe();\n activeTask = null;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n };\n function emitWhenIdle(this: SchedulerAction<unknown>) {\n // This is called `dueTime` after the first value\n // but we might have received new values during this window!\n\n const targetTime = lastTime! + dueTime;\n const now = scheduler.now();\n if (now < targetTime) {\n // On that case, re-schedule to the new target\n activeTask = this.schedule(undefined, targetTime - now);\n subscriber.add(activeTask);\n return;\n }\n\n emit();\n }\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n lastValue = value;\n lastTime = scheduler.now();\n\n // Only set up a task if it's not already up\n if (!activeTask) {\n activeTask = scheduler.schedule(emitWhenIdle, dueTime);\n subscriber.add(activeTask);\n }\n },\n () => {\n // Source completed.\n // Emit any pending debounced values then complete\n emit();\n subscriber.complete();\n },\n // Pass all errors through to consumer.\n undefined,\n () => {\n // Finalization.\n lastValue = activeTask = null;\n }\n )\n );\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits a given value if the source Observable completes without emitting any\n * `next` value, otherwise mirrors the source Observable.\n *\n * <span class=\"informal\">If the source Observable turns out to be empty, then\n * this operator will emit a default value.</span>\n *\n * ![](defaultIfEmpty.png)\n *\n * `defaultIfEmpty` emits the values emitted by the source Observable or a\n * specified default value if the source Observable is empty (completes without\n * having emitted any `next` value).\n *\n * ## Example\n *\n * If no clicks happen in 5 seconds, then emit 'no clicks'\n *\n * ```ts\n * import { fromEvent, takeUntil, interval, defaultIfEmpty } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const clicksBeforeFive = clicks.pipe(takeUntil(interval(5000)));\n * const result = clicksBeforeFive.pipe(defaultIfEmpty('no clicks'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link empty}\n * @see {@link last}\n *\n * @param defaultValue The default value used if the source\n * Observable is empty.\n * @return A function that returns an Observable that emits either the\n * specified `defaultValue` if the source Observable emits no items, or the\n * values emitted by the source Observable.\n */\nexport function defaultIfEmpty<T, R>(defaultValue: R): OperatorFunction<T, T | R> {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n subscriber.next(value);\n },\n () => {\n if (!hasValue) {\n subscriber.next(defaultValue!);\n }\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { EMPTY } from '../observable/empty';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits only the first `count` values emitted by the source Observable.\n *\n * <span class=\"informal\">Takes the first `count` values from the source, then\n * completes.</span>\n *\n * ![](take.png)\n *\n * `take` returns an Observable that emits only the first `count` values emitted\n * by the source Observable. If the source emits fewer than `count` values then\n * all of its values are emitted. After that, it completes, regardless if the\n * source completes.\n *\n * ## Example\n *\n * Take the first 5 seconds of an infinite 1-second interval Observable\n *\n * ```ts\n * import { interval, take } from 'rxjs';\n *\n * const intervalCount = interval(1000);\n * const takeFive = intervalCount.pipe(take(5));\n * takeFive.subscribe(x => console.log(x));\n *\n * // Logs:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param count The maximum number of `next` values to emit.\n * @return A function that returns an Observable that emits only the first\n * `count` values emitted by the source Observable, or all of the values from\n * the source if the source emits fewer than `count` values.\n */\nexport function take<T>(count: number): MonoTypeOperatorFunction<T> {\n return count <= 0\n ? // If we are taking no values, that's empty.\n () => EMPTY\n : operate((source, subscriber) => {\n let seen = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // Increment the number of values we have seen,\n // then check it against the allowed count to see\n // if we are still letting values through.\n if (++seen <= count) {\n subscriber.next(value);\n // If we have met or passed our allowed count,\n // we need to complete. We have to do <= here,\n // because re-entrant code will increment `seen` twice.\n if (count <= seen) {\n subscriber.complete();\n }\n }\n })\n );\n });\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\n\n/**\n * Ignores all items emitted by the source Observable and only passes calls of `complete` or `error`.\n *\n * ![](ignoreElements.png)\n *\n * The `ignoreElements` operator suppresses all items emitted by the source Observable,\n * but allows its termination notification (either `error` or `complete`) to pass through unchanged.\n *\n * If you do not care about the items being emitted by an Observable, but you do want to be notified\n * when it completes or when it terminates with an error, you can apply the `ignoreElements` operator\n * to the Observable, which will ensure that it will never call its observers’ `next` handlers.\n *\n * ## Example\n *\n * Ignore all `next` emissions from the source\n *\n * ```ts\n * import { of, ignoreElements } from 'rxjs';\n *\n * of('you', 'talking', 'to', 'me')\n * .pipe(ignoreElements())\n * .subscribe({\n * next: word => console.log(word),\n * error: err => console.log('error:', err),\n * complete: () => console.log('the end'),\n * });\n *\n * // result:\n * // 'the end'\n * ```\n *\n * @return A function that returns an empty Observable that only calls\n * `complete` or `error`, based on which one is called by the source\n * Observable.\n */\nexport function ignoreElements(): OperatorFunction<unknown, never> {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, noop));\n });\n}\n","import { OperatorFunction } from '../types';\nimport { map } from './map';\n\n/** @deprecated To be removed in v9. Use {@link map} instead: `map(() => value)`. */\nexport function mapTo<R>(value: R): OperatorFunction<unknown, R>;\n/**\n * @deprecated Do not specify explicit type parameters. Signatures with type parameters\n * that cannot be inferred will be removed in v8. `mapTo` itself will be removed in v9,\n * use {@link map} instead: `map(() => value)`.\n * */\nexport function mapTo<T, R>(value: R): OperatorFunction<T, R>;\n\n/**\n * Emits the given constant value on the output Observable every time the source\n * Observable emits a value.\n *\n * <span class=\"informal\">Like {@link map}, but it maps every source value to\n * the same output value every time.</span>\n *\n * ![](mapTo.png)\n *\n * Takes a constant `value` as argument, and emits that whenever the source\n * Observable emits a value. In other words, ignores the actual source value,\n * and simply uses the emission moment to know when to emit the given `value`.\n *\n * ## Example\n *\n * Map every click to the string `'Hi'`\n *\n * ```ts\n * import { fromEvent, mapTo } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const greetings = clicks.pipe(mapTo('Hi'));\n *\n * greetings.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param value The value to map each source value to.\n * @return A function that returns an Observable that emits the given `value`\n * every time the source Observable emits.\n * @deprecated To be removed in v9. Use {@link map} instead: `map(() => value)`.\n */\nexport function mapTo<R>(value: R): OperatorFunction<unknown, R> {\n return map(() => value);\n}\n","import { Observable } from '../Observable';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { concat } from '../observable/concat';\nimport { take } from './take';\nimport { ignoreElements } from './ignoreElements';\nimport { mapTo } from './mapTo';\nimport { mergeMap } from './mergeMap';\nimport { innerFrom } from '../observable/innerFrom';\n\n/** @deprecated The `subscriptionDelay` parameter will be removed in v8. */\nexport function delayWhen<T>(\n delayDurationSelector: (value: T, index: number) => ObservableInput<any>,\n subscriptionDelay: Observable<any>\n): MonoTypeOperatorFunction<T>;\nexport function delayWhen<T>(delayDurationSelector: (value: T, index: number) => ObservableInput<any>): MonoTypeOperatorFunction<T>;\n\n/**\n * Delays the emission of items from the source Observable by a given time span\n * determined by the emissions of another Observable.\n *\n * <span class=\"informal\">It's like {@link delay}, but the time span of the\n * delay duration is determined by a second Observable.</span>\n *\n * ![](delayWhen.png)\n *\n * `delayWhen` operator shifts each emitted value from the source Observable by\n * a time span determined by another Observable. When the source emits a value,\n * the `delayDurationSelector` function is called with the value emitted from\n * the source Observable as the first argument to the `delayDurationSelector`.\n * The `delayDurationSelector` function should return an {@link ObservableInput},\n * that is internally converted to an Observable that is called the \"duration\"\n * Observable.\n *\n * The source value is emitted on the output Observable only when the \"duration\"\n * Observable emits ({@link guide/glossary-and-semantics#next next}s) any value.\n * Upon that, the \"duration\" Observable gets unsubscribed.\n *\n * Before RxJS V7, the {@link guide/glossary-and-semantics#complete completion}\n * of the \"duration\" Observable would have been triggering the emission of the\n * source value to the output Observable, but with RxJS V7, this is not the case\n * anymore.\n *\n * Only next notifications (from the \"duration\" Observable) trigger values from\n * the source Observable to be passed to the output Observable. If the \"duration\"\n * Observable only emits the complete notification (without next), the value\n * emitted by the source Observable will never get to the output Observable - it\n * will be swallowed. If the \"duration\" Observable errors, the error will be\n * propagated to the output Observable.\n *\n * Optionally, `delayWhen` takes a second argument, `subscriptionDelay`, which\n * is an Observable. When `subscriptionDelay` emits its first value or\n * completes, the source Observable is subscribed to and starts behaving like\n * described in the previous paragraph. If `subscriptionDelay` is not provided,\n * `delayWhen` will subscribe to the source Observable as soon as the output\n * Observable is subscribed.\n *\n * ## Example\n *\n * Delay each click by a random amount of time, between 0 and 5 seconds\n *\n * ```ts\n * import { fromEvent, delayWhen, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(\n * delayWhen(() => interval(Math.random() * 5000))\n * );\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link delay}\n * @see {@link throttle}\n * @see {@link throttleTime}\n * @see {@link debounce}\n * @see {@link debounceTime}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link audit}\n * @see {@link auditTime}\n *\n * @param delayDurationSelector A function that returns an `ObservableInput` for\n * each `value` emitted by the source Observable, which is then used to delay the\n * emission of that `value` on the output Observable until the `ObservableInput`\n * returned from this function emits a next value. When called, beside `value`,\n * this function receives a zero-based `index` of the emission order.\n * @param subscriptionDelay An Observable that triggers the subscription to the\n * source Observable once it emits any value.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by an amount of time specified by the Observable\n * returned by `delayDurationSelector`.\n */\nexport function delayWhen<T>(\n delayDurationSelector: (value: T, index: number) => ObservableInput<any>,\n subscriptionDelay?: Observable<any>\n): MonoTypeOperatorFunction<T> {\n if (subscriptionDelay) {\n // DEPRECATED PATH\n return (source: Observable<T>) =>\n concat(subscriptionDelay.pipe(take(1), ignoreElements()), source.pipe(delayWhen(delayDurationSelector)));\n }\n\n return mergeMap((value, index) => innerFrom(delayDurationSelector(value, index)).pipe(take(1), mapTo(value)));\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { delayWhen } from './delayWhen';\nimport { timer } from '../observable/timer';\n\n/**\n * Delays the emission of items from the source Observable by a given timeout or\n * until a given Date.\n *\n * <span class=\"informal\">Time shifts each item by some specified amount of\n * milliseconds.</span>\n *\n * ![](delay.svg)\n *\n * If the delay argument is a Number, this operator time shifts the source\n * Observable by that amount of time expressed in milliseconds. The relative\n * time intervals between the values are preserved.\n *\n * If the delay argument is a Date, this operator time shifts the start of the\n * Observable execution until the given date occurs.\n *\n * ## Examples\n *\n * Delay each click by one second\n *\n * ```ts\n * import { fromEvent, delay } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const delayedClicks = clicks.pipe(delay(1000)); // each click emitted after 1 second\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * Delay all clicks until a future date happens\n *\n * ```ts\n * import { fromEvent, delay } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const date = new Date('March 15, 2050 12:00:00'); // in the future\n * const delayedClicks = clicks.pipe(delay(date)); // click emitted only after that date\n * delayedClicks.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link delayWhen}\n * @see {@link throttle}\n * @see {@link throttleTime}\n * @see {@link debounce}\n * @see {@link debounceTime}\n * @see {@link sample}\n * @see {@link sampleTime}\n * @see {@link audit}\n * @see {@link auditTime}\n *\n * @param due The delay duration in milliseconds (a `number`) or a `Date` until\n * which the emission of the source items is delayed.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the time-shift for each item.\n * @return A function that returns an Observable that delays the emissions of\n * the source Observable by the specified timeout or Date.\n */\nexport function delay<T>(due: number | Date, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n const duration = timer(due, scheduler);\n return delayWhen(() => duration);\n}\n","import { observeNotification } from '../Notification';\nimport { OperatorFunction, ObservableNotification, ValueFromNotification } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Converts an Observable of {@link ObservableNotification} objects into the emissions\n * that they represent.\n *\n * <span class=\"informal\">Unwraps {@link ObservableNotification} objects as actual `next`,\n * `error` and `complete` emissions. The opposite of {@link materialize}.</span>\n *\n * ![](dematerialize.png)\n *\n * `dematerialize` is assumed to operate an Observable that only emits\n * {@link ObservableNotification} objects as `next` emissions, and does not emit any\n * `error`. Such Observable is the output of a `materialize` operation. Those\n * notifications are then unwrapped using the metadata they contain, and emitted\n * as `next`, `error`, and `complete` on the output Observable.\n *\n * Use this operator in conjunction with {@link materialize}.\n *\n * ## Example\n *\n * Convert an Observable of Notifications to an actual Observable\n *\n * ```ts\n * import { NextNotification, ErrorNotification, of, dematerialize } from 'rxjs';\n *\n * const notifA: NextNotification<string> = { kind: 'N', value: 'A' };\n * const notifB: NextNotification<string> = { kind: 'N', value: 'B' };\n * const notifE: ErrorNotification = { kind: 'E', error: new TypeError('x.toUpperCase is not a function') };\n *\n * const materialized = of(notifA, notifB, notifE);\n *\n * const upperCase = materialized.pipe(dematerialize());\n * upperCase.subscribe({\n * next: x => console.log(x),\n * error: e => console.error(e)\n * });\n *\n * // Results in:\n * // A\n * // B\n * // TypeError: x.toUpperCase is not a function\n * ```\n *\n * @see {@link materialize}\n *\n * @return A function that returns an Observable that emits items and\n * notifications embedded in Notification objects emitted by the source\n * Observable.\n */\nexport function dematerialize<N extends ObservableNotification<any>>(): OperatorFunction<N, ValueFromNotification<N>> {\n return operate((source, subscriber) => {\n source.subscribe(createOperatorSubscriber(subscriber, (notification) => observeNotification(notification, subscriber)));\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that are distinct by comparison from previous items.\n *\n * If a `keySelector` function is provided, then it will project each value from the source observable into a new value that it will\n * check for equality with previously projected values. If the `keySelector` function is not provided, it will use each value from the\n * source observable directly with an equality check against previous values.\n *\n * In JavaScript runtimes that support `Set`, this operator will use a `Set` to improve performance of the distinct value checking.\n *\n * In other runtimes, this operator will use a minimal implementation of `Set` that relies on an `Array` and `indexOf` under the\n * hood, so performance will degrade as more values are checked for distinction. Even in newer browsers, a long-running `distinct`\n * use might result in memory leaks. To help alleviate this in some scenarios, an optional `flushes` parameter is also provided so\n * that the internal `Set` can be \"flushed\", basically clearing it of values.\n *\n * ## Examples\n *\n * A simple example with numbers\n *\n * ```ts\n * import { of, distinct } from 'rxjs';\n *\n * of(1, 1, 2, 2, 2, 1, 2, 3, 4, 3, 2, 1)\n * .pipe(distinct())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 1\n * // 2\n * // 3\n * // 4\n * ```\n *\n * An example using the `keySelector` function\n *\n * ```ts\n * import { of, distinct } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo'},\n * { age: 7, name: 'Bar'},\n * { age: 5, name: 'Foo'}\n * )\n * .pipe(distinct(({ name }) => name))\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * ```\n * @see {@link distinctUntilChanged}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param keySelector Optional `function` to select which value you want to check as distinct.\n * @param flushes Optional `ObservableInput` for flushing the internal HashSet of the operator.\n * @return A function that returns an Observable that emits items from the\n * source Observable with distinct values.\n */\nexport function distinct<T, K>(keySelector?: (value: T) => K, flushes?: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n const distinctKeys = new Set();\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const key = keySelector ? keySelector(value) : value;\n if (!distinctKeys.has(key)) {\n distinctKeys.add(key);\n subscriber.next(value);\n }\n })\n );\n\n flushes && innerFrom(flushes).subscribe(createOperatorSubscriber(subscriber, () => distinctKeys.clear(), noop));\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function distinctUntilChanged<T>(comparator?: (previous: T, current: T) => boolean): MonoTypeOperatorFunction<T>;\nexport function distinctUntilChanged<T, K>(\n comparator: (previous: K, current: K) => boolean,\n keySelector: (value: T) => K\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns a result {@link Observable} that emits all values pushed by the source observable if they\n * are distinct in comparison to the last value the result observable emitted.\n *\n * When provided without parameters or with the first parameter (`{@link distinctUntilChanged#comparator comparator}`),\n * it behaves like this:\n *\n * 1. It will always emit the first value from the source.\n * 2. For all subsequent values pushed by the source, they will be compared to the previously emitted values\n * using the provided `comparator` or an `===` equality check.\n * 3. If the value pushed by the source is determined to be unequal by this check, that value is emitted and\n * becomes the new \"previously emitted value\" internally.\n *\n * When the second parameter (`{@link distinctUntilChanged#keySelector keySelector}`) is provided, the behavior\n * changes:\n *\n * 1. It will always emit the first value from the source.\n * 2. The `keySelector` will be run against all values, including the first value.\n * 3. For all values after the first, the selected key will be compared against the key selected from\n * the previously emitted value using the `comparator`.\n * 4. If the keys are determined to be unequal by this check, the value (not the key), is emitted\n * and the selected key from that value is saved for future comparisons against other keys.\n *\n * ## Examples\n *\n * A very basic example with no `{@link distinctUntilChanged#comparator comparator}`. Note that `1` is emitted more than once,\n * because it's distinct in comparison to the _previously emitted_ value,\n * not in comparison to _all other emitted values_.\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * of(1, 1, 1, 2, 2, 2, 1, 1, 3, 3)\n * .pipe(distinctUntilChanged())\n * .subscribe(console.log);\n * // Logs: 1, 2, 1, 3\n * ```\n *\n * With a `{@link distinctUntilChanged#comparator comparator}`, you can do custom comparisons. Let's say\n * you only want to emit a value when all of its components have\n * changed:\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * const totallyDifferentBuilds$ = of(\n * { engineVersion: '1.1.0', transmissionVersion: '1.2.0' },\n * { engineVersion: '1.1.0', transmissionVersion: '1.4.0' },\n * { engineVersion: '1.3.0', transmissionVersion: '1.4.0' },\n * { engineVersion: '1.3.0', transmissionVersion: '1.5.0' },\n * { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }\n * ).pipe(\n * distinctUntilChanged((prev, curr) => {\n * return (\n * prev.engineVersion === curr.engineVersion ||\n * prev.transmissionVersion === curr.transmissionVersion\n * );\n * })\n * );\n *\n * totallyDifferentBuilds$.subscribe(console.log);\n *\n * // Logs:\n * // { engineVersion: '1.1.0', transmissionVersion: '1.2.0' }\n * // { engineVersion: '1.3.0', transmissionVersion: '1.4.0' }\n * // { engineVersion: '2.0.0', transmissionVersion: '1.5.0' }\n * ```\n *\n * You can also provide a custom `{@link distinctUntilChanged#comparator comparator}` to check that emitted\n * changes are only in one direction. Let's say you only want to get\n * the next record temperature:\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * const temps$ = of(30, 31, 20, 34, 33, 29, 35, 20);\n *\n * const recordHighs$ = temps$.pipe(\n * distinctUntilChanged((prevHigh, temp) => {\n * // If the current temp is less than\n * // or the same as the previous record,\n * // the record hasn't changed.\n * return temp <= prevHigh;\n * })\n * );\n *\n * recordHighs$.subscribe(console.log);\n * // Logs: 30, 31, 34, 35\n * ```\n *\n * Selecting update events only when the `updatedBy` field shows\n * the account changed hands.\n *\n * ```ts\n * import { of, distinctUntilChanged } from 'rxjs';\n *\n * // A stream of updates to a given account\n * const accountUpdates$ = of(\n * { updatedBy: 'blesh', data: [] },\n * { updatedBy: 'blesh', data: [] },\n * { updatedBy: 'ncjamieson', data: [] },\n * { updatedBy: 'ncjamieson', data: [] },\n * { updatedBy: 'blesh', data: [] }\n * );\n *\n * // We only want the events where it changed hands\n * const changedHands$ = accountUpdates$.pipe(\n * distinctUntilChanged(undefined, update => update.updatedBy)\n * );\n *\n * changedHands$.subscribe(console.log);\n * // Logs:\n * // { updatedBy: 'blesh', data: Array[0] }\n * // { updatedBy: 'ncjamieson', data: Array[0] }\n * // { updatedBy: 'blesh', data: Array[0] }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilKeyChanged}\n *\n * @param comparator A function used to compare the previous and current keys for\n * equality. Defaults to a `===` check.\n * @param keySelector Used to select a key value to be passed to the `comparator`.\n *\n * @return A function that returns an Observable that emits items from the\n * source Observable with distinct values.\n */\nexport function distinctUntilChanged<T, K>(\n comparator?: (previous: K, current: K) => boolean,\n keySelector: (value: T) => K = identity as (value: T) => K\n): MonoTypeOperatorFunction<T> {\n // We've been allowing `null` do be passed as the `compare`, so we can't do\n // a default value for the parameter, because that will only work\n // for `undefined`.\n comparator = comparator ?? defaultCompare;\n\n return operate((source, subscriber) => {\n // The previous key, used to compare against keys selected\n // from new arrivals to determine \"distinctiveness\".\n let previousKey: K;\n // Whether or not this is the first value we've gotten.\n let first = true;\n\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // We always call the key selector.\n const currentKey = keySelector(value);\n\n // If it's the first value, we always emit it.\n // Otherwise, we compare this key to the previous key, and\n // if the comparer returns false, we emit.\n if (first || !comparator!(previousKey, currentKey)) {\n // Update our state *before* we emit the value\n // as emission can be the source of re-entrant code\n // in functional libraries like this. We only really\n // need to do this if it's the first value, or if the\n // key we're tracking in previous needs to change.\n first = false;\n previousKey = currentKey;\n\n // Emit the value!\n subscriber.next(value);\n }\n })\n );\n });\n}\n\nfunction defaultCompare(a: any, b: any) {\n return a === b;\n}\n","import { distinctUntilChanged } from './distinctUntilChanged';\nimport { MonoTypeOperatorFunction } from '../types';\n\nexport function distinctUntilKeyChanged<T>(key: keyof T): MonoTypeOperatorFunction<T>;\nexport function distinctUntilKeyChanged<T, K extends keyof T>(key: K, compare: (x: T[K], y: T[K]) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that emits all items emitted by the source Observable that\n * are distinct by comparison from the previous item, using a property accessed by\n * using the key provided to check if the two items are distinct.\n *\n * If a comparator function is provided, then it will be called for each item to\n * test for whether that value should be emitted or not.\n *\n * If a comparator function is not provided, an equality check is used by default.\n *\n * ## Examples\n *\n * An example comparing the name of persons\n *\n * ```ts\n * import { of, distinctUntilKeyChanged } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo' },\n * { age: 7, name: 'Bar' },\n * { age: 5, name: 'Foo' },\n * { age: 6, name: 'Foo' }\n * ).pipe(\n * distinctUntilKeyChanged('name')\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo' }\n * ```\n *\n * An example comparing the first letters of the name\n *\n * ```ts\n * import { of, distinctUntilKeyChanged } from 'rxjs';\n *\n * of(\n * { age: 4, name: 'Foo1' },\n * { age: 7, name: 'Bar' },\n * { age: 5, name: 'Foo2' },\n * { age: 6, name: 'Foo3' }\n * ).pipe(\n * distinctUntilKeyChanged('name', (x, y) => x.substring(0, 3) === y.substring(0, 3))\n * )\n * .subscribe(x => console.log(x));\n *\n * // displays:\n * // { age: 4, name: 'Foo1' }\n * // { age: 7, name: 'Bar' }\n * // { age: 5, name: 'Foo2' }\n * ```\n *\n * @see {@link distinct}\n * @see {@link distinctUntilChanged}\n *\n * @param key String key for object property lookup on each item.\n * @param compare Optional comparison function called to test if an item is distinct\n * from the previous item in the source.\n * @return A function that returns an Observable that emits items from the source\n * Observable with distinct values based on the key specified.\n */\nexport function distinctUntilKeyChanged<T, K extends keyof T>(\n key: K,\n compare?: (x: T[K], y: T[K]) => boolean\n): MonoTypeOperatorFunction<T> {\n return distinctUntilChanged((x: T, y: T) => (compare ? compare(x[key], y[key]) : x[key] === y[key]));\n}\n","import { EmptyError } from '../util/EmptyError';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * If the source observable completes without emitting a value, it will emit\n * an error. The error will be created at that time by the optional\n * `errorFactory` argument, otherwise, the error will be {@link EmptyError}.\n *\n * ![](throwIfEmpty.png)\n *\n * ## Example\n *\n * Throw an error if the document wasn't clicked within 1 second\n *\n * ```ts\n * import { fromEvent, takeUntil, timer, throwIfEmpty } from 'rxjs';\n *\n * const click$ = fromEvent(document, 'click');\n *\n * click$.pipe(\n * takeUntil(timer(1000)),\n * throwIfEmpty(() => new Error('The document was not clicked within 1 second'))\n * )\n * .subscribe({\n * next() {\n * console.log('The document was clicked');\n * },\n * error(err) {\n * console.error(err.message);\n * }\n * });\n * ```\n *\n * @param errorFactory A factory function called to produce the\n * error to be thrown when the source observable completes without emitting a\n * value.\n * @return A function that returns an Observable that throws an error if the\n * source Observable completed without emitting.\n */\nexport function throwIfEmpty<T>(errorFactory: () => any = defaultErrorFactory): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n hasValue = true;\n subscriber.next(value);\n },\n () => (hasValue ? subscriber.complete() : subscriber.error(errorFactory()))\n )\n );\n });\n}\n\nfunction defaultErrorFactory() {\n return new EmptyError();\n}\n","import { ArgumentOutOfRangeError } from '../util/ArgumentOutOfRangeError';\nimport { Observable } from '../Observable';\nimport { OperatorFunction } from '../types';\nimport { filter } from './filter';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { take } from './take';\n\n/**\n * Emits the single value at the specified `index` in a sequence of emissions\n * from the source Observable.\n *\n * <span class=\"informal\">Emits only the i-th value, then completes.</span>\n *\n * ![](elementAt.png)\n *\n * `elementAt` returns an Observable that emits the item at the specified\n * `index` in the source Observable, or a default value if that `index` is out\n * of range and the `default` argument is provided. If the `default` argument is\n * not given and the `index` is out of range, the output Observable will emit an\n * `ArgumentOutOfRangeError` error.\n *\n * ## Example\n *\n * Emit only the third click event\n *\n * ```ts\n * import { fromEvent, elementAt } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(elementAt(2));\n * result.subscribe(x => console.log(x));\n *\n * // Results in:\n * // click 1 = nothing\n * // click 2 = nothing\n * // click 3 = MouseEvent object logged to console\n * ```\n *\n * @see {@link first}\n * @see {@link last}\n * @see {@link skip}\n * @see {@link single}\n * @see {@link take}\n *\n * @throws {ArgumentOutOfRangeError} When using `elementAt(i)`, it delivers an\n * `ArgumentOutOfRangeError` to the Observer's `error` callback if `i < 0` or the\n * Observable has completed before emitting the i-th `next` notification.\n *\n * @param index Is the number `i` for the i-th source emission that has happened\n * since the subscription, starting from the number `0`.\n * @param defaultValue The default value returned for missing indices.\n * @return A function that returns an Observable that emits a single item, if\n * it is found. Otherwise, it will emit the default value if given. If not, it\n * emits an error.\n */\nexport function elementAt<T, D = T>(index: number, defaultValue?: D): OperatorFunction<T, T | D> {\n if (index < 0) {\n throw new ArgumentOutOfRangeError();\n }\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n filter((v, i) => i === index),\n take(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new ArgumentOutOfRangeError())\n );\n}\n","/** prettier */\nimport { Observable } from '../Observable';\nimport { concat } from '../observable/concat';\nimport { of } from '../observable/of';\nimport { MonoTypeOperatorFunction, SchedulerLike, OperatorFunction, ValueFromArray } from '../types';\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function endWith<T>(scheduler: SchedulerLike): MonoTypeOperatorFunction<T>;\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function endWith<T, A extends unknown[] = T[]>(\n ...valuesAndScheduler: [...A, SchedulerLike]\n): OperatorFunction<T, T | ValueFromArray<A>>;\n\nexport function endWith<T, A extends unknown[] = T[]>(...values: A): OperatorFunction<T, T | ValueFromArray<A>>;\n\n/**\n * Returns an observable that will emit all values from the source, then synchronously emit\n * the provided value(s) immediately after the source completes.\n *\n * NOTE: Passing a last argument of a Scheduler is _deprecated_, and may result in incorrect\n * types in TypeScript.\n *\n * This is useful for knowing when an observable ends. Particularly when paired with an\n * operator like {@link takeUntil}\n *\n * ![](endWith.png)\n *\n * ## Example\n *\n * Emit values to know when an interval starts and stops. The interval will\n * stop when a user clicks anywhere on the document.\n *\n * ```ts\n * import { interval, map, fromEvent, startWith, takeUntil, endWith } from 'rxjs';\n *\n * const ticker$ = interval(5000).pipe(\n * map(() => 'tick')\n * );\n *\n * const documentClicks$ = fromEvent(document, 'click');\n *\n * ticker$.pipe(\n * startWith('interval started'),\n * takeUntil(documentClicks$),\n * endWith('interval ended by click')\n * )\n * .subscribe(x => console.log(x));\n *\n * // Result (assuming a user clicks after 15 seconds)\n * // 'interval started'\n * // 'tick'\n * // 'tick'\n * // 'tick'\n * // 'interval ended by click'\n * ```\n *\n * @see {@link startWith}\n * @see {@link concat}\n * @see {@link takeUntil}\n *\n * @param values Items you want the modified Observable to emit last.\n * @return A function that returns an Observable that emits all values from the\n * source, then synchronously emits the provided value(s) immediately after the\n * source completes.\n */\nexport function endWith<T>(...values: Array<T | SchedulerLike>): MonoTypeOperatorFunction<T> {\n return (source: Observable<T>) => concat(source, of(...values)) as Observable<T>;\n}\n","import { Observable } from '../Observable';\nimport { Falsy, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function every<T>(predicate: BooleanConstructor): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function every<T>(\n predicate: BooleanConstructor,\n thisArg: any\n): OperatorFunction<T, Exclude<T, Falsy> extends never ? false : boolean>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function every<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, boolean>;\nexport function every<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, boolean>;\n\n/**\n * Returns an Observable that emits whether or not every item of the source satisfies the condition specified.\n *\n * <span class=\"informal\">If all values pass predicate before the source completes, emits true before completion,\n * otherwise emit false, then complete.</span>\n *\n * ![](every.png)\n *\n * ## Example\n *\n * A simple example emitting true if all elements are less than 5, false otherwise\n *\n * ```ts\n * import { of, every } from 'rxjs';\n *\n * of(1, 2, 3, 4, 5, 6)\n * .pipe(every(x => x < 5))\n * .subscribe(x => console.log(x)); // -> false\n * ```\n *\n * @param predicate A function for determining if an item meets a specified condition.\n * @param thisArg Optional object to use for `this` in the callback.\n * @return A function that returns an Observable of booleans that determines if\n * all items of the source Observable meet the condition specified.\n */\nexport function every<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n if (!predicate.call(thisArg, value, index++, source)) {\n subscriber.next(false);\n subscriber.complete();\n }\n },\n () => {\n subscriber.next(true);\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { map } from './map';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/* tslint:disable:max-line-length */\nexport function exhaustMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function exhaustMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function exhaustMap<T, I, R>(\n project: (value: T, index: number) => ObservableInput<I>,\n resultSelector: (outerValue: T, innerValue: I, outerIndex: number, innerIndex: number) => R\n): 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 only if the previous projected Observable has completed.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link exhaustAll}.</span>\n *\n * ![](exhaustMap.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. When it projects a source value to\n * an Observable, the output Observable begins emitting the items emitted by\n * that projected Observable. However, `exhaustMap` ignores every new projected\n * Observable if the previous projected Observable has not yet completed. Once\n * that one completes, it will accept and flatten the next projected Observable\n * and repeat this process.\n *\n * ## Example\n *\n * Run a finite timer for each click, only if there is no currently active timer\n *\n * ```ts\n * import { fromEvent, exhaustMap, interval, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * exhaustMap(() => interval(1000).pipe(take(5)))\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaust}\n * @see {@link mergeMap}\n * @see {@link switchMap}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable containing projected\n * Observables of each item of the source, ignoring projected Observables that\n * start before their preceding Observable has completed.\n */\nexport function exhaustMap<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 if (resultSelector) {\n // DEPRECATED PATH\n return (source: Observable<T>) =>\n source.pipe(exhaustMap((a, i) => innerFrom(project(a, i)).pipe(map((b: any, ii: any) => resultSelector(a, b, i, ii)))));\n }\n return operate((source, subscriber) => {\n let index = 0;\n let innerSub: Subscriber<T> | null = null;\n let isComplete = false;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (outerValue) => {\n if (!innerSub) {\n innerSub = createOperatorSubscriber(subscriber, undefined, () => {\n innerSub = null;\n isComplete && subscriber.complete();\n });\n innerFrom(project(outerValue, index++)).subscribe(innerSub);\n }\n },\n () => {\n isComplete = true;\n !innerSub && subscriber.complete();\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { exhaustMap } from './exhaustMap';\nimport { identity } from '../util/identity';\n\n/**\n * Converts a higher-order Observable into a first-order Observable by dropping\n * inner Observables while the previous inner Observable has not yet completed.\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables by dropping the\n * next inner Observables while the current inner is still executing.</span>\n *\n * ![](exhaustAll.svg)\n *\n * `exhaustAll` subscribes to an Observable that emits Observables, also known as a\n * higher-order Observable. Each time it observes one of these emitted inner\n * Observables, the output Observable begins emitting the items emitted by that\n * inner Observable. So far, it behaves like {@link mergeAll}. However,\n * `exhaustAll` ignores every new inner Observable if the previous Observable has\n * not yet completed. Once that one completes, it will accept and flatten the\n * next inner Observable and repeat this process.\n *\n * ## Example\n *\n * Run a finite timer for each click, only if there is no currently active timer\n *\n * ```ts\n * import { fromEvent, map, interval, take, exhaustAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const higherOrder = clicks.pipe(\n * map(() => interval(1000).pipe(take(5)))\n * );\n * const result = higherOrder.pipe(exhaustAll());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeAll}\n * @see {@link exhaustMap}\n * @see {@link zipAll}\n *\n * @return A function that returns an Observable that takes a source of\n * Observables and propagates the first Observable exclusively until it\n * completes before subscribing to the next.\n */\nexport function exhaustAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return exhaustMap(identity);\n}\n","import { exhaustAll } from './exhaustAll';\n\n/**\n * @deprecated Renamed to {@link exhaustAll}. Will be removed in v8.\n */\nexport const exhaust = exhaustAll;\n","import { OperatorFunction, ObservableInput, ObservedValueOf, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\n\n/* tslint:disable:max-line-length */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent?: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>>;\n/**\n * @deprecated The `scheduler` parameter will be removed in v8. If you need to schedule the inner subscription,\n * use `subscribeOn` within the projection function: `expand((value) => fn(value).pipe(subscribeOn(scheduler)))`.\n * Details: Details: https://rxjs.dev/deprecations/scheduler-argument\n */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent: number | undefined,\n scheduler: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>>;\n/* tslint:enable:max-line-length */\n\n/**\n * Recursively projects each source value to an Observable which is merged in\n * the output Observable.\n *\n * <span class=\"informal\">It's similar to {@link mergeMap}, but applies the\n * projection function to every source value as well as every output value.\n * It's recursive.</span>\n *\n * ![](expand.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. *Expand* will re-emit on the output\n * Observable every source value. Then, each output value is given to the\n * `project` function which returns an inner Observable to be merged on the\n * output Observable. Those output values resulting from the projection are also\n * given to the `project` function to produce new output values. This is how\n * *expand* behaves recursively.\n *\n * ## Example\n *\n * Start emitting the powers of two on every click, at most 10 of them\n *\n * ```ts\n * import { fromEvent, map, expand, of, delay, take } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const powersOfTwo = clicks.pipe(\n * map(() => 1),\n * expand(x => of(2 * x).pipe(delay(1000))),\n * take(10)\n * );\n * powersOfTwo.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n *\n * @param project A function that, when applied to an item emitted by the source\n * or the output Observable, returns an Observable.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @param scheduler The {@link SchedulerLike} to use for subscribing to\n * each projected inner Observable.\n * @return A function that returns an Observable that emits the source values\n * and also result of applying the projection function to each value emitted on\n * the output Observable and merging the results of the Observables obtained\n * from this transformation.\n */\nexport function expand<T, O extends ObservableInput<unknown>>(\n project: (value: T, index: number) => O,\n concurrent = Infinity,\n scheduler?: SchedulerLike\n): OperatorFunction<T, ObservedValueOf<O>> {\n concurrent = (concurrent || 0) < 1 ? Infinity : concurrent;\n return operate((source, subscriber) =>\n mergeInternals(\n // General merge params\n source,\n subscriber,\n project,\n concurrent,\n\n // onBeforeNext\n undefined,\n\n // Expand-specific\n true, // Use expand path\n scheduler // Inner subscription scheduler\n )\n );\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\n\n/**\n * Returns an Observable that mirrors the source Observable, but will call a specified function when\n * the source terminates on complete or error.\n * The specified function will also be called when the subscriber explicitly unsubscribes.\n *\n * ## Examples\n *\n * Execute callback function when the observable completes\n *\n * ```ts\n * import { interval, take, finalize } from 'rxjs';\n *\n * // emit value in sequence every 1 second\n * const source = interval(1000);\n * const example = source.pipe(\n * take(5), //take only the first 5 values\n * finalize(() => console.log('Sequence complete')) // Execute when the observable completes\n * );\n * const subscribe = example.subscribe(val => console.log(val));\n *\n * // results:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 'Sequence complete'\n * ```\n *\n * Execute callback function when the subscriber explicitly unsubscribes\n *\n * ```ts\n * import { interval, finalize, tap, noop, timer } from 'rxjs';\n *\n * const source = interval(100).pipe(\n * finalize(() => console.log('[finalize] Called')),\n * tap({\n * next: () => console.log('[next] Called'),\n * error: () => console.log('[error] Not called'),\n * complete: () => console.log('[tap complete] Not called')\n * })\n * );\n *\n * const sub = source.subscribe({\n * next: x => console.log(x),\n * error: noop,\n * complete: () => console.log('[complete] Not called')\n * });\n *\n * timer(150).subscribe(() => sub.unsubscribe());\n *\n * // results:\n * // '[next] Called'\n * // 0\n * // '[finalize] Called'\n * ```\n *\n * @param callback Function to be called when source terminates.\n * @return A function that returns an Observable that mirrors the source, but\n * will call the specified function on termination.\n */\nexport function finalize<T>(callback: () => void): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n // TODO: This try/finally was only added for `useDeprecatedSynchronousErrorHandling`.\n // REMOVE THIS WHEN THAT HOT GARBAGE IS REMOVED IN V8.\n try {\n source.subscribe(subscriber);\n } finally {\n subscriber.add(callback);\n }\n });\n}\n","import { Observable } from '../Observable';\nimport { Subscriber } from '../Subscriber';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function find<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function find<T, S extends T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => value is S,\n thisArg: A\n): OperatorFunction<T, S | undefined>;\nexport function find<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S\n): OperatorFunction<T, S | undefined>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function find<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, T | undefined>;\nexport function find<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, T | undefined>;\n/**\n * Emits only the first value emitted by the source Observable that meets some\n * condition.\n *\n * <span class=\"informal\">Finds the first value that passes some test and emits\n * that.</span>\n *\n * ![](find.png)\n *\n * `find` searches for the first item in the source Observable that matches the\n * specified condition embodied by the `predicate`, and returns the first\n * occurrence in the source. Unlike {@link first}, the `predicate` is required\n * in `find`, and does not emit an error if a valid value is not found\n * (emits `undefined` instead).\n *\n * ## Example\n *\n * Find and emit the first click that happens on a DIV element\n *\n * ```ts\n * import { fromEvent, find } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(find(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link first}\n * @see {@link findIndex}\n * @see {@link take}\n *\n * @param predicate A function called with each item to test for condition matching.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return A function that returns an Observable that emits the first item that\n * matches the condition.\n */\nexport function find<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, T | undefined> {\n return operate(createFind(predicate, thisArg, 'value'));\n}\n\nexport function createFind<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg: any,\n emit: 'value' | 'index'\n) {\n const findIndex = emit === 'index';\n return (source: Observable<T>, subscriber: Subscriber<any>) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n const i = index++;\n if (predicate.call(thisArg, value, i, source)) {\n subscriber.next(findIndex ? i : value);\n subscriber.complete();\n }\n },\n () => {\n subscriber.next(findIndex ? -1 : undefined);\n subscriber.complete();\n }\n )\n );\n };\n}\n","import { Observable } from '../Observable';\nimport { Falsy, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createFind } from './find';\n\nexport function findIndex<T>(predicate: BooleanConstructor): OperatorFunction<T, T extends Falsy ? -1 : number>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function findIndex<T>(predicate: BooleanConstructor, thisArg: any): OperatorFunction<T, T extends Falsy ? -1 : number>;\n/** @deprecated Use a closure instead of a `thisArg`. Signatures accepting a `thisArg` will be removed in v8. */\nexport function findIndex<T, A>(\n predicate: (this: A, value: T, index: number, source: Observable<T>) => boolean,\n thisArg: A\n): OperatorFunction<T, number>;\nexport function findIndex<T>(predicate: (value: T, index: number, source: Observable<T>) => boolean): OperatorFunction<T, number>;\n\n/**\n * Emits only the index of the first value emitted by the source Observable that\n * meets some condition.\n *\n * <span class=\"informal\">It's like {@link find}, but emits the index of the\n * found value, not the value itself.</span>\n *\n * ![](findIndex.png)\n *\n * `findIndex` searches for the first item in the source Observable that matches\n * the specified condition embodied by the `predicate`, and returns the\n * (zero-based) index of the first occurrence in the source. Unlike\n * {@link first}, the `predicate` is required in `findIndex`, and does not emit\n * an error if a valid value is not found.\n *\n * ## Example\n *\n * Emit the index of first click that happens on a DIV element\n *\n * ```ts\n * import { fromEvent, findIndex } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(findIndex(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link first}\n * @see {@link take}\n *\n * @param predicate A function called with each item to test for condition matching.\n * @param thisArg An optional argument to determine the value of `this` in the\n * `predicate` function.\n * @return A function that returns an Observable that emits the index of the\n * first item that matches the condition.\n */\nexport function findIndex<T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n thisArg?: any\n): OperatorFunction<T, number> {\n return operate(createFind(predicate, thisArg, 'index'));\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { filter } from './filter';\nimport { take } from './take';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { identity } from '../util/identity';\n\nexport function first<T, D = T>(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>;\nexport function first<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function first<T, D>(predicate: BooleanConstructor, defaultValue: D): OperatorFunction<T, TruthyTypesOf<T> | D>;\nexport function first<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue?: S\n): OperatorFunction<T, S>;\nexport function first<T, S extends T, D>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue: D\n): OperatorFunction<T, S | D>;\nexport function first<T, D = T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n defaultValue?: D\n): OperatorFunction<T, T | D>;\n\n/**\n * Emits only the first value (or the first value that meets some condition)\n * emitted by the source Observable.\n *\n * <span class=\"informal\">Emits only the first value. Or emits only the first\n * value that passes some test.</span>\n *\n * ![](first.png)\n *\n * If called with no arguments, `first` emits the first value of the source\n * Observable, then completes. If called with a `predicate` function, `first`\n * emits the first value of the source that matches the specified condition. Emits an error\n * notification if `defaultValue` was not provided and a matching element is not found.\n *\n * ## Examples\n *\n * Emit only the first click that happens on the DOM\n *\n * ```ts\n * import { fromEvent, first } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first());\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Emits the first click that happens on a DIV\n *\n * ```ts\n * import { fromEvent, first } from 'rxjs';\n *\n * const div = document.createElement('div');\n * div.style.cssText = 'width: 200px; height: 200px; background: #09c;';\n * document.body.appendChild(div);\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(first(ev => (<HTMLElement>ev.target).tagName === 'DIV'));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link filter}\n * @see {@link find}\n * @see {@link take}\n * @see {@link last}\n *\n * @throws {EmptyError} Delivers an `EmptyError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * This is how `first()` is different from `take(1)` which completes instead.\n *\n * @param predicate An optional function called with each item to test for condition\n * matching.\n * @param defaultValue The default value emitted in case no valid value was found on\n * the source.\n * @return A function that returns an Observable that emits the first item that\n * matches the condition.\n */\nexport function first<T, D>(\n predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n defaultValue?: D\n): OperatorFunction<T, T | D> {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n take(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new EmptyError())\n );\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { ObservableInput, Observer, OperatorFunction, SubjectLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber, OperatorSubscriber } from './OperatorSubscriber';\n\nexport interface BasicGroupByOptions<K, T> {\n element?: undefined;\n duration?: (grouped: GroupedObservable<K, T>) => ObservableInput<any>;\n connector?: () => SubjectLike<T>;\n}\n\nexport interface GroupByOptionsWithElement<K, E, T> {\n element: (value: T) => E;\n duration?: (grouped: GroupedObservable<K, E>) => ObservableInput<any>;\n connector?: () => SubjectLike<E>;\n}\n\nexport function groupBy<T, K>(key: (value: T) => K, options: BasicGroupByOptions<K, T>): OperatorFunction<T, GroupedObservable<K, T>>;\n\nexport function groupBy<T, K, E>(\n key: (value: T) => K,\n options: GroupByOptionsWithElement<K, E, T>\n): OperatorFunction<T, GroupedObservable<K, E>>;\n\nexport function groupBy<T, K extends T>(\n key: (value: T) => value is K\n): OperatorFunction<T, GroupedObservable<true, K> | GroupedObservable<false, Exclude<T, K>>>;\n\nexport function groupBy<T, K>(key: (value: T) => K): OperatorFunction<T, GroupedObservable<K, T>>;\n\n/**\n * @deprecated use the options parameter instead.\n */\nexport function groupBy<T, K>(\n key: (value: T) => K,\n element: void,\n duration: (grouped: GroupedObservable<K, T>) => Observable<any>\n): OperatorFunction<T, GroupedObservable<K, T>>;\n\n/**\n * @deprecated use the options parameter instead.\n */\nexport function groupBy<T, K, R>(\n key: (value: T) => K,\n element?: (value: T) => R,\n duration?: (grouped: GroupedObservable<K, R>) => Observable<any>\n): OperatorFunction<T, GroupedObservable<K, R>>;\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 key function.\n *\n * If a {@link GroupedObservable} for this key exists, this {@link GroupedObservable} emits. Otherwise, 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 element function.\n *\n * ## Examples\n *\n * Group objects by `id` and return as array\n *\n * ```ts\n * import { of, groupBy, mergeMap, reduce } from 'rxjs';\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' }, { id: 1, name: 'TypeScript'}]\n * // [{ id: 2, name: 'Parcel' }, { id: 2, name: 'webpack'}]\n * // [{ id: 3, name: 'TSLint' }]\n * ```\n *\n * Pivot data on the `id` field\n *\n * ```ts\n * import { of, groupBy, mergeMap, reduce, map } from 'rxjs';\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, { element: p => p.name }),\n * mergeMap(group$ => group$.pipe(reduce((acc, cur) => [...acc, cur], [`${ group$.key }`]))),\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 key A function that extracts the key\n * for each item.\n * @param element A function that extracts the\n * return element for each item.\n * @param duration\n * A function that returns an Observable to determine how long each group should\n * exist.\n * @param connector Factory function to create an\n * intermediate Subject through which grouped elements are emitted.\n * @return A function that returns an Observable that emits GroupedObservables,\n * each of which corresponds to a unique key value and each of which emits\n * those items from the source Observable that share that key value.\n *\n * @deprecated Use the options parameter instead.\n */\nexport function groupBy<T, K, R>(\n key: (value: T) => K,\n element?: (value: T) => R,\n duration?: (grouped: GroupedObservable<K, R>) => Observable<any>,\n connector?: () => Subject<R>\n): OperatorFunction<T, GroupedObservable<K, R>>;\n\n// Impl\nexport function groupBy<T, K, R>(\n keySelector: (value: T) => K,\n elementOrOptions?: ((value: any) => any) | void | BasicGroupByOptions<K, T> | GroupByOptionsWithElement<K, R, T>,\n duration?: (grouped: GroupedObservable<any, any>) => ObservableInput<any>,\n connector?: () => SubjectLike<any>\n): OperatorFunction<T, GroupedObservable<K, R>> {\n return operate((source, subscriber) => {\n let element: ((value: any) => any) | void;\n if (!elementOrOptions || typeof elementOrOptions === 'function') {\n element = elementOrOptions as ((value: any) => any);\n } else {\n ({ duration, element, connector } = elementOrOptions);\n }\n\n // A lookup for the groups that we have so far.\n const groups = new Map<K, SubjectLike<any>>();\n\n // Used for notifying all groups and the subscriber in the same way.\n const notify = (cb: (group: Observer<any>) => void) => {\n groups.forEach(cb);\n cb(subscriber);\n };\n\n // Used to handle errors from the source, AND errors that occur during the\n // next call from the source.\n const handleError = (err: any) => notify((consumer) => consumer.error(err));\n\n // The number of actively subscribed groups\n let activeGroups = 0;\n\n // Whether or not teardown was attempted on this subscription.\n let teardownAttempted = false;\n\n // Capturing a reference to this, because we need a handle to it\n // in `createGroupedObservable` below. This is what we use to\n // subscribe to our source observable. This sometimes needs to be unsubscribed\n // out-of-band with our `subscriber` which is the downstream subscriber, or destination,\n // in cases where a user unsubscribes from the main resulting subscription, but\n // still has groups from this subscription subscribed and would expect values from it\n // Consider: `source.pipe(groupBy(fn), take(2))`.\n const groupBySourceSubscriber = new OperatorSubscriber(\n subscriber,\n (value: T) => {\n // Because we have to notify all groups of any errors that occur in here,\n // we have to add our own try/catch to ensure that those errors are propagated.\n // OperatorSubscriber will only send the error to the main subscriber.\n try {\n const key = keySelector(value);\n\n let group = groups.get(key);\n if (!group) {\n // Create our group subject\n groups.set(key, (group = connector ? connector() : new Subject<any>()));\n\n // Emit the grouped observable. Note that we can't do a simple `asObservable()` here,\n // because the grouped observable has special semantics around reference counting\n // to ensure we don't sever our connection to the source prematurely.\n const grouped = createGroupedObservable(key, group);\n subscriber.next(grouped);\n\n if (duration) {\n const durationSubscriber = createOperatorSubscriber(\n // Providing the group here ensures that it is disposed of -- via `unsubscribe` --\n // when the duration subscription is torn down. That is important, because then\n // if someone holds a handle to the grouped observable and tries to subscribe to it\n // after the connection to the source has been severed, they will get an\n // `ObjectUnsubscribedError` and know they can't possibly get any notifications.\n group as any,\n () => {\n // Our duration notified! We can complete the group.\n // The group will be removed from the map in the finalization phase.\n group!.complete();\n durationSubscriber?.unsubscribe();\n },\n // Completions are also sent to the group, but just the group.\n undefined,\n // Errors on the duration subscriber are sent to the group\n // but only the group. They are not sent to the main subscription.\n undefined,\n // Finalization: Remove this group from our map.\n () => groups.delete(key)\n );\n\n // Start our duration notifier.\n groupBySourceSubscriber.add(innerFrom(duration(grouped)).subscribe(durationSubscriber));\n }\n }\n\n // Send the value to our group.\n group.next(element ? element(value) : value);\n } catch (err) {\n handleError(err);\n }\n },\n // Source completes.\n () => notify((consumer) => consumer.complete()),\n // Error from the source.\n handleError,\n // Free up memory.\n // When the source subscription is _finally_ torn down, release the subjects and keys\n // in our groups Map, they may be quite large and we don't want to keep them around if we\n // don't have to.\n () => groups.clear(),\n () => {\n teardownAttempted = true;\n // We only kill our subscription to the source if we have\n // no active groups. As stated above, consider this scenario:\n // source$.pipe(groupBy(fn), take(2)).\n return activeGroups === 0;\n }\n );\n\n // Subscribe to the source\n source.subscribe(groupBySourceSubscriber);\n\n /**\n * Creates the actual grouped observable returned.\n * @param key The key of the group\n * @param groupSubject The subject that fuels the group\n */\n function createGroupedObservable(key: K, groupSubject: SubjectLike<any>) {\n const result: any = new Observable<T>((groupSubscriber) => {\n activeGroups++;\n const innerSub = groupSubject.subscribe(groupSubscriber);\n return () => {\n innerSub.unsubscribe();\n // We can kill the subscription to our source if we now have no more\n // active groups subscribed, and a finalization was already attempted on\n // the source.\n --activeGroups === 0 && teardownAttempted && groupBySourceSubscriber.unsubscribe();\n };\n });\n result.key = key;\n return result;\n }\n });\n}\n\n/**\n * An observable of values that is the emitted by the result of a {@link groupBy} operator,\n * contains a `key` property for the grouping.\n */\nexport interface GroupedObservable<K, T> extends Observable<T> {\n /**\n * The key value for the grouped notifications.\n */\n readonly key: K;\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits `false` if the input Observable emits any values, or emits `true` if the\n * input Observable completes without emitting any values.\n *\n * <span class=\"informal\">Tells whether any values are emitted by an Observable.</span>\n *\n * ![](isEmpty.png)\n *\n * `isEmpty` transforms an Observable that emits values into an Observable that\n * emits a single boolean value representing whether or not any values were\n * emitted by the source Observable. As soon as the source Observable emits a\n * value, `isEmpty` will emit a `false` and complete. If the source Observable\n * completes having not emitted anything, `isEmpty` will emit a `true` and\n * complete.\n *\n * A similar effect could be achieved with {@link count}, but `isEmpty` can emit\n * a `false` value sooner.\n *\n * ## Examples\n *\n * Emit `false` for a non-empty Observable\n *\n * ```ts\n * import { Subject, isEmpty } from 'rxjs';\n *\n * const source = new Subject<string>();\n * const result = source.pipe(isEmpty());\n *\n * source.subscribe(x => console.log(x));\n * result.subscribe(x => console.log(x));\n *\n * source.next('a');\n * source.next('b');\n * source.next('c');\n * source.complete();\n *\n * // Outputs\n * // 'a'\n * // false\n * // 'b'\n * // 'c'\n * ```\n *\n * Emit `true` for an empty Observable\n *\n * ```ts\n * import { EMPTY, isEmpty } from 'rxjs';\n *\n * const result = EMPTY.pipe(isEmpty());\n * result.subscribe(x => console.log(x));\n *\n * // Outputs\n * // true\n * ```\n *\n * @see {@link count}\n * @see {@link EMPTY}\n *\n * @return A function that returns an Observable that emits boolean value\n * indicating whether the source Observable was empty or not.\n */\nexport function isEmpty<T>(): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n subscriber.next(false);\n subscriber.complete();\n },\n () => {\n subscriber.next(true);\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { EMPTY } from '../observable/empty';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Waits for the source to complete, then emits the last N values from the source,\n * as specified by the `count` argument.\n *\n * ![](takeLast.png)\n *\n * `takeLast` results in an observable that will hold values up to `count` values in memory,\n * until the source completes. It then pushes all values in memory to the consumer, in the\n * order they were received from the source, then notifies the consumer that it is\n * complete.\n *\n * If for some reason the source completes before the `count` supplied to `takeLast` is reached,\n * all values received until that point are emitted, and then completion is notified.\n *\n * **Warning**: Using `takeLast` with an observable that never completes will result\n * in an observable that never emits a value.\n *\n * ## Example\n *\n * Take the last 3 values of an Observable with many values\n *\n * ```ts\n * import { range, takeLast } from 'rxjs';\n *\n * const many = range(1, 100);\n * const lastThree = many.pipe(takeLast(3));\n * lastThree.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeUntil}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param count The maximum number of values to emit from the end of\n * the sequence of values emitted by the source Observable.\n * @return A function that returns an Observable that emits at most the last\n * `count` values emitted by the source Observable.\n */\nexport function takeLast<T>(count: number): MonoTypeOperatorFunction<T> {\n return count <= 0\n ? () => EMPTY\n : operate((source, subscriber) => {\n // This buffer will hold the values we are going to emit\n // when the source completes. Since we only want to take the\n // last N values, we can't emit until we're sure we're not getting\n // any more values.\n let buffer: T[] = [];\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Add the most recent value onto the end of our buffer.\n buffer.push(value);\n // If our buffer is now larger than the number of values we\n // want to take, we remove the oldest value from the buffer.\n count < buffer.length && buffer.shift();\n },\n () => {\n // The source completed, we now know what are last values\n // are, emit them in the order they were received.\n for (const value of buffer) {\n subscriber.next(value);\n }\n subscriber.complete();\n },\n // Errors are passed through to the consumer\n undefined,\n () => {\n // During finalization release the values in our buffer.\n buffer = null!;\n }\n )\n );\n });\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\nimport { OperatorFunction, TruthyTypesOf } from '../types';\nimport { filter } from './filter';\nimport { takeLast } from './takeLast';\nimport { throwIfEmpty } from './throwIfEmpty';\nimport { defaultIfEmpty } from './defaultIfEmpty';\nimport { identity } from '../util/identity';\n\nexport function last<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function last<T, D>(predicate: BooleanConstructor, defaultValue: D): OperatorFunction<T, TruthyTypesOf<T> | D>;\nexport function last<T, D = T>(predicate?: null, defaultValue?: D): OperatorFunction<T, T | D>;\nexport function last<T, S extends T>(\n predicate: (value: T, index: number, source: Observable<T>) => value is S,\n defaultValue?: S\n): OperatorFunction<T, S>;\nexport function last<T, D = T>(\n predicate: (value: T, index: number, source: Observable<T>) => boolean,\n defaultValue?: D\n): OperatorFunction<T, T | D>;\n\n/**\n * Returns an Observable that emits only the last item emitted by the source Observable.\n * It optionally takes a predicate function as a parameter, in which case, rather than emitting\n * the last item from the source Observable, the resulting Observable will emit the last item\n * from the source Observable that satisfies the predicate.\n *\n * ![](last.png)\n *\n * It will emit an error notification if the source completes without notification or one that matches\n * the predicate. It returns the last value or if a predicate is provided last value that matches the\n * predicate. It returns the given default value if no notification is emitted or matches the predicate.\n *\n * ## Examples\n *\n * Last alphabet from the sequence\n *\n * ```ts\n * import { from, last } from 'rxjs';\n *\n * const source = from(['x', 'y', 'z']);\n * const result = source.pipe(last());\n *\n * result.subscribe(value => console.log(`Last alphabet: ${ value }`));\n *\n * // Outputs\n * // Last alphabet: z\n * ```\n *\n * Default value when the value in the predicate is not matched\n *\n * ```ts\n * import { from, last } from 'rxjs';\n *\n * const source = from(['x', 'y', 'z']);\n * const result = source.pipe(last(char => char === 'a', 'not found'));\n *\n * result.subscribe(value => console.log(`'a' is ${ value }.`));\n *\n * // Outputs\n * // 'a' is not found.\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n * @see {@link skipWhile}\n * @see {@link first}\n *\n * @throws {EmptyError} Delivers an `EmptyError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n *\n * @param predicate The condition any source emitted item has to satisfy.\n * @param defaultValue An optional default value to provide if last `predicate`\n * isn't met or no values were emitted.\n * @return A function that returns an Observable that emits only the last item\n * satisfying the given condition from the source, or an error notification\n * with an `EmptyError` object if no such items are emitted.\n */\nexport function last<T, D>(\n predicate?: ((value: T, index: number, source: Observable<T>) => boolean) | null,\n defaultValue?: D\n): OperatorFunction<T, T | D> {\n const hasDefaultValue = arguments.length >= 2;\n return (source: Observable<T>) =>\n source.pipe(\n predicate ? filter((v, i) => predicate(v, i, source)) : identity,\n takeLast(1),\n hasDefaultValue ? defaultIfEmpty(defaultValue!) : throwIfEmpty(() => new EmptyError())\n );\n}\n","import { Notification } from '../Notification';\nimport { OperatorFunction, ObservableNotification } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Represents all of the notifications from the source Observable as `next`\n * emissions marked with their original types within {@link Notification}\n * objects.\n *\n * <span class=\"informal\">Wraps `next`, `error` and `complete` emissions in\n * {@link Notification} objects, emitted as `next` on the output Observable.\n * </span>\n *\n * ![](materialize.png)\n *\n * `materialize` returns an Observable that emits a `next` notification for each\n * `next`, `error`, or `complete` emission of the source Observable. When the\n * source Observable emits `complete`, the output Observable will emit `next` as\n * a Notification of type \"complete\", and then it will emit `complete` as well.\n * When the source Observable emits `error`, the output will emit `next` as a\n * Notification of type \"error\", and then `complete`.\n *\n * This operator is useful for producing metadata of the source Observable, to\n * be consumed as `next` emissions. Use it in conjunction with\n * {@link dematerialize}.\n *\n * ## Example\n *\n * Convert a faulty Observable to an Observable of Notifications\n *\n * ```ts\n * import { of, materialize, map } from 'rxjs';\n *\n * const letters = of('a', 'b', 13, 'd');\n * const upperCase = letters.pipe(map((x: any) => x.toUpperCase()));\n * const materialized = upperCase.pipe(materialize());\n *\n * materialized.subscribe(x => console.log(x));\n *\n * // Results in the following:\n * // - Notification { kind: 'N', value: 'A', error: undefined, hasValue: true }\n * // - Notification { kind: 'N', value: 'B', error: undefined, hasValue: true }\n * // - Notification { kind: 'E', value: undefined, error: TypeError { message: x.toUpperCase is not a function }, hasValue: false }\n * ```\n *\n * @see {@link Notification}\n * @see {@link dematerialize}\n *\n * @return A function that returns an Observable that emits\n * {@link Notification} objects that wrap the original emissions from the\n * source Observable with metadata.\n */\nexport function materialize<T>(): OperatorFunction<T, Notification<T> & ObservableNotification<T>> {\n return operate((source, subscriber) => {\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n subscriber.next(Notification.createNext(value));\n },\n () => {\n subscriber.next(Notification.createComplete());\n subscriber.complete();\n },\n (err) => {\n subscriber.next(Notification.createError(err));\n subscriber.complete();\n }\n )\n );\n });\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * The `max` operator operates on an Observable that emits numbers (or items that\n * can be compared with a provided function), and when source Observable completes\n * it emits a single item: the item with the largest value.\n *\n * ![](max.png)\n *\n * ## Examples\n *\n * Get the maximal value of a series of numbers\n *\n * ```ts\n * import { of, max } from 'rxjs';\n *\n * of(5, 4, 7, 2, 8)\n * .pipe(max())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 8\n * ```\n *\n * Use a comparer function to get the maximal item\n *\n * ```ts\n * import { of, max } from 'rxjs';\n *\n * of(\n * { age: 7, name: 'Foo' },\n * { age: 5, name: 'Bar' },\n * { age: 9, name: 'Beer' }\n * ).pipe(\n * max((a, b) => a.age < b.age ? -1 : 1)\n * )\n * .subscribe(x => console.log(x.name));\n *\n * // Outputs\n * // 'Beer'\n * ```\n *\n * @see {@link min}\n *\n * @param comparer Optional comparer function that it will use instead of its\n * default to compare the value of two items.\n * @return A function that returns an Observable that emits item with the\n * largest value.\n */\nexport function max<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) > 0 ? x : y) : (x, y) => (x > y ? x : y));\n}\n","import { mergeMap } from './mergeMap';\n\n/**\n * @deprecated Renamed to {@link mergeMap}. Will be removed in v8.\n */\nexport const flatMap = mergeMap;\n","import { OperatorFunction, ObservedValueOf, ObservableInput } from '../types';\nimport { mergeMap } from './mergeMap';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link mergeMap} instead: `mergeMap(() => result)` */\nexport function mergeMapTo<O extends ObservableInput<unknown>>(\n innerObservable: O,\n concurrent?: number\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/**\n * @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead.\n * Details: https://rxjs.dev/deprecations/resultSelector\n */\nexport function mergeMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R,\n concurrent?: number\n): OperatorFunction<T, R>;\n/* tslint:enable:max-line-length */\n\n/**\n * Projects each source value to the same Observable which is merged multiple\n * times in the output Observable.\n *\n * <span class=\"informal\">It's like {@link mergeMap}, but maps each value always\n * to the same inner Observable.</span>\n *\n * ![](mergeMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then merges those resulting Observables into one\n * single Observable, which is the output Observable.\n *\n * ## Example\n *\n * For each click event, start an interval Observable ticking every 1 second\n *\n * ```ts\n * import { fromEvent, mergeMapTo, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(mergeMapTo(interval(1000)));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link merge}\n * @see {@link mergeAll}\n * @see {@link mergeMap}\n * @see {@link mergeScan}\n * @see {@link switchMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable that emits items from the\n * given `innerObservable`.\n * @deprecated Will be removed in v9. Use {@link mergeMap} instead: `mergeMap(() => result)`\n */\nexport function mergeMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: ((outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R) | number,\n concurrent: number = Infinity\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n if (isFunction(resultSelector)) {\n return mergeMap(() => innerObservable, resultSelector, concurrent);\n }\n if (typeof resultSelector === 'number') {\n concurrent = resultSelector;\n }\n return mergeMap(() => innerObservable, concurrent);\n}\n","import { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeInternals } from './mergeInternals';\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, then each intermediate\n * Observable returned is merged into the output Observable.\n *\n * <span class=\"informal\">It's like {@link scan}, but the Observables returned\n * by the accumulator are merged into the outer Observable.</span>\n *\n * The first parameter of the `mergeScan` is an `accumulator` function which is\n * being called every time the source Observable emits a value. `mergeScan` will\n * subscribe to the value returned by the `accumulator` function and will emit\n * values to the subscriber emitted by inner Observable.\n *\n * The `accumulator` function is being called with three parameters passed to it:\n * `acc`, `value` and `index`. The `acc` parameter is used as the state parameter\n * whose value is initially set to the `seed` parameter (the second parameter\n * passed to the `mergeScan` operator).\n *\n * `mergeScan` internally keeps the value of the `acc` parameter: as long as the\n * source Observable emits without inner Observable emitting, the `acc` will be\n * set to `seed`. The next time the inner Observable emits a value, `mergeScan`\n * will internally remember it and it will be passed to the `accumulator`\n * function as `acc` parameter the next time source emits.\n *\n * The `value` parameter of the `accumulator` function is the value emitted by the\n * source Observable, while the `index` is a number which represent the order of the\n * current emission by the source Observable. It starts with 0.\n *\n * The last parameter to the `mergeScan` is the `concurrent` value which defaults\n * to Infinity. It represents the maximum number of inner Observable subscriptions\n * at a time.\n *\n * ## Example\n *\n * Count the number of click events\n *\n * ```ts\n * import { fromEvent, map, mergeScan, of } from 'rxjs';\n *\n * const click$ = fromEvent(document, 'click');\n * const one$ = click$.pipe(map(() => 1));\n * const seed = 0;\n * const count$ = one$.pipe(\n * mergeScan((acc, one) => of(acc + one), seed)\n * );\n *\n * count$.subscribe(x => console.log(x));\n *\n * // Results:\n * // 1\n * // 2\n * // 3\n * // 4\n * // ...and so on for each click\n * ```\n *\n * @see {@link scan}\n * @see {@link switchScan}\n *\n * @param accumulator The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @param concurrent Maximum number of input Observables being subscribed to\n * concurrently.\n * @return A function that returns an Observable of the accumulated values.\n */\nexport function mergeScan<T, R>(\n accumulator: (acc: R, value: T, index: number) => ObservableInput<R>,\n seed: R,\n concurrent = Infinity\n): OperatorFunction<T, R> {\n return operate((source, subscriber) => {\n // The accumulated state.\n let state = seed;\n\n return mergeInternals(\n source,\n subscriber,\n (value, index) => accumulator(state, value, index),\n concurrent,\n (value) => {\n state = value;\n },\n false,\n undefined,\n () => (state = null!)\n );\n });\n}\n","import { ObservableInput, ObservableInputTuple, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { mergeAll } from './mergeAll';\nimport { popNumber, popScheduler } from '../util/args';\nimport { from } from '../observable/from';\n\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(...sources: [...ObservableInputTuple<A>]): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndConcurrency: [...ObservableInputTuple<A>, number]\n): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndScheduler: [...ObservableInputTuple<A>, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n/** @deprecated Replaced with {@link mergeWith}. Will be removed in v8. */\nexport function merge<T, A extends readonly unknown[]>(\n ...sourcesAndConcurrencyAndScheduler: [...ObservableInputTuple<A>, number, SchedulerLike]\n): OperatorFunction<T, T | A[number]>;\n\nexport function merge<T>(...args: unknown[]): OperatorFunction<T, unknown> {\n const scheduler = popScheduler(args);\n const concurrent = popNumber(args, Infinity);\n\n return operate((source, subscriber) => {\n mergeAll(concurrent)(from([source, ...(args as ObservableInput<T>[])], scheduler)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { merge } from './merge';\n\n/**\n * Merge the values from all observables to a single observable result.\n *\n * Creates an observable, that when subscribed to, subscribes to the source\n * observable, and all other sources provided as arguments. All values from\n * every source are emitted from the resulting subscription.\n *\n * When all sources complete, the resulting observable will complete.\n *\n * When any source errors, the resulting observable will error.\n *\n * ## Example\n *\n * Joining all outputs from multiple user input event streams\n *\n * ```ts\n * import { fromEvent, map, mergeWith } from 'rxjs';\n *\n * const clicks$ = fromEvent(document, 'click').pipe(map(() => 'click'));\n * const mousemoves$ = fromEvent(document, 'mousemove').pipe(map(() => 'mousemove'));\n * const dblclicks$ = fromEvent(document, 'dblclick').pipe(map(() => 'dblclick'));\n *\n * mousemoves$\n * .pipe(mergeWith(clicks$, dblclicks$))\n * .subscribe(x => console.log(x));\n *\n * // result (assuming user interactions)\n * // 'mousemove'\n * // 'mousemove'\n * // 'mousemove'\n * // 'click'\n * // 'click'\n * // 'dblclick'\n * ```\n *\n * @see {@link merge}\n *\n * @param otherSources the sources to combine the current source with.\n * @return A function that returns an Observable that merges the values from\n * all given Observables.\n */\nexport function mergeWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return merge(...otherSources);\n}\n","import { reduce } from './reduce';\nimport { MonoTypeOperatorFunction } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * The `min` operator operates on an Observable that emits numbers (or items that\n * can be compared with a provided function), and when source Observable completes\n * it emits a single item: the item with the smallest value.\n *\n * ![](min.png)\n *\n * ## Examples\n *\n * Get the minimal value of a series of numbers\n *\n * ```ts\n * import { of, min } from 'rxjs';\n *\n * of(5, 4, 7, 2, 8)\n * .pipe(min())\n * .subscribe(x => console.log(x));\n *\n * // Outputs\n * // 2\n * ```\n *\n * Use a comparer function to get the minimal item\n *\n * ```ts\n * import { of, min } from 'rxjs';\n *\n * of(\n * { age: 7, name: 'Foo' },\n * { age: 5, name: 'Bar' },\n * { age: 9, name: 'Beer' }\n * ).pipe(\n * min((a, b) => a.age < b.age ? -1 : 1)\n * )\n * .subscribe(x => console.log(x.name));\n *\n * // Outputs\n * // 'Bar'\n * ```\n *\n * @see {@link max}\n *\n * @param comparer Optional comparer function that it will use instead of its\n * default to compare the value of two items.\n * @return A function that returns an Observable that emits item with the\n * smallest value.\n */\nexport function min<T>(comparer?: (x: T, y: T) => number): MonoTypeOperatorFunction<T> {\n return reduce(isFunction(comparer) ? (x, y) => (comparer(x, y) < 0 ? x : y) : (x, y) => (x < y ? x : y));\n}\n","import { Subject } from '../Subject';\nimport { Observable } from '../Observable';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { OperatorFunction, UnaryFunction, ObservedValueOf, ObservableInput } from '../types';\nimport { isFunction } from '../util/isFunction';\nimport { connect } from './connect';\n\n/**\n * An operator that creates a {@link ConnectableObservable}, that when connected,\n * with the `connect` method, will use the provided subject to multicast the values\n * from the source to all consumers.\n *\n * @param subject The subject to multicast through.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * If you're using {@link refCount} after `multicast`, use the {@link share} operator instead.\n * `multicast(subject), refCount()` is equivalent to\n * `share({ connector: () => subject, resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T>(subject: Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Because this is deprecated in favor of the {@link connect} operator, and was otherwise poorly documented,\n * rather than duplicate the effort of documenting the same behavior, please see documentation for the\n * {@link connect} operator.\n *\n * @param subject The subject used to multicast.\n * @param selector A setup function to setup the multicast\n * @return A function that returns an observable that mirrors the observable returned by the selector.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `multicast(subject, selector)` is equivalent to\n * `connect(selector, { connector: () => subject })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, O extends ObservableInput<any>>(\n subject: Subject<T>,\n selector: (shared: Observable<T>) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * An operator that creates a {@link ConnectableObservable}, that when connected,\n * with the `connect` method, will use the provided subject to multicast the values\n * from the source to all consumers.\n *\n * @param subjectFactory A factory that will be called to create the subject. Passing a function here\n * will cause the underlying subject to be \"reset\" on error, completion, or refCounted unsubscription of\n * the source.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * If you're using {@link refCount} after `multicast`, use the {@link share} operator instead.\n * `multicast(() => new BehaviorSubject('test')), refCount()` is equivalent to\n * `share({ connector: () => new BehaviorSubject('test') })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T>(subjectFactory: () => Subject<T>): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Because this is deprecated in favor of the {@link connect} operator, and was otherwise poorly documented,\n * rather than duplicate the effort of documenting the same behavior, please see documentation for the\n * {@link connect} operator.\n *\n * @param subjectFactory A factory that creates the subject used to multicast.\n * @param selector A function to setup the multicast and select the output.\n * @return A function that returns an observable that mirrors the observable returned by the selector.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `multicast(subjectFactory, selector)` is equivalent to\n * `connect(selector, { connector: subjectFactory })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, O extends ObservableInput<any>>(\n subjectFactory: () => Subject<T>,\n selector: (shared: Observable<T>) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function multicast<T, R>(\n subjectOrSubjectFactory: Subject<T> | (() => Subject<T>),\n selector?: (source: Observable<T>) => Observable<R>\n): OperatorFunction<T, R> {\n const subjectFactory = isFunction(subjectOrSubjectFactory) ? subjectOrSubjectFactory : () => subjectOrSubjectFactory;\n\n if (isFunction(selector)) {\n // If a selector function is provided, then we're a \"normal\" operator that isn't\n // going to return a ConnectableObservable. We can use `connect` to do what we\n // need to do.\n return connect(selector, {\n connector: subjectFactory,\n });\n }\n\n return (source: Observable<T>) => new ConnectableObservable<any>(source, subjectFactory);\n}\n","import { ObservableInputTuple, OperatorFunction } from '../types';\nimport { argsOrArgArray } from '../util/argsOrArgArray';\nimport { onErrorResumeNext as oERNCreate } from '../observable/onErrorResumeNext';\n\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n sources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]>;\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n ...sources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]>;\n\n/**\n * When any of the provided Observable emits an complete or error notification, it immediately subscribes to the next one\n * that was passed.\n *\n * <span class=\"informal\">Execute series of Observables, subscribes to next one on error or complete.</span>\n *\n * ![](onErrorResumeNext.png)\n *\n * `onErrorResumeNext` is an operator that accepts a series of Observables, provided either directly as\n * arguments or as an array. If no single Observable is provided, returned Observable will simply behave the same\n * as the source.\n *\n * `onErrorResumeNext` returns an Observable that starts by subscribing and re-emitting values from the source Observable.\n * When its stream of values ends - no matter if Observable completed or emitted an error - `onErrorResumeNext`\n * will subscribe to the first Observable that was passed as an argument to the method. It will start re-emitting\n * its values as well and - again - when that stream ends, `onErrorResumeNext` will proceed to subscribing yet another\n * Observable in provided series, no matter if previous Observable completed or ended with an error. This will\n * be happening until there is no more Observables left in the series, at which point returned Observable will\n * complete - even if the last subscribed stream ended with an error.\n *\n * `onErrorResumeNext` can be therefore thought of as version of {@link concat} operator, which is more permissive\n * when it comes to the errors emitted by its input Observables. While `concat` subscribes to the next Observable\n * in series only if previous one successfully completed, `onErrorResumeNext` subscribes even if it ended with\n * an error.\n *\n * Note that you do not get any access to errors emitted by the Observables. In particular do not\n * expect these errors to appear in error callback passed to {@link Observable#subscribe}. If you want to take\n * specific actions based on what error was emitted by an Observable, you should try out {@link catchError} instead.\n *\n *\n * ## Example\n *\n * Subscribe to the next Observable after map fails\n *\n * ```ts\n * import { of, onErrorResumeNext, map } from 'rxjs';\n *\n * of(1, 2, 3, 0)\n * .pipe(\n * map(x => {\n * if (x === 0) {\n * throw Error();\n * }\n *\n * return 10 / x;\n * }),\n * onErrorResumeNext(of(1, 2, 3))\n * )\n * .subscribe({\n * next: val => console.log(val),\n * error: err => console.log(err), // Will never be called.\n * complete: () => console.log('that\\'s it!')\n * });\n *\n * // Logs:\n * // 10\n * // 5\n * // 3.3333333333333335\n * // 1\n * // 2\n * // 3\n * // 'that's it!'\n * ```\n *\n * @see {@link concat}\n * @see {@link catchError}\n *\n * @param sources `ObservableInput`s passed either directly or as an array.\n * @return A function that returns an Observable that emits values from source\n * Observable, but - if it errors - subscribes to the next passed Observable\n * and so on, until it completes or runs out of Observables.\n */\nexport function onErrorResumeNextWith<T, A extends readonly unknown[]>(\n ...sources: [[...ObservableInputTuple<A>]] | [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n // For some reason, TS 4.1 RC gets the inference wrong here and infers the\n // result to be `A[number][]` - completely dropping the ObservableInput part\n // of the type. This makes no sense whatsoever. As a workaround, the type is\n // asserted explicitly.\n const nextSources = argsOrArgArray(sources) as unknown as ObservableInputTuple<A>;\n\n return (source) => oERNCreate(source, ...nextSources);\n}\n\n/**\n * @deprecated Renamed. Use {@link onErrorResumeNextWith} instead. Will be removed in v8.\n */\nexport const onErrorResumeNext = onErrorResumeNextWith;\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Groups pairs of consecutive emissions together and emits them as an array of\n * two values.\n *\n * <span class=\"informal\">Puts the current value and previous value together as\n * an array, and emits that.</span>\n *\n * ![](pairwise.png)\n *\n * The Nth emission from the source Observable will cause the output Observable\n * to emit an array [(N-1)th, Nth] of the previous and the current value, as a\n * pair. For this reason, `pairwise` emits on the second and subsequent\n * emissions from the source Observable, but not on the first emission, because\n * there is no previous value in that case.\n *\n * ## Example\n *\n * On every click (starting from the second), emit the relative distance to the previous click\n *\n * ```ts\n * import { fromEvent, pairwise, map } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const pairs = clicks.pipe(pairwise());\n * const distance = pairs.pipe(\n * map(([first, second]) => {\n * const x0 = first.clientX;\n * const y0 = first.clientY;\n * const x1 = second.clientX;\n * const y1 = second.clientY;\n * return Math.sqrt(Math.pow(x0 - x1, 2) + Math.pow(y0 - y1, 2));\n * })\n * );\n *\n * distance.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link buffer}\n * @see {@link bufferCount}\n *\n * @return A function that returns an Observable of pairs (as arrays) of\n * consecutive values from the source Observable.\n */\nexport function pairwise<T>(): OperatorFunction<T, [T, T]> {\n return operate((source, subscriber) => {\n let prev: T;\n let hasPrev = false;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const p = prev;\n prev = value;\n hasPrev && subscriber.next([p, value]);\n hasPrev = true;\n })\n );\n });\n}\n","import { map } from './map';\nimport { OperatorFunction } from '../types';\n\n/* tslint:disable:max-line-length */\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T>(k1: K1): OperatorFunction<T, T[K1]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1]>(k1: K1, k2: K2): OperatorFunction<T, T[K1][K2]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2]>(\n k1: K1,\n k2: K2,\n k3: K3\n): OperatorFunction<T, T[K1][K2][K3]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T, K1 extends keyof T, K2 extends keyof T[K1], K3 extends keyof T[K1][K2], K4 extends keyof T[K1][K2][K3]>(\n k1: K1,\n k2: K2,\n k3: K3,\n k4: K4\n): OperatorFunction<T, T[K1][K2][K3][K4]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5): OperatorFunction<T, T[K1][K2][K3][K4][K5]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4],\n K6 extends keyof T[K1][K2][K3][K4][K5]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6): OperatorFunction<T, T[K1][K2][K3][K4][K5][K6]>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<\n T,\n K1 extends keyof T,\n K2 extends keyof T[K1],\n K3 extends keyof T[K1][K2],\n K4 extends keyof T[K1][K2][K3],\n K5 extends keyof T[K1][K2][K3][K4],\n K6 extends keyof T[K1][K2][K3][K4][K5]\n>(k1: K1, k2: K2, k3: K3, k4: K4, k5: K5, k6: K6, ...rest: string[]): OperatorFunction<T, unknown>;\n/** @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8. */\nexport function pluck<T>(...properties: string[]): OperatorFunction<T, unknown>;\n/* tslint:enable:max-line-length */\n\n/**\n * Maps each source value to its specified nested property.\n *\n * <span class=\"informal\">Like {@link map}, but meant only for picking one of\n * the nested properties of every emitted value.</span>\n *\n * ![](pluck.png)\n *\n * Given a list of strings or numbers describing a path to a property, retrieves\n * the value of a specified nested property from all values in the source\n * Observable. If a property can't be resolved, it will return `undefined` for\n * that value.\n *\n * ## Example\n *\n * Map every click to the tagName of the clicked target element\n *\n * ```ts\n * import { fromEvent, pluck } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const tagNames = clicks.pipe(pluck('target', 'tagName'));\n *\n * tagNames.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link map}\n *\n * @param properties The nested properties to pluck from each source\n * value.\n * @return A function that returns an Observable of property values from the\n * source values.\n * @deprecated Use {@link map} and optional chaining: `pluck('foo', 'bar')` is `map(x => x?.foo?.bar)`. Will be removed in v8.\n */\nexport function pluck<T, R>(...properties: Array<string | number | symbol>): OperatorFunction<T, R> {\n const length = properties.length;\n if (length === 0) {\n throw new Error('list of properties cannot be empty.');\n }\n return map((x) => {\n let currentProp: any = x;\n for (let i = 0; i < length; i++) {\n const p = currentProp?.[properties[i]];\n if (typeof p !== 'undefined') {\n currentProp = p;\n } else {\n return undefined;\n }\n }\n return currentProp;\n });\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { multicast } from './multicast';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { MonoTypeOperatorFunction, OperatorFunction, UnaryFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { connect } from './connect';\n\n/**\n * Returns a connectable observable that, when connected, will multicast\n * all values through a single underlying {@link Subject} instance.\n *\n * @deprecated Will be removed in v8. To create a connectable observable, use {@link connectable}.\n * `source.pipe(publish())` is equivalent to\n * `connectable(source, { connector: () => new Subject(), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publish`, use {@link share} operator instead.\n * `source.pipe(publish(), refCount())` is equivalent to\n * `source.pipe(share({ resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>>;\n\n/**\n * Returns an observable, that when subscribed to, creates an underlying {@link Subject},\n * provides an observable view of it to a `selector` function, takes the observable result of\n * that selector function and subscribes to it, sending its values to the consumer, _then_ connects\n * the subject to the original source.\n *\n * @param selector A function used to setup multicasting prior to automatic connection.\n *\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `publish(selector)` is equivalent to `connect(selector)`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T, O extends ObservableInput<any>>(selector: (shared: Observable<T>) => O): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * Returns a ConnectableObservable, which is a variety of Observable that waits until its connect method is called\n * before it begins emitting items to those Observers that have subscribed to it.\n *\n * <span class=\"informal\">Makes a cold Observable hot</span>\n *\n * ![](publish.png)\n *\n * ## Examples\n *\n * Make `source$` hot by applying `publish` operator, then merge each inner observable into a single one\n * and subscribe\n *\n * ```ts\n * import { zip, interval, of, map, publish, merge, tap } from 'rxjs';\n *\n * const source$ = zip(interval(2000), of(1, 2, 3, 4, 5, 6, 7, 8, 9))\n * .pipe(map(([, number]) => number));\n *\n * source$\n * .pipe(\n * publish(multicasted$ =>\n * merge(\n * multicasted$.pipe(tap(x => console.log('Stream 1:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 2:', x))),\n * multicasted$.pipe(tap(x => console.log('Stream 3:', x)))\n * )\n * )\n * )\n * .subscribe();\n *\n * // Results every two seconds\n * // Stream 1: 1\n * // Stream 2: 1\n * // Stream 3: 1\n * // ...\n * // Stream 1: 9\n * // Stream 2: 9\n * // Stream 3: 9\n * ```\n *\n * @see {@link publishLast}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @param selector Optional selector function which can use the multicasted source sequence as many times\n * as needed, without causing multiple subscriptions to the source sequence.\n * Subscribers to the given source will receive all notifications of the source from the time of the subscription on.\n * @return A function that returns a ConnectableObservable that upon connection\n * causes the source Observable to emit items to its Observers.\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publish<T, R>(selector?: OperatorFunction<T, R>): MonoTypeOperatorFunction<T> | OperatorFunction<T, R> {\n return selector ? (source) => connect(selector)(source) : (source) => multicast(new Subject<T>())(source);\n}\n","import { Observable } from '../Observable';\nimport { BehaviorSubject } from '../BehaviorSubject';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Creates a {@link ConnectableObservable} that utilizes a {@link BehaviorSubject}.\n *\n * @param initialValue The initial value passed to the {@link BehaviorSubject}.\n * @return A function that returns a {@link ConnectableObservable}\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link BehaviorSubject} under the hood, use {@link connectable}.\n * `source.pipe(publishBehavior(initValue))` is equivalent to\n * `connectable(source, { connector: () => new BehaviorSubject(initValue), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishBehavior`, use the {@link share} operator instead.\n * `source.pipe(publishBehavior(initValue), refCount())` is equivalent to\n * `source.pipe(share({ connector: () => new BehaviorSubject(initValue), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishBehavior<T>(initialValue: T): UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n // Note that this has *never* supported the selector function.\n return (source) => {\n const subject = new BehaviorSubject<T>(initialValue);\n return new ConnectableObservable(source, () => subject);\n };\n}\n","import { Observable } from '../Observable';\nimport { AsyncSubject } from '../AsyncSubject';\nimport { ConnectableObservable } from '../observable/ConnectableObservable';\nimport { UnaryFunction } from '../types';\n\n/**\n * Returns a connectable observable sequence that shares a single subscription to the\n * underlying sequence containing only the last notification.\n *\n * ![](publishLast.png)\n *\n * Similar to {@link publish}, but it waits until the source observable completes and stores\n * the last emitted value.\n * Similarly to {@link publishReplay} and {@link publishBehavior}, this keeps storing the last\n * value even if it has no more subscribers. If subsequent subscriptions happen, they will\n * immediately get that last stored value and complete.\n *\n * ## Example\n *\n * ```ts\n * import { ConnectableObservable, interval, publishLast, tap, take } from 'rxjs';\n *\n * const connectable = <ConnectableObservable<number>>interval(1000)\n * .pipe(\n * tap(x => console.log('side effect', x)),\n * take(3),\n * publishLast()\n * );\n *\n * connectable.subscribe({\n * next: x => console.log('Sub. A', x),\n * error: err => console.log('Sub. A Error', err),\n * complete: () => console.log('Sub. A Complete')\n * });\n *\n * connectable.subscribe({\n * next: x => console.log('Sub. B', x),\n * error: err => console.log('Sub. B Error', err),\n * complete: () => console.log('Sub. B Complete')\n * });\n *\n * connectable.connect();\n *\n * // Results:\n * // 'side effect 0' - after one second\n * // 'side effect 1' - after two seconds\n * // 'side effect 2' - after three seconds\n * // 'Sub. A 2' - immediately after 'side effect 2'\n * // 'Sub. B 2'\n * // 'Sub. A Complete'\n * // 'Sub. B Complete'\n * ```\n *\n * @see {@link ConnectableObservable}\n * @see {@link publish}\n * @see {@link publishReplay}\n * @see {@link publishBehavior}\n *\n * @return A function that returns an Observable that emits elements of a\n * sequence produced by multicasting the source sequence.\n * @deprecated Will be removed in v8. To create a connectable observable with an\n * {@link AsyncSubject} under the hood, use {@link connectable}.\n * `source.pipe(publishLast())` is equivalent to\n * `connectable(source, { connector: () => new AsyncSubject(), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishLast`, use the {@link share} operator instead.\n * `source.pipe(publishLast(), refCount())` is equivalent to\n * `source.pipe(share({ connector: () => new AsyncSubject(), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishLast<T>(): UnaryFunction<Observable<T>, ConnectableObservable<T>> {\n // Note that this has *never* supported a selector function like `publish` and `publishReplay`.\n return (source) => {\n const subject = new AsyncSubject<T>();\n return new ConnectableObservable(source, () => subject);\n };\n}\n","import { Observable } from '../Observable';\nimport { ReplaySubject } from '../ReplaySubject';\nimport { multicast } from './multicast';\nimport { MonoTypeOperatorFunction, OperatorFunction, TimestampProvider, ObservableInput, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/**\n * Creates a {@link ConnectableObservable} that uses a {@link ReplaySubject}\n * internally.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link ReplaySubject} under the hood, use {@link connectable}.\n * `source.pipe(publishReplay(size, time, scheduler))` is equivalent to\n * `connectable(source, { connector: () => new ReplaySubject(size, time, scheduler), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishReplay`, use the {@link share} operator instead.\n * `publishReplay(size, time, scheduler), refCount()` is equivalent to\n * `share({ connector: () => new ReplaySubject(size, time, scheduler), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T>(\n bufferSize?: number,\n windowTime?: number,\n timestampProvider?: TimestampProvider\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Creates an observable, that when subscribed to, will create a {@link ReplaySubject},\n * and pass an observable from it (using [asObservable](api/index/class/Subject#asObservable)) to\n * the `selector` function, which then returns an observable that is subscribed to before\n * \"connecting\" the source to the internal `ReplaySubject`.\n *\n * Since this is deprecated, for additional details see the documentation for {@link connect}.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param selector A function used to setup the multicast.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. Use the {@link connect} operator instead.\n * `source.pipe(publishReplay(size, window, selector, scheduler))` is equivalent to\n * `source.pipe(connect(selector, { connector: () => new ReplaySubject(size, window, scheduler) }))`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, O extends ObservableInput<any>>(\n bufferSize: number | undefined,\n windowTime: number | undefined,\n selector: (shared: Observable<T>) => O,\n timestampProvider?: TimestampProvider\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * Creates a {@link ConnectableObservable} that uses a {@link ReplaySubject}\n * internally.\n *\n * @param bufferSize The buffer size for the underlying {@link ReplaySubject}.\n * @param windowTime The window time for the underlying {@link ReplaySubject}.\n * @param selector Passing `undefined` here determines that this operator will return a {@link ConnectableObservable}.\n * @param timestampProvider The timestamp provider for the underlying {@link ReplaySubject}.\n * @deprecated Will be removed in v8. To create a connectable observable that uses a\n * {@link ReplaySubject} under the hood, use {@link connectable}.\n * `source.pipe(publishReplay(size, time, scheduler))` is equivalent to\n * `connectable(source, { connector: () => new ReplaySubject(size, time, scheduler), resetOnDisconnect: false })`.\n * If you're using {@link refCount} after `publishReplay`, use the {@link share} operator instead.\n * `publishReplay(size, time, scheduler), refCount()` is equivalent to\n * `share({ connector: () => new ReplaySubject(size, time, scheduler), resetOnError: false, resetOnComplete: false, resetOnRefCountZero: false })`.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, O extends ObservableInput<any>>(\n bufferSize: number | undefined,\n windowTime: number | undefined,\n selector: undefined,\n timestampProvider: TimestampProvider\n): OperatorFunction<T, ObservedValueOf<O>>;\n\n/**\n * @deprecated Will be removed in v8. Use the {@link connectable} observable, the {@link connect} operator or the\n * {@link share} operator instead. See the overloads below for equivalent replacement examples of this operator's\n * behaviors.\n * Details: https://rxjs.dev/deprecations/multicasting\n */\nexport function publishReplay<T, R>(\n bufferSize?: number,\n windowTime?: number,\n selectorOrScheduler?: TimestampProvider | OperatorFunction<T, R>,\n timestampProvider?: TimestampProvider\n) {\n if (selectorOrScheduler && !isFunction(selectorOrScheduler)) {\n timestampProvider = selectorOrScheduler;\n }\n const selector = isFunction(selectorOrScheduler) ? selectorOrScheduler : undefined;\n // Note, we're passing `selector!` here, because at runtime, `undefined` is an acceptable argument\n // but it makes our TypeScript signature for `multicast` unhappy (as it should, because it's gross).\n return (source: Observable<T>) => multicast(new ReplaySubject<T>(bufferSize, windowTime, timestampProvider), selector!)(source);\n}\n","import { OperatorFunction, ObservableInputTuple } from '../types';\nimport { raceInit } from '../observable/race';\nimport { operate } from '../util/lift';\nimport { identity } from '../util/identity';\n\n/**\n * Creates an Observable that mirrors the first source Observable to emit a next,\n * error or complete notification from the combination of the Observable to which\n * the operator is applied and supplied Observables.\n *\n * ## Example\n *\n * ```ts\n * import { interval, map, raceWith } from 'rxjs';\n *\n * const obs1 = interval(7000).pipe(map(() => 'slow one'));\n * const obs2 = interval(3000).pipe(map(() => 'fast one'));\n * const obs3 = interval(5000).pipe(map(() => 'medium one'));\n *\n * obs1\n * .pipe(raceWith(obs2, obs3))\n * .subscribe(winner => console.log(winner));\n *\n * // Outputs\n * // a series of 'fast one'\n * ```\n *\n * @param otherSources Sources used to race for which Observable emits first.\n * @return A function that returns an Observable that mirrors the output of the\n * first Observable to emit an item.\n */\nexport function raceWith<T, A extends readonly unknown[]>(\n ...otherSources: [...ObservableInputTuple<A>]\n): OperatorFunction<T, T | A[number]> {\n return !otherSources.length\n ? identity\n : operate((source, subscriber) => {\n raceInit<T | A[number]>([source, ...otherSources])(subscriber);\n });\n}\n","import { Subscription } from '../Subscription';\nimport { EMPTY } from '../observable/empty';\nimport { operate } from '../util/lift';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { timer } from '../observable/timer';\n\nexport interface RepeatConfig {\n /**\n * The number of times to repeat the source. Defaults to `Infinity`.\n */\n count?: number;\n\n /**\n * If a `number`, will delay the repeat of the source by that number of milliseconds.\n * If a function, it will provide the number of times the source has been subscribed to,\n * and the return value should be a valid observable input that will notify when the source\n * should be repeated. If the notifier observable is empty, the result will complete.\n */\n delay?: number | ((count: number) => ObservableInput<any>);\n}\n\n/**\n * Returns an Observable that will resubscribe to the source stream when the source stream completes.\n *\n * <span class=\"informal\">Repeats all values emitted on the source. It's like {@link retry}, but for non error cases.</span>\n *\n * ![](repeat.png)\n *\n * Repeat will output values from a source until the source completes, then it will resubscribe to the\n * source a specified number of times, with a specified delay. Repeat can be particularly useful in\n * combination with closing operators like {@link take}, {@link takeUntil}, {@link first}, or {@link takeWhile},\n * as it can be used to restart a source again from scratch.\n *\n * Repeat is very similar to {@link retry}, where {@link retry} will resubscribe to the source in the error case, but\n * `repeat` will resubscribe if the source completes.\n *\n * Note that `repeat` will _not_ catch errors. Use {@link retry} for that.\n *\n * - `repeat(0)` returns an empty observable\n * - `repeat()` will repeat forever\n * - `repeat({ delay: 200 })` will repeat forever, with a delay of 200ms between repetitions.\n * - `repeat({ count: 2, delay: 400 })` will repeat twice, with a delay of 400ms between repetitions.\n * - `repeat({ delay: (count) => timer(count * 1000) })` will repeat forever, but will have a delay that grows by one second for each repetition.\n *\n * ## Example\n *\n * Repeat a message stream\n *\n * ```ts\n * import { of, repeat } from 'rxjs';\n *\n * const source = of('Repeat message');\n * const result = source.pipe(repeat(3));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results\n * // 'Repeat message'\n * // 'Repeat message'\n * // 'Repeat message'\n * ```\n *\n * Repeat 3 values, 2 times\n *\n * ```ts\n * import { interval, take, repeat } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(take(3), repeat(2));\n *\n * result.subscribe(x => console.log(x));\n *\n * // Results every second\n * // 0\n * // 1\n * // 2\n * // 0\n * // 1\n * // 2\n * ```\n *\n * Defining two complex repeats with delays on the same source.\n * Note that the second repeat cannot be called until the first\n * repeat as exhausted it's count.\n *\n * ```ts\n * import { defer, of, repeat } from 'rxjs';\n *\n * const source = defer(() => {\n * return of(`Hello, it is ${new Date()}`)\n * });\n *\n * source.pipe(\n * // Repeat 3 times with a delay of 1 second between repetitions\n * repeat({\n * count: 3,\n * delay: 1000,\n * }),\n *\n * // *Then* repeat forever, but with an exponential step-back\n * // maxing out at 1 minute.\n * repeat({\n * delay: (count) => timer(Math.min(60000, 2 ^ count * 1000))\n * })\n * )\n * ```\n *\n * @see {@link repeatWhen}\n * @see {@link retry}\n *\n * @param countOrConfig Either the number of times the source Observable items are repeated\n * (a count of 0 will yield an empty Observable) or a {@link RepeatConfig} object.\n */\nexport function repeat<T>(countOrConfig?: number | RepeatConfig): MonoTypeOperatorFunction<T> {\n let count = Infinity;\n let delay: RepeatConfig['delay'];\n\n if (countOrConfig != null) {\n if (typeof countOrConfig === 'object') {\n ({ count = Infinity, delay } = countOrConfig);\n } else {\n count = countOrConfig;\n }\n }\n\n return count <= 0\n ? () => EMPTY\n : operate((source, subscriber) => {\n let soFar = 0;\n let sourceSub: Subscription | null;\n\n const resubscribe = () => {\n sourceSub?.unsubscribe();\n sourceSub = null;\n if (delay != null) {\n const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(soFar));\n const notifierSubscriber = createOperatorSubscriber(subscriber, () => {\n notifierSubscriber.unsubscribe();\n subscribeToSource();\n });\n notifier.subscribe(notifierSubscriber);\n } else {\n subscribeToSource();\n }\n };\n\n const subscribeToSource = () => {\n let syncUnsub = false;\n sourceSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, () => {\n if (++soFar < count) {\n if (sourceSub) {\n resubscribe();\n } else {\n syncUnsub = true;\n }\n } else {\n subscriber.complete();\n }\n })\n );\n\n if (syncUnsub) {\n resubscribe();\n }\n };\n\n subscribeToSource();\n });\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of a `complete`. If the source\n * Observable calls `complete`, this method will emit to the Observable returned from `notifier`. If that Observable\n * calls `complete` or `error`, then this method will call `complete` or `error` on the child subscription. Otherwise\n * this method will resubscribe to the source Observable.\n *\n * ![](repeatWhen.png)\n *\n * ## Example\n *\n * Repeat a message stream on click\n *\n * ```ts\n * import { of, fromEvent, repeatWhen } from 'rxjs';\n *\n * const source = of('Repeat message');\n * const documentClick$ = fromEvent(document, 'click');\n *\n * const result = source.pipe(repeatWhen(() => documentClick$));\n *\n * result.subscribe(data => console.log(data))\n * ```\n *\n * @see {@link repeat}\n * @see {@link retry}\n * @see {@link retryWhen}\n *\n * @param notifier Function that receives an Observable of notifications with\n * which a user can `complete` or `error`, aborting the repetition.\n * @return A function that returns an Observable that mirrors the source\n * Observable with the exception of a `complete`.\n * @deprecated Will be removed in v9 or v10. Use {@link repeat}'s {@link RepeatConfig#delay delay} option instead.\n * Instead of `repeatWhen(() => notify$)`, use: `repeat({ delay: () => notify$ })`.\n */\nexport function repeatWhen<T>(notifier: (notifications: Observable<void>) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null;\n let syncResub = false;\n let completions$: Subject<void>;\n let isNotifierComplete = false;\n let isMainComplete = false;\n\n /**\n * Checks to see if we can complete the result, completes it, and returns `true` if it was completed.\n */\n const checkComplete = () => isMainComplete && isNotifierComplete && (subscriber.complete(), true);\n /**\n * Gets the subject to send errors through. If it doesn't exist,\n * we know we need to setup the notifier.\n */\n const getCompletionSubject = () => {\n if (!completions$) {\n completions$ = new Subject();\n\n // If the call to `notifier` throws, it will be caught by the OperatorSubscriber\n // In the main subscription -- in `subscribeForRepeatWhen`.\n innerFrom(notifier(completions$)).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n if (innerSub) {\n subscribeForRepeatWhen();\n } else {\n // If we don't have an innerSub yet, that's because the inner subscription\n // call hasn't even returned yet. We've arrived here synchronously.\n // So we flag that we want to resub, such that we can ensure finalization\n // happens before we resubscribe.\n syncResub = true;\n }\n },\n () => {\n isNotifierComplete = true;\n checkComplete();\n }\n )\n );\n }\n return completions$;\n };\n\n const subscribeForRepeatWhen = () => {\n isMainComplete = false;\n\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, () => {\n isMainComplete = true;\n // Check to see if we are complete, and complete if so.\n // If we are not complete. Get the subject. This calls the `notifier` function.\n // If that function fails, it will throw and `.next()` will not be reached on this\n // line. The thrown error is caught by the _complete handler in this\n // `OperatorSubscriber` and handled appropriately.\n !checkComplete() && getCompletionSubject().next();\n })\n );\n\n if (syncResub) {\n // Ensure that the inner subscription is torn down before\n // moving on to the next subscription in the synchronous case.\n // If we don't do this here, all inner subscriptions will not be\n // torn down until the entire observable is done.\n innerSub.unsubscribe();\n // It is important to null this out. Not only to free up memory, but\n // to make sure code above knows we are in a subscribing state to\n // handle synchronous resubscription.\n innerSub = null;\n // We may need to do this multiple times, so reset the flags.\n syncResub = false;\n // Resubscribe\n subscribeForRepeatWhen();\n }\n };\n\n // Start the subscription\n subscribeForRepeatWhen();\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { Subscription } from '../Subscription';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\nimport { timer } from '../observable/timer';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * The {@link retry} operator configuration object. `retry` either accepts a `number`\n * or an object described by this interface.\n */\nexport interface RetryConfig {\n /**\n * The maximum number of times to retry. If `count` is omitted, `retry` will try to\n * resubscribe on errors infinite number of times.\n */\n count?: number;\n /**\n * The number of milliseconds to delay before retrying, OR a function to\n * return a notifier for delaying. If a function is given, that function should\n * return a notifier that, when it emits will retry the source. If the notifier\n * completes _without_ emitting, the resulting observable will complete without error,\n * if the notifier errors, the error will be pushed to the result.\n */\n delay?: number | ((error: any, retryCount: number) => ObservableInput<any>);\n /**\n * Whether or not to reset the retry counter when the retried subscription\n * emits its first value.\n */\n resetOnSuccess?: boolean;\n}\n\nexport function retry<T>(count?: number): MonoTypeOperatorFunction<T>;\nexport function retry<T>(config: RetryConfig): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`.\n *\n * If the source Observable calls `error`, this method will resubscribe to the source Observable for a maximum of\n * `count` resubscriptions rather than propagating the `error` call.\n *\n * ![](retry.png)\n *\n * The number of retries is determined by the `count` parameter. It can be set either by passing a number to\n * `retry` function or by setting `count` property when `retry` is configured using {@link RetryConfig}. If\n * `count` is omitted, `retry` will try to resubscribe on errors infinite number of times.\n *\n * Any and all items emitted by the source Observable will be emitted by the resulting Observable, even those\n * emitted during failed subscriptions. For example, if an Observable fails at first but emits `[1, 2]` then\n * succeeds the second time and emits: `[1, 2, 3, 4, 5, complete]` then the complete stream of emissions and\n * notifications would be: `[1, 2, 1, 2, 3, 4, 5, complete]`.\n *\n * ## Example\n *\n * ```ts\n * import { interval, mergeMap, throwError, of, retry } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(\n * mergeMap(val => val > 5 ? throwError(() => 'Error!') : of(val)),\n * retry(2) // retry 2 times on error\n * );\n *\n * result.subscribe({\n * next: value => console.log(value),\n * error: err => console.log(`${ err }: Retried 2 times then quit!`)\n * });\n *\n * // Output:\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 0..1..2..3..4..5..\n * // 'Error!: Retried 2 times then quit!'\n * ```\n *\n * @see {@link retryWhen}\n *\n * @param configOrCount Either number of retry attempts before failing or a\n * {@link RetryConfig} object.\n * @return A function that returns an Observable that will resubscribe to the\n * source stream when the source stream errors, at most `count` times.\n */\nexport function retry<T>(configOrCount: number | RetryConfig = Infinity): MonoTypeOperatorFunction<T> {\n let config: RetryConfig;\n if (configOrCount && typeof configOrCount === 'object') {\n config = configOrCount;\n } else {\n config = {\n count: configOrCount as number,\n };\n }\n const { count = Infinity, delay, resetOnSuccess: resetOnSuccess = false } = config;\n\n return count <= 0\n ? identity\n : operate((source, subscriber) => {\n let soFar = 0;\n let innerSub: Subscription | null;\n const subscribeForRetry = () => {\n let syncUnsub = false;\n innerSub = source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // If we're resetting on success\n if (resetOnSuccess) {\n soFar = 0;\n }\n subscriber.next(value);\n },\n // Completions are passed through to consumer.\n undefined,\n (err) => {\n if (soFar++ < count) {\n // We are still under our retry count\n const resub = () => {\n if (innerSub) {\n innerSub.unsubscribe();\n innerSub = null;\n subscribeForRetry();\n } else {\n syncUnsub = true;\n }\n };\n\n if (delay != null) {\n // The user specified a retry delay.\n // They gave us a number, use a timer, otherwise, it's a function,\n // and we're going to call it to get a notifier.\n const notifier = typeof delay === 'number' ? timer(delay) : innerFrom(delay(err, soFar));\n const notifierSubscriber = createOperatorSubscriber(\n subscriber,\n () => {\n // After we get the first notification, we\n // unsubscribe from the notifier, because we don't want anymore\n // and we resubscribe to the source.\n notifierSubscriber.unsubscribe();\n resub();\n },\n () => {\n // The notifier completed without emitting.\n // The author is telling us they want to complete.\n subscriber.complete();\n }\n );\n notifier.subscribe(notifierSubscriber);\n } else {\n // There was no notifier given. Just resub immediately.\n resub();\n }\n } else {\n // We're past our maximum number of retries.\n // Just send along the error.\n subscriber.error(err);\n }\n }\n )\n );\n if (syncUnsub) {\n innerSub.unsubscribe();\n innerSub = null;\n subscribeForRetry();\n }\n };\n subscribeForRetry();\n });\n}\n","import { Observable } from '../Observable';\nimport { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Returns an Observable that mirrors the source Observable with the exception of an `error`. If the source Observable\n * calls `error`, this method will emit the Throwable that caused the error to the `ObservableInput` returned from `notifier`.\n * If that Observable calls `complete` or `error` then this method will call `complete` or `error` on the child\n * subscription. Otherwise this method will resubscribe to the source Observable.\n *\n * ![](retryWhen.png)\n *\n * Retry an observable sequence on error based on custom criteria.\n *\n * ## Example\n *\n * ```ts\n * import { interval, map, retryWhen, tap, delayWhen, timer } from 'rxjs';\n *\n * const source = interval(1000);\n * const result = source.pipe(\n * map(value => {\n * if (value > 5) {\n * // error will be picked up by retryWhen\n * throw value;\n * }\n * return value;\n * }),\n * retryWhen(errors =>\n * errors.pipe(\n * // log error message\n * tap(value => console.log(`Value ${ value } was too high!`)),\n * // restart in 5 seconds\n * delayWhen(value => timer(value * 1000))\n * )\n * )\n * );\n *\n * result.subscribe(value => console.log(value));\n *\n * // results:\n * // 0\n * // 1\n * // 2\n * // 3\n * // 4\n * // 5\n * // 'Value 6 was too high!'\n * // - Wait 5 seconds then repeat\n * ```\n *\n * @see {@link retry}\n *\n * @param notifier Function that receives an Observable of notifications with which a\n * user can `complete` or `error`, aborting the retry.\n * @return A function that returns an Observable that mirrors the source\n * Observable with the exception of an `error`.\n * @deprecated Will be removed in v9 or v10, use {@link retry}'s `delay` option instead.\n * Will be removed in v9 or v10. Use {@link retry}'s {@link RetryConfig#delay delay} option instead.\n * Instead of `retryWhen(() => notify$)`, use: `retry({ delay: () => notify$ })`.\n */\nexport function retryWhen<T>(notifier: (errors: Observable<any>) => ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let innerSub: Subscription | null;\n let syncResub = false;\n let errors$: Subject<any>;\n\n const subscribeForRetryWhen = () => {\n innerSub = source.subscribe(\n createOperatorSubscriber(subscriber, undefined, undefined, (err) => {\n if (!errors$) {\n errors$ = new Subject();\n innerFrom(notifier(errors$)).subscribe(\n createOperatorSubscriber(subscriber, () =>\n // If we have an innerSub, this was an asynchronous call, kick off the retry.\n // Otherwise, if we don't have an innerSub yet, that's because the inner subscription\n // call hasn't even returned yet. We've arrived here synchronously.\n // So we flag that we want to resub, such that we can ensure finalization\n // happens before we resubscribe.\n innerSub ? subscribeForRetryWhen() : (syncResub = true)\n )\n );\n }\n if (errors$) {\n // We have set up the notifier without error.\n errors$.next(err);\n }\n })\n );\n\n if (syncResub) {\n // Ensure that the inner subscription is torn down before\n // moving on to the next subscription in the synchronous case.\n // If we don't do this here, all inner subscriptions will not be\n // torn down until the entire observable is done.\n innerSub.unsubscribe();\n innerSub = null;\n // We may need to do this multiple times, so reset the flag.\n syncResub = false;\n // Resubscribe\n subscribeForRetryWhen();\n }\n };\n\n // Start the subscription\n subscribeForRetryWhen();\n });\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { noop } from '../util/noop';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits the most recently emitted value from the source Observable whenever\n * another Observable, the `notifier`, emits.\n *\n * <span class=\"informal\">It's like {@link sampleTime}, but samples whenever\n * the `notifier` `ObservableInput` emits something.</span>\n *\n * ![](sample.png)\n *\n * Whenever the `notifier` `ObservableInput` emits a value, `sample`\n * looks at the source Observable and emits whichever value it has most recently\n * emitted since the previous sampling, unless the source has not emitted\n * anything since the previous sampling. The `notifier` is subscribed to as soon\n * as the output Observable is subscribed.\n *\n * ## Example\n *\n * On every click, sample the most recent `seconds` timer\n *\n * ```ts\n * import { fromEvent, interval, sample } from 'rxjs';\n *\n * const seconds = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = seconds.pipe(sample(clicks));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param notifier The `ObservableInput` to use for sampling the\n * source Observable.\n * @return A function that returns an Observable that emits the results of\n * sampling the values emitted by the source Observable whenever the notifier\n * Observable emits value or completes.\n */\nexport function sample<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let lastValue: T | null = null;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n hasValue = true;\n lastValue = value;\n })\n );\n innerFrom(notifier).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n if (hasValue) {\n hasValue = false;\n const value = lastValue!;\n lastValue = null;\n subscriber.next(value);\n }\n },\n noop\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { sample } from './sample';\nimport { interval } from '../observable/interval';\n\n/**\n * Emits the most recently emitted value from the source Observable within\n * periodic time intervals.\n *\n * <span class=\"informal\">Samples the source Observable at periodic time\n * intervals, emitting what it samples.</span>\n *\n * ![](sampleTime.png)\n *\n * `sampleTime` periodically looks at the source Observable and emits whichever\n * value it has most recently emitted since the previous sampling, unless the\n * source has not emitted anything since the previous sampling. The sampling\n * happens periodically in time every `period` milliseconds (or the time unit\n * defined by the optional `scheduler` argument). The sampling starts as soon as\n * the output Observable is subscribed.\n *\n * ## Example\n *\n * Every second, emit the most recent click at most once\n *\n * ```ts\n * import { fromEvent, sampleTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(sampleTime(1000));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param period The sampling period expressed in milliseconds or the time unit\n * determined internally by the optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for managing the timers\n * that handle the sampling.\n * @return A function that returns an Observable that emits the results of\n * sampling the values emitted by the source Observable at the specified time\n * interval.\n */\nexport function sampleTime<T>(period: number, scheduler: SchedulerLike = asyncScheduler): MonoTypeOperatorFunction<T> {\n return sample(interval(period, scheduler));\n}\n","import { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { scanInternals } from './scanInternals';\n\nexport function scan<V, A = V>(accumulator: (acc: A | V, value: V, index: number) => A): OperatorFunction<V, V | A>;\nexport function scan<V, A>(accumulator: (acc: A, value: V, index: number) => A, seed: A): OperatorFunction<V, A>;\nexport function scan<V, A, S>(accumulator: (acc: A | S, value: V, index: number) => A, seed: S): OperatorFunction<V, A>;\n\n// TODO: link to a \"redux pattern\" section in the guide (location TBD)\n\n/**\n * Useful for encapsulating and managing state. Applies an accumulator (or \"reducer function\")\n * to each value from the source after an initial state is established -- either via\n * a `seed` value (second argument), or from the first value from the source.\n *\n * <span class=\"informal\">It's like {@link reduce}, but emits the current\n * accumulation state after each update</span>\n *\n * ![](scan.png)\n *\n * This operator maintains an internal state and emits it after processing each value as follows:\n *\n * 1. First value arrives\n * - If a `seed` value was supplied (as the second argument to `scan`), let `state = seed` and `value = firstValue`.\n * - If NO `seed` value was supplied (no second argument), let `state = firstValue` and go to 3.\n * 2. Let `state = accumulator(state, value)`.\n * - If an error is thrown by `accumulator`, notify the consumer of an error. The process ends.\n * 3. Emit `state`.\n * 4. Next value arrives, let `value = nextValue`, go to 2.\n *\n * ## Examples\n *\n * An average of previous numbers. This example shows how\n * not providing a `seed` can prime the stream with the\n * first value from the source.\n *\n * ```ts\n * import { of, scan, map } from 'rxjs';\n *\n * const numbers$ = of(1, 2, 3);\n *\n * numbers$\n * .pipe(\n * // Get the sum of the numbers coming in.\n * scan((total, n) => total + n),\n * // Get the average by dividing the sum by the total number\n * // received so far (which is 1 more than the zero-based index).\n * map((sum, index) => sum / (index + 1))\n * )\n * .subscribe(console.log);\n * ```\n *\n * The Fibonacci sequence. This example shows how you can use\n * a seed to prime accumulation process. Also... you know... Fibonacci.\n * So important to like, computers and stuff that its whiteboarded\n * in job interviews. Now you can show them the Rx version! (Please don't, haha)\n *\n * ```ts\n * import { interval, scan, map, startWith } from 'rxjs';\n *\n * const firstTwoFibs = [0, 1];\n * // An endless stream of Fibonacci numbers.\n * const fibonacci$ = interval(1000).pipe(\n * // Scan to get the fibonacci numbers (after 0, 1)\n * scan(([a, b]) => [b, a + b], firstTwoFibs),\n * // Get the second number in the tuple, it's the one you calculated\n * map(([, n]) => n),\n * // Start with our first two digits :)\n * startWith(...firstTwoFibs)\n * );\n *\n * fibonacci$.subscribe(console.log);\n * ```\n *\n * @see {@link expand}\n * @see {@link mergeScan}\n * @see {@link reduce}\n * @see {@link switchScan}\n *\n * @param accumulator A \"reducer function\". This will be called for each value after an initial state is\n * acquired.\n * @param seed The initial state. If this is not provided, the first value from the source will\n * be used as the initial state, and emitted without going through the accumulator. All subsequent values\n * will be processed by the accumulator function. If this is provided, all values will go through\n * the accumulator function.\n * @return A function that returns an Observable of the accumulated values.\n */\nexport function scan<V, A, S>(accumulator: (acc: V | A | S, value: V, index: number) => A, seed?: S): OperatorFunction<V, V | A> {\n // providing a seed of `undefined` *should* be valid and trigger\n // hasSeed! so don't use `seed !== undefined` checks!\n // For this reason, we have to check it here at the original call site\n // otherwise inside Operator/Subscriber we won't know if `undefined`\n // means they didn't provide anything or if they literally provided `undefined`\n return operate(scanInternals(accumulator, seed as S, arguments.length >= 2, true));\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Compares all values of two observables in sequence using an optional comparator function\n * and returns an observable of a single boolean value representing whether or not the two sequences\n * are equal.\n *\n * <span class=\"informal\">Checks to see of all values emitted by both observables are equal, in order.</span>\n *\n * ![](sequenceEqual.png)\n *\n * `sequenceEqual` subscribes to source observable and `compareTo` `ObservableInput` (that internally\n * gets converted to an observable) and buffers incoming values from each observable. Whenever either\n * observable emits a value, the value is buffered and the buffers are shifted and compared from the bottom\n * up; If any value pair doesn't match, the returned observable will emit `false` and complete. If one of the\n * observables completes, the operator will wait for the other observable to complete; If the other\n * observable emits before completing, the returned observable will emit `false` and complete. If one observable never\n * completes or emits after the other completes, the returned observable will never complete.\n *\n * ## Example\n *\n * Figure out if the Konami code matches\n *\n * ```ts\n * import { from, fromEvent, map, bufferCount, mergeMap, sequenceEqual } from 'rxjs';\n *\n * const codes = from([\n * 'ArrowUp',\n * 'ArrowUp',\n * 'ArrowDown',\n * 'ArrowDown',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'ArrowLeft',\n * 'ArrowRight',\n * 'KeyB',\n * 'KeyA',\n * 'Enter', // no start key, clearly.\n * ]);\n *\n * const keys = fromEvent<KeyboardEvent>(document, 'keyup').pipe(map(e => e.code));\n * const matches = keys.pipe(\n * bufferCount(11, 1),\n * mergeMap(last11 => from(last11).pipe(sequenceEqual(codes)))\n * );\n * matches.subscribe(matched => console.log('Successful cheat at Contra? ', matched));\n * ```\n *\n * @see {@link combineLatest}\n * @see {@link zip}\n * @see {@link withLatestFrom}\n *\n * @param compareTo The `ObservableInput` sequence to compare the source sequence to.\n * @param comparator An optional function to compare each value pair.\n *\n * @return A function that returns an Observable that emits a single boolean\n * value representing whether or not the values emitted by the source\n * Observable and provided `ObservableInput` were equal in sequence.\n */\nexport function sequenceEqual<T>(\n compareTo: ObservableInput<T>,\n comparator: (a: T, b: T) => boolean = (a, b) => a === b\n): OperatorFunction<T, boolean> {\n return operate((source, subscriber) => {\n // The state for the source observable\n const aState = createState<T>();\n // The state for the compareTo observable;\n const bState = createState<T>();\n\n /** A utility to emit and complete */\n const emit = (isEqual: boolean) => {\n subscriber.next(isEqual);\n subscriber.complete();\n };\n\n /**\n * Creates a subscriber that subscribes to one of the sources, and compares its collected\n * state -- `selfState` -- to the other source's collected state -- `otherState`. This\n * is used for both streams.\n */\n const createSubscriber = (selfState: SequenceState<T>, otherState: SequenceState<T>) => {\n const sequenceEqualSubscriber = createOperatorSubscriber(\n subscriber,\n (a: T) => {\n const { buffer, complete } = otherState;\n if (buffer.length === 0) {\n // If there's no values in the other buffer\n // and the other stream is complete, we know\n // this isn't a match, because we got one more value.\n // Otherwise, we push onto our buffer, so when the other\n // stream emits, it can pull this value off our buffer and check it\n // at the appropriate time.\n complete ? emit(false) : selfState.buffer.push(a);\n } else {\n // If the other stream *does* have values in its buffer,\n // pull the oldest one off so we can compare it to what we\n // just got. If it wasn't a match, emit `false` and complete.\n !comparator(a, buffer.shift()!) && emit(false);\n }\n },\n () => {\n // Or observable completed\n selfState.complete = true;\n const { complete, buffer } = otherState;\n // If the other observable is also complete, and there's\n // still stuff left in their buffer, it doesn't match, if their\n // buffer is empty, then it does match. This is because we can't\n // possibly get more values here anymore.\n complete && emit(buffer.length === 0);\n // Be sure to clean up our stream as soon as possible if we can.\n sequenceEqualSubscriber?.unsubscribe();\n }\n );\n\n return sequenceEqualSubscriber;\n };\n\n // Subscribe to each source.\n source.subscribe(createSubscriber(aState, bState));\n innerFrom(compareTo).subscribe(createSubscriber(bState, aState));\n });\n}\n\n/**\n * A simple structure for the data used to test each sequence\n */\ninterface SequenceState<T> {\n /** A temporary store for arrived values before they are checked */\n buffer: T[];\n /** Whether or not the sequence source has completed. */\n complete: boolean;\n}\n\n/**\n * Creates a simple structure that is used to represent\n * data used to test each sequence.\n */\nfunction createState<T>(): SequenceState<T> {\n return {\n buffer: [],\n complete: false,\n };\n}\n","import { innerFrom } from '../observable/innerFrom';\nimport { Subject } from '../Subject';\nimport { SafeSubscriber } from '../Subscriber';\nimport { Subscription } from '../Subscription';\nimport { MonoTypeOperatorFunction, SubjectLike, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\n\nexport interface ShareConfig<T> {\n /**\n * The factory used to create the subject that will connect the source observable to\n * multicast consumers.\n */\n connector?: () => SubjectLike<T>;\n /**\n * If `true`, the resulting observable will reset internal state on error from source and return to a \"cold\" state. This\n * allows the resulting observable to be \"retried\" in the event of an error.\n * If `false`, when an error comes from the source it will push the error into the connecting subject, and the subject\n * will remain the connecting subject, meaning the resulting observable will not go \"cold\" again, and subsequent retries\n * or resubscriptions will resubscribe to that same subject. In all cases, RxJS subjects will emit the same error again, however\n * {@link ReplaySubject} will also push its buffered values before pushing the error.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnError?: boolean | ((error: any) => ObservableInput<any>);\n /**\n * If `true`, the resulting observable will reset internal state on completion from source and return to a \"cold\" state. This\n * allows the resulting observable to be \"repeated\" after it is done.\n * If `false`, when the source completes, it will push the completion through the connecting subject, and the subject\n * will remain the connecting subject, meaning the resulting observable will not go \"cold\" again, and subsequent repeats\n * or resubscriptions will resubscribe to that same subject.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnComplete?: boolean | (() => ObservableInput<any>);\n /**\n * If `true`, when the number of subscribers to the resulting observable reaches zero due to those subscribers unsubscribing, the\n * internal state will be reset and the resulting observable will return to a \"cold\" state. This means that the next\n * time the resulting observable is subscribed to, a new subject will be created and the source will be subscribed to\n * again.\n * If `false`, when the number of subscribers to the resulting observable reaches zero due to unsubscription, the subject\n * will remain connected to the source, and new subscriptions to the result will be connected through that same subject.\n * It is also possible to pass a notifier factory returning an `ObservableInput` instead which grants more fine-grained\n * control over how and when the reset should happen. This allows behaviors like conditional or delayed resets.\n */\n resetOnRefCountZero?: boolean | (() => ObservableInput<any>);\n}\n\nexport function share<T>(): MonoTypeOperatorFunction<T>;\n\nexport function share<T>(options: ShareConfig<T>): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns a new Observable that multicasts (shares) the original Observable. As long as there is at least one\n * Subscriber this Observable will be subscribed and emitting data. When all subscribers have unsubscribed it will\n * unsubscribe from the source Observable. Because the Observable is multicasting it makes the stream `hot`.\n * This is an alias for `multicast(() => new Subject()), refCount()`.\n *\n * The subscription to the underlying source Observable can be reset (unsubscribe and resubscribe for new subscribers),\n * if the subscriber count to the shared observable drops to 0, or if the source Observable errors or completes. It is\n * possible to use notifier factories for the resets to allow for behaviors like conditional or delayed resets. Please\n * note that resetting on error or complete of the source Observable does not behave like a transparent retry or restart\n * of the source because the error or complete will be forwarded to all subscribers and their subscription will be\n * closed. Only new subscribers after a reset on error or complete happened will cause a fresh subscription to the\n * source. To achieve transparent retries or restarts pipe the source through appropriate operators before sharing.\n *\n * ![](share.png)\n *\n * ## Example\n *\n * Generate new multicast Observable from the `source` Observable value\n *\n * ```ts\n * import { interval, tap, map, take, share } from 'rxjs';\n *\n * const source = interval(1000).pipe(\n * tap(x => console.log('Processing: ', x)),\n * map(x => x * x),\n * take(6),\n * share()\n * );\n *\n * source.subscribe(x => console.log('subscription 1: ', x));\n * source.subscribe(x => console.log('subscription 2: ', x));\n *\n * // Logs:\n * // Processing: 0\n * // subscription 1: 0\n * // subscription 2: 0\n * // Processing: 1\n * // subscription 1: 1\n * // subscription 2: 1\n * // Processing: 2\n * // subscription 1: 4\n * // subscription 2: 4\n * // Processing: 3\n * // subscription 1: 9\n * // subscription 2: 9\n * // Processing: 4\n * // subscription 1: 16\n * // subscription 2: 16\n * // Processing: 5\n * // subscription 1: 25\n * // subscription 2: 25\n * ```\n *\n * ## Example with notifier factory: Delayed reset\n *\n * ```ts\n * import { interval, take, share, timer } from 'rxjs';\n *\n * const source = interval(1000).pipe(\n * take(3),\n * share({\n * resetOnRefCountZero: () => timer(1000)\n * })\n * );\n *\n * const subscriptionOne = source.subscribe(x => console.log('subscription 1: ', x));\n * setTimeout(() => subscriptionOne.unsubscribe(), 1300);\n *\n * setTimeout(() => source.subscribe(x => console.log('subscription 2: ', x)), 1700);\n *\n * setTimeout(() => source.subscribe(x => console.log('subscription 3: ', x)), 5000);\n *\n * // Logs:\n * // subscription 1: 0\n * // (subscription 1 unsubscribes here)\n * // (subscription 2 subscribes here ~400ms later, source was not reset)\n * // subscription 2: 1\n * // subscription 2: 2\n * // (subscription 2 unsubscribes here)\n * // (subscription 3 subscribes here ~2000ms later, source did reset before)\n * // subscription 3: 0\n * // subscription 3: 1\n * // subscription 3: 2\n * ```\n *\n * @see {@link shareReplay}\n *\n * @return A function that returns an Observable that mirrors the source.\n */\nexport function share<T>(options: ShareConfig<T> = {}): MonoTypeOperatorFunction<T> {\n const { connector = () => new Subject<T>(), resetOnError = true, resetOnComplete = true, resetOnRefCountZero = true } = options;\n // It's necessary to use a wrapper here, as the _operator_ must be\n // referentially transparent. Otherwise, it cannot be used in calls to the\n // static `pipe` function - to create a partial pipeline.\n //\n // The _operator function_ - the function returned by the _operator_ - will\n // not be referentially transparent - as it shares its source - but the\n // _operator function_ is called when the complete pipeline is composed via a\n // call to a source observable's `pipe` method - not when the static `pipe`\n // function is called.\n return (wrapperSource) => {\n let connection: SafeSubscriber<T> | undefined;\n let resetConnection: Subscription | undefined;\n let subject: SubjectLike<T> | undefined;\n let refCount = 0;\n let hasCompleted = false;\n let hasErrored = false;\n\n const cancelReset = () => {\n resetConnection?.unsubscribe();\n resetConnection = undefined;\n };\n // Used to reset the internal state to a \"cold\"\n // state, as though it had never been subscribed to.\n const reset = () => {\n cancelReset();\n connection = subject = undefined;\n hasCompleted = hasErrored = false;\n };\n const resetAndUnsubscribe = () => {\n // We need to capture the connection before\n // we reset (if we need to reset).\n const conn = connection;\n reset();\n conn?.unsubscribe();\n };\n\n return operate<T, T>((source, subscriber) => {\n refCount++;\n if (!hasErrored && !hasCompleted) {\n cancelReset();\n }\n\n // Create the subject if we don't have one yet. Grab a local reference to\n // it as well, which avoids non-null assertions when using it and, if we\n // connect to it now, then error/complete need a reference after it was\n // reset.\n const dest = (subject = subject ?? connector());\n\n // Add the finalization directly to the subscriber - instead of returning it -\n // so that the handling of the subscriber's unsubscription will be wired\n // up _before_ the subscription to the source occurs. This is done so that\n // the assignment to the source connection's `closed` property will be seen\n // by synchronous firehose sources.\n subscriber.add(() => {\n refCount--;\n\n // If we're resetting on refCount === 0, and it's 0, we only want to do\n // that on \"unsubscribe\", really. Resetting on error or completion is a different\n // configuration.\n if (refCount === 0 && !hasErrored && !hasCompleted) {\n resetConnection = handleReset(resetAndUnsubscribe, resetOnRefCountZero);\n }\n });\n\n // The following line adds the subscription to the subscriber passed.\n // Basically, `subscriber === dest.subscribe(subscriber)` is `true`.\n dest.subscribe(subscriber);\n\n if (\n !connection &&\n // Check this shareReplay is still activate - it can be reset to 0\n // and be \"unsubscribed\" _before_ it actually subscribes.\n // If we were to subscribe then, it'd leak and get stuck.\n refCount > 0\n ) {\n // We need to create a subscriber here - rather than pass an observer and\n // assign the returned subscription to connection - because it's possible\n // for reentrant subscriptions to the shared observable to occur and in\n // those situations we want connection to be already-assigned so that we\n // don't create another connection to the source.\n connection = new SafeSubscriber({\n next: (value) => dest.next(value),\n error: (err) => {\n hasErrored = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnError, err);\n dest.error(err);\n },\n complete: () => {\n hasCompleted = true;\n cancelReset();\n resetConnection = handleReset(reset, resetOnComplete);\n dest.complete();\n },\n });\n innerFrom(source).subscribe(connection);\n }\n })(wrapperSource);\n };\n}\n\nfunction handleReset<T extends unknown[] = never[]>(\n reset: () => void,\n on: boolean | ((...args: T) => ObservableInput<any>),\n ...args: T\n): Subscription | undefined {\n if (on === true) {\n reset();\n return;\n }\n\n if (on === false) {\n return;\n }\n\n const onSubscriber = new SafeSubscriber({\n next: () => {\n onSubscriber.unsubscribe();\n reset();\n },\n });\n\n return innerFrom(on(...args)).subscribe(onSubscriber);\n}\n","import { ReplaySubject } from '../ReplaySubject';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { share } from './share';\n\nexport interface ShareReplayConfig {\n bufferSize?: number;\n windowTime?: number;\n refCount: boolean;\n scheduler?: SchedulerLike;\n}\n\nexport function shareReplay<T>(config: ShareReplayConfig): MonoTypeOperatorFunction<T>;\nexport function shareReplay<T>(bufferSize?: number, windowTime?: number, scheduler?: SchedulerLike): MonoTypeOperatorFunction<T>;\n\n/**\n * Share source and replay specified number of emissions on subscription.\n *\n * This operator is a specialization of `replay` that connects to a source observable\n * and multicasts through a `ReplaySubject` constructed with the specified arguments.\n * A successfully completed source will stay cached in the `shareReplay`ed observable forever,\n * but an errored source can be retried.\n *\n * ## Why use `shareReplay`?\n *\n * You generally want to use `shareReplay` when you have side-effects or taxing computations\n * that you do not wish to be executed amongst multiple subscribers.\n * It may also be valuable in situations where you know you will have late subscribers to\n * a stream that need access to previously emitted values.\n * This ability to replay values on subscription is what differentiates {@link share} and `shareReplay`.\n *\n * ## Reference counting\n *\n * By default `shareReplay` will use `refCount` of false, meaning that it will _not_ unsubscribe the\n * source when the reference counter drops to zero, i.e. the inner `ReplaySubject` will _not_ be unsubscribed\n * (and potentially run for ever).\n * This is the default as it is expected that `shareReplay` is often used to keep around expensive to setup\n * observables which we want to keep running instead of having to do the expensive setup again.\n *\n * As of RXJS version 6.4.0 a new overload signature was added to allow for manual control over what\n * happens when the operators internal reference counter drops to zero.\n * If `refCount` is true, the source will be unsubscribed from once the reference count drops to zero, i.e.\n * the inner `ReplaySubject` will be unsubscribed. All new subscribers will receive value emissions from a\n * new `ReplaySubject` which in turn will cause a new subscription to the source observable.\n *\n * ## Examples\n *\n * Example with a third subscriber coming late to the party\n *\n * ```ts\n * import { interval, take, shareReplay } from 'rxjs';\n *\n * const shared$ = interval(2000).pipe(\n * take(6),\n * shareReplay(3)\n * );\n *\n * shared$.subscribe(x => console.log('sub A: ', x));\n * shared$.subscribe(y => console.log('sub B: ', y));\n *\n * setTimeout(() => {\n * shared$.subscribe(y => console.log('sub C: ', y));\n * }, 11000);\n *\n * // Logs:\n * // (after ~2000 ms)\n * // sub A: 0\n * // sub B: 0\n * // (after ~4000 ms)\n * // sub A: 1\n * // sub B: 1\n * // (after ~6000 ms)\n * // sub A: 2\n * // sub B: 2\n * // (after ~8000 ms)\n * // sub A: 3\n * // sub B: 3\n * // (after ~10000 ms)\n * // sub A: 4\n * // sub B: 4\n * // (after ~11000 ms, sub C gets the last 3 values)\n * // sub C: 2\n * // sub C: 3\n * // sub C: 4\n * // (after ~12000 ms)\n * // sub A: 5\n * // sub B: 5\n * // sub C: 5\n * ```\n *\n * Example for `refCount` usage\n *\n * ```ts\n * import { Observable, tap, interval, shareReplay, take } from 'rxjs';\n *\n * const log = <T>(name: string, source: Observable<T>) => source.pipe(\n * tap({\n * subscribe: () => console.log(`${ name }: subscribed`),\n * next: value => console.log(`${ name }: ${ value }`),\n * complete: () => console.log(`${ name }: completed`),\n * finalize: () => console.log(`${ name }: unsubscribed`)\n * })\n * );\n *\n * const obs$ = log('source', interval(1000));\n *\n * const shared$ = log('shared', obs$.pipe(\n * shareReplay({ bufferSize: 1, refCount: true }),\n * take(2)\n * ));\n *\n * shared$.subscribe(x => console.log('sub A: ', x));\n * shared$.subscribe(y => console.log('sub B: ', y));\n *\n * // PRINTS:\n * // shared: subscribed <-- reference count = 1\n * // source: subscribed\n * // shared: subscribed <-- reference count = 2\n * // source: 0\n * // shared: 0\n * // sub A: 0\n * // shared: 0\n * // sub B: 0\n * // source: 1\n * // shared: 1\n * // sub A: 1\n * // shared: completed <-- take(2) completes the subscription for sub A\n * // shared: unsubscribed <-- reference count = 1\n * // shared: 1\n * // sub B: 1\n * // shared: completed <-- take(2) completes the subscription for sub B\n * // shared: unsubscribed <-- reference count = 0\n * // source: unsubscribed <-- replaySubject unsubscribes from source observable because the reference count dropped to 0 and refCount is true\n *\n * // In case of refCount being false, the unsubscribe is never called on the source and the source would keep on emitting, even if no subscribers\n * // are listening.\n * // source: 2\n * // source: 3\n * // source: 4\n * // ...\n * ```\n *\n * @see {@link publish}\n * @see {@link share}\n * @see {@link publishReplay}\n *\n * @param configOrBufferSize Maximum element count of the replay buffer or {@link ShareReplayConfig configuration}\n * object.\n * @param windowTime Maximum time length of the replay buffer in milliseconds.\n * @param scheduler Scheduler where connected observers within the selector function\n * will be invoked on.\n * @return A function that returns an Observable sequence that contains the\n * elements of a sequence produced by multicasting the source sequence within a\n * selector function.\n */\nexport function shareReplay<T>(\n configOrBufferSize?: ShareReplayConfig | number,\n windowTime?: number,\n scheduler?: SchedulerLike\n): MonoTypeOperatorFunction<T> {\n let bufferSize: number;\n let refCount = false;\n if (configOrBufferSize && typeof configOrBufferSize === 'object') {\n ({ bufferSize = Infinity, windowTime = Infinity, refCount = false, scheduler } = configOrBufferSize);\n } else {\n bufferSize = (configOrBufferSize ?? Infinity) as number;\n }\n return share<T>({\n connector: () => new ReplaySubject(bufferSize, windowTime, scheduler),\n resetOnError: true,\n resetOnComplete: false,\n resetOnRefCountZero: refCount,\n });\n}\n","import { Observable } from '../Observable';\nimport { EmptyError } from '../util/EmptyError';\n\nimport { MonoTypeOperatorFunction, OperatorFunction, TruthyTypesOf } from '../types';\nimport { SequenceError } from '../util/SequenceError';\nimport { NotFoundError } from '../util/NotFoundError';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function single<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an observable that asserts that only one value is\n * emitted from the observable that matches the predicate. If no\n * predicate is provided, then it will assert that the observable\n * only emits one value.\n *\n * If the source Observable did not emit `next` before completion, it\n * will emit an {@link EmptyError} to the Observer's `error` callback.\n *\n * In the event that two values are found that match the predicate,\n * or when there are two values emitted and no predicate, it will\n * emit a {@link SequenceError} to the Observer's `error` callback.\n *\n * In the event that no values match the predicate, if one is provided,\n * it will emit a {@link NotFoundError} to the Observer's `error` callback.\n *\n * ## Example\n *\n * Expect only `name` beginning with `'B'`\n *\n * ```ts\n * import { of, single } from 'rxjs';\n *\n * const source1 = of(\n * { name: 'Ben' },\n * { name: 'Tracy' },\n * { name: 'Laney' },\n * { name: 'Lily' }\n * );\n *\n * source1\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe(x => console.log(x));\n * // Emits 'Ben'\n *\n *\n * const source2 = of(\n * { name: 'Ben' },\n * { name: 'Tracy' },\n * { name: 'Bradley' },\n * { name: 'Lincoln' }\n * );\n *\n * source2\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe({ error: err => console.error(err) });\n * // Error emitted: SequenceError('Too many values match')\n *\n *\n * const source3 = of(\n * { name: 'Laney' },\n * { name: 'Tracy' },\n * { name: 'Lily' },\n * { name: 'Lincoln' }\n * );\n *\n * source3\n * .pipe(single(x => x.name.startsWith('B')))\n * .subscribe({ error: err => console.error(err) });\n * // Error emitted: NotFoundError('No values match')\n * ```\n *\n * @see {@link first}\n * @see {@link find}\n * @see {@link findIndex}\n * @see {@link elementAt}\n *\n * @throws {NotFoundError} Delivers a `NotFoundError` to the Observer's `error`\n * callback if the Observable completes before any `next` notification was sent.\n * @throws {SequenceError} Delivers a `SequenceError` if more than one value is\n * emitted that matches the provided predicate. If no predicate is provided, it\n * will deliver a `SequenceError` if more than one value comes from the source.\n * @throws {EmptyError} Delivers an `EmptyError` if no values were `next`ed prior\n * to completion.\n *\n * @param predicate A predicate function to evaluate items emitted by the source\n * Observable.\n * @return A function that returns an Observable that emits the single item\n * emitted by the source Observable that matches the predicate.\n */\nexport function single<T>(predicate?: (value: T, index: number, source: Observable<T>) => boolean): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let hasValue = false;\n let singleValue: T;\n let seenValue = false;\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n seenValue = true;\n if (!predicate || predicate(value, index++, source)) {\n hasValue && subscriber.error(new SequenceError('Too many matching values'));\n hasValue = true;\n singleValue = value;\n }\n },\n () => {\n if (hasValue) {\n subscriber.next(singleValue);\n subscriber.complete();\n } else {\n subscriber.error(seenValue ? new NotFoundError('No matching values') : new EmptyError());\n }\n }\n )\n );\n });\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { filter } from './filter';\n\n/**\n * Returns an Observable that skips the first `count` items emitted by the source Observable.\n *\n * ![](skip.png)\n *\n * Skips the values until the sent notifications are equal or less than provided skip count. It raises\n * an error if skip count is equal or more than the actual number of emits and source raises an error.\n *\n * ## Example\n *\n * Skip the values before the emission\n *\n * ```ts\n * import { interval, skip } from 'rxjs';\n *\n * // emit every half second\n * const source = interval(500);\n * // skip the first 10 emitted values\n * const result = source.pipe(skip(10));\n *\n * result.subscribe(value => console.log(value));\n * // output: 10...11...12...13...\n * ```\n *\n * @see {@link last}\n * @see {@link skipWhile}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n *\n * @param count The number of times, items emitted by source Observable should be skipped.\n * @return A function that returns an Observable that skips the first `count`\n * values emitted by the source Observable.\n */\nexport function skip<T>(count: number): MonoTypeOperatorFunction<T> {\n return filter((_, index) => count <= index);\n}\n","import { MonoTypeOperatorFunction } from '../types';\nimport { identity } from '../util/identity';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Skip a specified number of values before the completion of an observable.\n *\n * ![](skipLast.png)\n *\n * Returns an observable that will emit values as soon as it can, given a number of\n * skipped values. For example, if you `skipLast(3)` on a source, when the source\n * emits its fourth value, the first value the source emitted will finally be emitted\n * from the returned observable, as it is no longer part of what needs to be skipped.\n *\n * All values emitted by the result of `skipLast(N)` will be delayed by `N` emissions,\n * as each value is held in a buffer until enough values have been emitted that that\n * the buffered value may finally be sent to the consumer.\n *\n * After subscribing, unsubscribing will not result in the emission of the buffered\n * skipped values.\n *\n * ## Example\n *\n * Skip the last 2 values of an observable with many values\n *\n * ```ts\n * import { of, skipLast } from 'rxjs';\n *\n * const numbers = of(1, 2, 3, 4, 5);\n * const skipLastTwo = numbers.pipe(skipLast(2));\n * skipLastTwo.subscribe(x => console.log(x));\n *\n * // Results in:\n * // 1 2 3\n * // (4 and 5 are skipped)\n * ```\n *\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipWhile}\n * @see {@link take}\n *\n * @param skipCount Number of elements to skip from the end of the source Observable.\n * @return A function that returns an Observable that skips the last `count`\n * values emitted by the source Observable.\n */\nexport function skipLast<T>(skipCount: number): MonoTypeOperatorFunction<T> {\n return skipCount <= 0\n ? // For skipCounts less than or equal to zero, we are just mirroring the source.\n identity\n : operate((source, subscriber) => {\n // A ring buffer to hold the values while we wait to see\n // if we can emit it or it's part of the \"skipped\" last values.\n // Note that it is the _same size_ as the skip count.\n let ring: T[] = new Array(skipCount);\n // The number of values seen so far. This is used to get\n // the index of the current value when it arrives.\n let seen = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n // Get the index of the value we have right now\n // relative to all other values we've seen, then\n // increment `seen`. This ensures we've moved to\n // the next slot in our ring buffer.\n const valueIndex = seen++;\n if (valueIndex < skipCount) {\n // If we haven't seen enough values to fill our buffer yet,\n // Then we aren't to a number of seen values where we can\n // emit anything, so let's just start by filling the ring buffer.\n ring[valueIndex] = value;\n } else {\n // We are traversing over the ring array in such\n // a way that when we get to the end, we loop back\n // and go to the start.\n const index = valueIndex % skipCount;\n // Pull the oldest value out so we can emit it,\n // and stuff the new value in it's place.\n const oldValue = ring[index];\n ring[index] = value;\n // Emit the old value. It is important that this happens\n // after we swap the value in the buffer, if it happens\n // before we swap the value in the buffer, then a synchronous\n // source can get the buffer out of whack.\n subscriber.next(oldValue);\n }\n })\n );\n\n return () => {\n // Release our values in memory\n ring = null!;\n };\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\n\n/**\n * Returns an Observable that skips items emitted by the source Observable until a second Observable emits an item.\n *\n * The `skipUntil` operator causes the observable stream to skip the emission of values until the passed in observable\n * emits the first value. This can be particularly useful in combination with user interactions, responses of HTTP\n * requests or waiting for specific times to pass by.\n *\n * ![](skipUntil.png)\n *\n * Internally, the `skipUntil` operator subscribes to the passed in `notifier` `ObservableInput` (which gets converted\n * to an Observable) in order to recognize the emission of its first value. When `notifier` emits next, the operator\n * unsubscribes from it and starts emitting the values of the *source* observable until it completes or errors. It\n * will never let the *source* observable emit any values if the `notifier` completes or throws an error without\n * emitting a value before.\n *\n * ## Example\n *\n * In the following example, all emitted values of the interval observable are skipped until the user clicks anywhere\n * within the page\n *\n * ```ts\n * import { interval, fromEvent, skipUntil } from 'rxjs';\n *\n * const intervalObservable = interval(1000);\n * const click = fromEvent(document, 'click');\n *\n * const emitAfterClick = intervalObservable.pipe(\n * skipUntil(click)\n * );\n * // clicked at 4.6s. output: 5...6...7...8........ or\n * // clicked at 7.3s. output: 8...9...10..11.......\n * emitAfterClick.subscribe(value => console.log(value));\n * ```\n *\n * @see {@link last}\n * @see {@link skip}\n * @see {@link skipWhile}\n * @see {@link skipLast}\n *\n * @param notifier An `ObservableInput` that has to emit an item before the source Observable elements begin to\n * be mirrored by the resulting Observable.\n * @return A function that returns an Observable that skips items from the\n * source Observable until the `notifier` Observable emits an item, then emits the\n * remaining items.\n */\nexport function skipUntil<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let taking = false;\n\n const skipSubscriber = createOperatorSubscriber(\n subscriber,\n () => {\n skipSubscriber?.unsubscribe();\n taking = true;\n },\n noop\n );\n\n innerFrom(notifier).subscribe(skipSubscriber);\n\n source.subscribe(createOperatorSubscriber(subscriber, (value) => taking && subscriber.next(value)));\n });\n}\n","import { Falsy, MonoTypeOperatorFunction, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function skipWhile<T>(predicate: BooleanConstructor): OperatorFunction<T, Extract<T, Falsy> extends never ? never : T>;\nexport function skipWhile<T>(predicate: (value: T, index: number) => true): OperatorFunction<T, never>;\nexport function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Returns an Observable that skips all items emitted by the source Observable as long as a specified condition holds\n * true, but emits all further source items as soon as the condition becomes false.\n *\n * ![](skipWhile.png)\n *\n * Skips all the notifications with a truthy predicate. It will not skip the notifications when the predicate is falsy.\n * It can also be skipped using index. Once the predicate is true, it will not be called again.\n *\n * ## Example\n *\n * Skip some super heroes\n *\n * ```ts\n * import { from, skipWhile } from 'rxjs';\n *\n * const source = from(['Green Arrow', 'SuperMan', 'Flash', 'SuperGirl', 'Black Canary'])\n * // Skip the heroes until SuperGirl\n * const example = source.pipe(skipWhile(hero => hero !== 'SuperGirl'));\n * // output: SuperGirl, Black Canary\n * example.subscribe(femaleHero => console.log(femaleHero));\n * ```\n *\n * Skip values from the array until index 5\n *\n * ```ts\n * import { from, skipWhile } from 'rxjs';\n *\n * const source = from([1, 2, 3, 4, 5, 6, 7, 9, 10]);\n * const example = source.pipe(skipWhile((_, i) => i !== 5));\n * // output: 6, 7, 9, 10\n * example.subscribe(value => console.log(value));\n * ```\n *\n * @see {@link last}\n * @see {@link skip}\n * @see {@link skipUntil}\n * @see {@link skipLast}\n *\n * @param predicate A function to test each item emitted from the source Observable.\n * @return A function that returns an Observable that begins emitting items\n * emitted by the source Observable when the specified predicate becomes false.\n */\nexport function skipWhile<T>(predicate: (value: T, index: number) => boolean): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let taking = false;\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => (taking || (taking = !predicate(value, index++))) && subscriber.next(value))\n );\n });\n}\n","import { concat } from '../observable/concat';\nimport { OperatorFunction, SchedulerLike, ValueFromArray } from '../types';\nimport { popScheduler } from '../util/args';\nimport { operate } from '../util/lift';\n\n// Devs are more likely to pass null or undefined than they are a scheduler\n// without accompanying values. To make things easier for (naughty) devs who\n// use the `strictNullChecks: false` TypeScript compiler option, these\n// overloads with explicit null and undefined values are included.\n\nexport function startWith<T>(value: null): OperatorFunction<T, T | null>;\nexport function startWith<T>(value: undefined): OperatorFunction<T, T | undefined>;\n\n/** @deprecated The `scheduler` parameter will be removed in v8. Use `scheduled` and `concatAll`. Details: https://rxjs.dev/deprecations/scheduler-argument */\nexport function startWith<T, A extends readonly unknown[] = T[]>(\n ...valuesAndScheduler: [...A, SchedulerLike]\n): OperatorFunction<T, T | ValueFromArray<A>>;\nexport function startWith<T, A extends readonly unknown[] = T[]>(...values: A): OperatorFunction<T, T | ValueFromArray<A>>;\n\n/**\n * Returns an observable that, at the moment of subscription, will synchronously emit all\n * values provided to this operator, then subscribe to the source and mirror all of its emissions\n * to subscribers.\n *\n * This is a useful way to know when subscription has occurred on an existing observable.\n *\n * <span class=\"informal\">First emits its arguments in order, and then any\n * emissions from the source.</span>\n *\n * ![](startWith.png)\n *\n * ## Examples\n *\n * Emit a value when a timer starts.\n *\n * ```ts\n * import { timer, map, startWith } from 'rxjs';\n *\n * timer(1000)\n * .pipe(\n * map(() => 'timer emit'),\n * startWith('timer start')\n * )\n * .subscribe(x => console.log(x));\n *\n * // results:\n * // 'timer start'\n * // 'timer emit'\n * ```\n *\n * @param values Items you want the modified Observable to emit first.\n * @return A function that returns an Observable that synchronously emits\n * provided values before subscribing to the source Observable.\n *\n * @see {@link endWith}\n * @see {@link finalize}\n * @see {@link concat}\n */\nexport function startWith<T, D>(...values: D[]): OperatorFunction<T, T | D> {\n const scheduler = popScheduler(values);\n return operate((source, subscriber) => {\n // Here we can't pass `undefined` as a scheduler, because if we did, the\n // code inside of `concat` would be confused by the `undefined`, and treat it\n // like an invalid observable. So we have to split it two different ways.\n (scheduler ? concat(values, source, scheduler) : concat(values, source)).subscribe(subscriber);\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { innerFrom } from '../observable/innerFrom';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/* tslint:disable:max-line-length */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<T, O extends ObservableInput<any>>(\n project: (value: T, index: number) => O,\n resultSelector: undefined\n): OperatorFunction<T, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMap<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, 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, emitting values only from the most recently projected Observable.\n *\n * <span class=\"informal\">Maps each value to an Observable, then flattens all of\n * these inner Observables using {@link switchAll}.</span>\n *\n * ![](switchMap.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 time it observes one of these\n * inner Observables, the output Observable begins emitting the items emitted by\n * that inner Observable. When a new inner Observable is emitted, `switchMap`\n * stops emitting items from the earlier-emitted inner Observable and begins\n * emitting items from the new one. It continues to behave like this for\n * subsequent inner Observables.\n *\n * ## Example\n *\n * Generate new Observable according to source Observable values\n *\n * ```ts\n * import { of, switchMap } from 'rxjs';\n *\n * const switched = of(1, 2, 3).pipe(switchMap(x => of(x, x ** 2, x ** 3)));\n * switched.subscribe(x => console.log(x));\n * // outputs\n * // 1\n * // 1\n * // 1\n * // 2\n * // 4\n * // 8\n * // 3\n * // 9\n * // 27\n * ```\n *\n * Restart an interval Observable on every click event\n *\n * ```ts\n * import { fromEvent, switchMap, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMap(() => interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMap}\n * @see {@link exhaustMap}\n * @see {@link mergeMap}\n * @see {@link switchAll}\n * @see {@link switchMapTo}\n *\n * @param project A function that, when applied to an item emitted by the source\n * Observable, returns an Observable.\n * @return A function that returns an Observable that emits the result of\n * applying the projection function (and the optional deprecated\n * `resultSelector`) to each item emitted by the source Observable and taking\n * only the values from the most recently projected inner Observable.\n */\nexport function switchMap<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 operate((source, subscriber) => {\n let innerSubscriber: Subscriber<ObservedValueOf<O>> | null = null;\n let index = 0;\n // Whether or not the source subscription has completed\n let isComplete = false;\n\n // We only complete the result if the source is complete AND we don't have an active inner subscription.\n // This is called both when the source completes and when the inners complete.\n const checkComplete = () => isComplete && !innerSubscriber && subscriber.complete();\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n // Cancel the previous inner subscription if there was one\n innerSubscriber?.unsubscribe();\n let innerIndex = 0;\n const outerIndex = index++;\n // Start the next inner subscription\n innerFrom(project(value, outerIndex)).subscribe(\n (innerSubscriber = createOperatorSubscriber(\n subscriber,\n // When we get a new inner value, next it through. Note that this is\n // handling the deprecate result selector here. This is because with this architecture\n // it ends up being smaller than using the map operator.\n (innerValue) => subscriber.next(resultSelector ? resultSelector(value, innerValue, outerIndex, innerIndex++) : innerValue),\n () => {\n // The inner has completed. Null out the inner subscriber to\n // free up memory and to signal that we have no inner subscription\n // currently.\n innerSubscriber = null!;\n checkComplete();\n }\n ))\n );\n },\n () => {\n isComplete = true;\n checkComplete();\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInput, ObservedValueOf } from '../types';\nimport { switchMap } from './switchMap';\nimport { identity } from '../util/identity';\n\n/**\n * Converts a higher-order Observable into a first-order Observable\n * producing values only from the most recent observable sequence\n *\n * <span class=\"informal\">Flattens an Observable-of-Observables.</span>\n *\n * ![](switchAll.png)\n *\n * `switchAll` subscribes to a source that is an observable of observables, also known as a\n * \"higher-order observable\" (or `Observable<Observable<T>>`). It subscribes to the most recently\n * provided \"inner observable\" emitted by the source, unsubscribing from any previously subscribed\n * to inner observable, such that only the most recent inner observable may be subscribed to at\n * any point in time. The resulting observable returned by `switchAll` will only complete if the\n * source observable completes, *and* any currently subscribed to inner observable also has completed,\n * if there are any.\n *\n * ## Examples\n *\n * Spawn a new interval observable for each click event, but for every new\n * click, cancel the previous interval and subscribe to the new one\n *\n * ```ts\n * import { fromEvent, tap, map, interval, switchAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click').pipe(tap(() => console.log('click')));\n * const source = clicks.pipe(map(() => interval(1000)));\n *\n * source\n * .pipe(switchAll())\n * .subscribe(x => console.log(x));\n *\n * // Output\n * // click\n * // 0\n * // 1\n * // 2\n * // 3\n * // ...\n * // click\n * // 0\n * // 1\n * // 2\n * // ...\n * // click\n * // ...\n * ```\n *\n * @see {@link combineLatestAll}\n * @see {@link concatAll}\n * @see {@link exhaustAll}\n * @see {@link switchMap}\n * @see {@link switchMapTo}\n * @see {@link mergeAll}\n *\n * @return A function that returns an Observable that converts a higher-order\n * Observable into a first-order Observable producing values only from the most\n * recent Observable sequence.\n */\nexport function switchAll<O extends ObservableInput<any>>(): OperatorFunction<O, ObservedValueOf<O>> {\n return switchMap(identity);\n}\n","import { switchMap } from './switchMap';\nimport { ObservableInput, OperatorFunction, ObservedValueOf } from '../types';\nimport { isFunction } from '../util/isFunction';\n\n/** @deprecated Will be removed in v9. Use {@link switchMap} instead: `switchMap(() => result)` */\nexport function switchMapTo<O extends ObservableInput<unknown>>(observable: O): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMapTo<O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: undefined\n): OperatorFunction<unknown, ObservedValueOf<O>>;\n/** @deprecated The `resultSelector` parameter will be removed in v8. Use an inner `map` instead. Details: https://rxjs.dev/deprecations/resultSelector */\nexport function switchMapTo<T, R, O extends ObservableInput<unknown>>(\n observable: O,\n resultSelector: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, R>;\n\n/**\n * Projects each source value to the same Observable which is flattened multiple\n * times with {@link switchMap} in the output Observable.\n *\n * <span class=\"informal\">It's like {@link switchMap}, but maps each value\n * always to the same inner Observable.</span>\n *\n * ![](switchMapTo.png)\n *\n * Maps each source value to the given Observable `innerObservable` regardless\n * of the source value, and then flattens those resulting Observables into one\n * single Observable, which is the output Observable. The output Observables\n * emits values only from the most recently emitted instance of\n * `innerObservable`.\n *\n * ## Example\n *\n * Restart an interval Observable on every click event\n *\n * ```ts\n * import { fromEvent, switchMapTo, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(switchMapTo(interval(1000)));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link concatMapTo}\n * @see {@link switchAll}\n * @see {@link switchMap}\n * @see {@link mergeMapTo}\n *\n * @param innerObservable An `ObservableInput` to replace each value from the\n * source Observable.\n * @return A function that returns an Observable that emits items from the\n * given `innerObservable` (and optionally transformed through the deprecated\n * `resultSelector`) every time a value is emitted on the source Observable,\n * and taking only the values from the most recently projected inner\n * Observable.\n * @deprecated Will be removed in v9. Use {@link switchMap} instead: `switchMap(() => result)`\n */\nexport function switchMapTo<T, R, O extends ObservableInput<unknown>>(\n innerObservable: O,\n resultSelector?: (outerValue: T, innerValue: ObservedValueOf<O>, outerIndex: number, innerIndex: number) => R\n): OperatorFunction<T, ObservedValueOf<O> | R> {\n return isFunction(resultSelector) ? switchMap(() => innerObservable, resultSelector) : switchMap(() => innerObservable);\n}\n","import { ObservableInput, ObservedValueOf, OperatorFunction } from '../types';\nimport { switchMap } from './switchMap';\nimport { operate } from '../util/lift';\n\n// TODO: Generate a marble diagram for these docs.\n\n/**\n * Applies an accumulator function over the source Observable where the\n * accumulator function itself returns an Observable, emitting values\n * only from the most recently returned Observable.\n *\n * <span class=\"informal\">It's like {@link mergeScan}, but only the most recent\n * Observable returned by the accumulator is merged into the outer Observable.</span>\n *\n * @see {@link scan}\n * @see {@link mergeScan}\n * @see {@link switchMap}\n *\n * @param accumulator\n * The accumulator function called on each source value.\n * @param seed The initial accumulation value.\n * @return A function that returns an observable of the accumulated values.\n */\nexport function switchScan<T, R, O extends ObservableInput<any>>(\n accumulator: (acc: R, value: T, index: number) => O,\n seed: R\n): OperatorFunction<T, ObservedValueOf<O>> {\n return operate((source, subscriber) => {\n // The state we will keep up to date to pass into our\n // accumulator function at each new value from the source.\n let state = seed;\n\n // Use `switchMap` on our `source` to do the work of creating\n // this operator. Note the backwards order here of `switchMap()(source)`\n // to avoid needing to use `pipe` unnecessarily\n switchMap(\n // On each value from the source, call the accumulator with\n // our previous state, the value and the index.\n (value: T, index) => accumulator(state, value, index),\n // Using the deprecated result selector here as a dirty trick\n // to update our state with the flattened value.\n (_, innerValue) => ((state = innerValue), innerValue)\n )(source).subscribe(subscriber);\n\n return () => {\n // Release state on finalization\n state = null!;\n };\n });\n}\n","import { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { noop } from '../util/noop';\n\n/**\n * Emits the values emitted by the source Observable until a `notifier`\n * Observable emits a value.\n *\n * <span class=\"informal\">Lets values pass until a second Observable,\n * `notifier`, emits a value. Then, it completes.</span>\n *\n * ![](takeUntil.png)\n *\n * `takeUntil` subscribes and begins mirroring the source Observable. It also\n * monitors a second Observable, `notifier` that you provide. If the `notifier`\n * emits a value, the output Observable stops mirroring the source Observable\n * and completes. If the `notifier` doesn't emit any value and completes\n * then `takeUntil` will pass all values.\n *\n * ## Example\n *\n * Tick every second until the first click happens\n *\n * ```ts\n * import { interval, fromEvent, takeUntil } from 'rxjs';\n *\n * const source = interval(1000);\n * const clicks = fromEvent(document, 'click');\n * const result = source.pipe(takeUntil(clicks));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeWhile}\n * @see {@link skip}\n *\n * @param notifier The `ObservableInput` whose first emitted value will cause the output\n * Observable of `takeUntil` to stop emitting values from the source Observable.\n * @return A function that returns an Observable that emits the values from the\n * source Observable until `notifier` emits its first value.\n */\nexport function takeUntil<T>(notifier: ObservableInput<any>): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n innerFrom(notifier).subscribe(createOperatorSubscriber(subscriber, () => subscriber.complete(), noop));\n !subscriber.closed && source.subscribe(subscriber);\n });\n}\n","import { OperatorFunction, MonoTypeOperatorFunction, TruthyTypesOf } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\nexport function takeWhile<T>(predicate: BooleanConstructor, inclusive: true): MonoTypeOperatorFunction<T>;\nexport function takeWhile<T>(predicate: BooleanConstructor, inclusive: false): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function takeWhile<T>(predicate: BooleanConstructor): OperatorFunction<T, TruthyTypesOf<T>>;\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S): OperatorFunction<T, S>;\nexport function takeWhile<T, S extends T>(predicate: (value: T, index: number) => value is S, inclusive: false): OperatorFunction<T, S>;\nexport function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive?: boolean): MonoTypeOperatorFunction<T>;\n\n/**\n * Emits values emitted by the source Observable so long as each value satisfies\n * the given `predicate`, and then completes as soon as this `predicate` is not\n * satisfied.\n *\n * <span class=\"informal\">Takes values from the source only while they pass the\n * condition given. When the first value does not satisfy, it completes.</span>\n *\n * ![](takeWhile.png)\n *\n * `takeWhile` subscribes and begins mirroring the source Observable. Each value\n * emitted on the source is given to the `predicate` function which returns a\n * boolean, representing a condition to be satisfied by the source values. The\n * output Observable emits the source values until such time as the `predicate`\n * returns false, at which point `takeWhile` stops mirroring the source\n * Observable and completes the output Observable.\n *\n * ## Example\n *\n * Emit click events only while the clientX property is greater than 200\n *\n * ```ts\n * import { fromEvent, takeWhile } from 'rxjs';\n *\n * const clicks = fromEvent<PointerEvent>(document, 'click');\n * const result = clicks.pipe(takeWhile(ev => ev.clientX > 200));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link take}\n * @see {@link takeLast}\n * @see {@link takeUntil}\n * @see {@link skip}\n *\n * @param predicate A function that evaluates a value emitted by the source\n * Observable and returns a boolean. Also takes the (zero-based) index as the\n * second argument.\n * @param inclusive When set to `true` the value that caused `predicate` to\n * return `false` will also be emitted.\n * @return A function that returns an Observable that emits values from the\n * source Observable so long as each value satisfies the condition defined by\n * the `predicate`, then completes.\n */\nexport function takeWhile<T>(predicate: (value: T, index: number) => boolean, inclusive = false): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n let index = 0;\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const result = predicate(value, index++);\n (result || inclusive) && subscriber.next(value);\n !result && subscriber.complete();\n })\n );\n });\n}\n","import { MonoTypeOperatorFunction, Observer } from '../types';\nimport { isFunction } from '../util/isFunction';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { identity } from '../util/identity';\n\n/**\n * An extension to the {@link Observer} interface used only by the {@link tap} operator.\n *\n * It provides a useful set of callbacks a user can register to do side-effects in\n * cases other than what the usual {@link Observer} callbacks are\n * ({@link guide/glossary-and-semantics#next next},\n * {@link guide/glossary-and-semantics#error error} and/or\n * {@link guide/glossary-and-semantics#complete complete}).\n *\n * ## Example\n *\n * ```ts\n * import { fromEvent, switchMap, tap, interval, take } from 'rxjs';\n *\n * const source$ = fromEvent(document, 'click');\n * const result$ = source$.pipe(\n * switchMap((_, i) => i % 2 === 0\n * ? fromEvent(document, 'mousemove').pipe(\n * tap({\n * subscribe: () => console.log('Subscribed to the mouse move events after click #' + i),\n * unsubscribe: () => console.log('Mouse move events #' + i + ' unsubscribed'),\n * finalize: () => console.log('Mouse move events #' + i + ' finalized')\n * })\n * )\n * : interval(1_000).pipe(\n * take(5),\n * tap({\n * subscribe: () => console.log('Subscribed to the 1-second interval events after click #' + i),\n * unsubscribe: () => console.log('1-second interval events #' + i + ' unsubscribed'),\n * finalize: () => console.log('1-second interval events #' + i + ' finalized')\n * })\n * )\n * )\n * );\n *\n * const subscription = result$.subscribe({\n * next: console.log\n * });\n *\n * setTimeout(() => {\n * console.log('Unsubscribe after 60 seconds');\n * subscription.unsubscribe();\n * }, 60_000);\n * ```\n */\nexport interface TapObserver<T> extends Observer<T> {\n /**\n * The callback that `tap` operator invokes at the moment when the source Observable\n * gets subscribed to.\n */\n subscribe: () => void;\n /**\n * The callback that `tap` operator invokes when an explicit\n * {@link guide/glossary-and-semantics#unsubscription unsubscribe} happens. It won't get invoked on\n * `error` or `complete` events.\n */\n unsubscribe: () => void;\n /**\n * The callback that `tap` operator invokes when any kind of\n * {@link guide/glossary-and-semantics#finalization finalization} happens - either when\n * the source Observable `error`s or `complete`s or when it gets explicitly unsubscribed\n * by the user. There is no difference in using this callback or the {@link finalize}\n * operator, but if you're already using `tap` operator, you can use this callback\n * instead. You'd get the same result in either case.\n */\n finalize: () => void;\n}\nexport function tap<T>(observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void)): MonoTypeOperatorFunction<T>;\n/** @deprecated Instead of passing separate callback arguments, use an observer argument. Signatures taking separate callback arguments will be removed in v8. Details: https://rxjs.dev/deprecations/subscribe-arguments */\nexport function tap<T>(\n next?: ((value: T) => void) | null,\n error?: ((error: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T>;\n\n/**\n * Used to perform side-effects for notifications from the source observable\n *\n * <span class=\"informal\">Used when you want to affect outside state with a notification without altering the notification</span>\n *\n * ![](tap.png)\n *\n * Tap is designed to allow the developer a designated place to perform side effects. While you _could_ perform side-effects\n * inside of a `map` or a `mergeMap`, that would make their mapping functions impure, which isn't always a big deal, but will\n * make it so you can't do things like memoize those functions. The `tap` operator is designed solely for such side-effects to\n * help you remove side-effects from other operations.\n *\n * For any notification, next, error, or complete, `tap` will call the appropriate callback you have provided to it, via a function\n * reference, or a partial observer, then pass that notification down the stream.\n *\n * The observable returned by `tap` is an exact mirror of the source, with one exception: Any error that occurs -- synchronously -- in a handler\n * provided to `tap` will be emitted as an error from the returned observable.\n *\n * > Be careful! You can mutate objects as they pass through the `tap` operator's handlers.\n *\n * The most common use of `tap` is actually for debugging. You can place a `tap(console.log)` anywhere\n * in your observable `pipe`, log out the notifications as they are emitted by the source returned by the previous\n * operation.\n *\n * ## Examples\n *\n * Check a random number before it is handled. Below is an observable that will use a random number between 0 and 1,\n * and emit `'big'` or `'small'` depending on the size of that number. But we wanted to log what the original number\n * was, so we have added a `tap(console.log)`.\n *\n * ```ts\n * import { of, tap, map } from 'rxjs';\n *\n * of(Math.random()).pipe(\n * tap(console.log),\n * map(n => n > 0.5 ? 'big' : 'small')\n * ).subscribe(console.log);\n * ```\n *\n * Using `tap` to analyze a value and force an error. Below is an observable where in our system we only\n * want to emit numbers 3 or less we get from another source. We can force our observable to error\n * using `tap`.\n *\n * ```ts\n * import { of, tap } from 'rxjs';\n *\n * const source = of(1, 2, 3, 4, 5);\n *\n * source.pipe(\n * tap(n => {\n * if (n > 3) {\n * throw new TypeError(`Value ${ n } is greater than 3`);\n * }\n * })\n * )\n * .subscribe({ next: console.log, error: err => console.log(err.message) });\n * ```\n *\n * We want to know when an observable completes before moving on to the next observable. The system\n * below will emit a random series of `'X'` characters from 3 different observables in sequence. The\n * only way we know when one observable completes and moves to the next one, in this case, is because\n * we have added a `tap` with the side effect of logging to console.\n *\n * ```ts\n * import { of, concatMap, interval, take, map, tap } from 'rxjs';\n *\n * of(1, 2, 3).pipe(\n * concatMap(n => interval(1000).pipe(\n * take(Math.round(Math.random() * 10)),\n * map(() => 'X'),\n * tap({ complete: () => console.log(`Done with ${ n }`) })\n * ))\n * )\n * .subscribe(console.log);\n * ```\n *\n * @see {@link finalize}\n * @see {@link TapObserver}\n *\n * @param observerOrNext A next handler or partial observer\n * @param error An error handler\n * @param complete A completion handler\n * @return A function that returns an Observable identical to the source, but\n * runs the specified Observer or callback(s) for each item.\n */\nexport function tap<T>(\n observerOrNext?: Partial<TapObserver<T>> | ((value: T) => void) | null,\n error?: ((e: any) => void) | null,\n complete?: (() => void) | null\n): MonoTypeOperatorFunction<T> {\n // We have to check to see not only if next is a function,\n // but if error or complete were passed. This is because someone\n // could technically call tap like `tap(null, fn)` or `tap(null, null, fn)`.\n const tapObserver =\n isFunction(observerOrNext) || error || complete\n ? // tslint:disable-next-line: no-object-literal-type-assertion\n ({ next: observerOrNext as Exclude<typeof observerOrNext, Partial<TapObserver<T>>>, error, complete } as Partial<TapObserver<T>>)\n : observerOrNext;\n\n return tapObserver\n ? operate((source, subscriber) => {\n tapObserver.subscribe?.();\n let isUnsub = true;\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n tapObserver.next?.(value);\n subscriber.next(value);\n },\n () => {\n isUnsub = false;\n tapObserver.complete?.();\n subscriber.complete();\n },\n (err) => {\n isUnsub = false;\n tapObserver.error?.(err);\n subscriber.error(err);\n },\n () => {\n if (isUnsub) {\n tapObserver.unsubscribe?.();\n }\n tapObserver.finalize?.();\n }\n )\n );\n })\n : // Tap was called with no valid tap observer or handler\n // (e.g. `tap(null, null, null)` or `tap(null)` or `tap()`)\n // so we're going to just mirror the source.\n identity;\n}\n","import { Subscription } from '../Subscription';\n\nimport { MonoTypeOperatorFunction, ObservableInput } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * An object interface used by {@link throttle} or {@link throttleTime} that ensure\n * configuration options of these operators.\n *\n * @see {@link throttle}\n * @see {@link throttleTime}\n */\nexport interface ThrottleConfig {\n /**\n * If `true`, the resulting Observable will emit the first value from the source\n * Observable at the **start** of the \"throttling\" process (when starting an\n * internal timer that prevents other emissions from the source to pass through).\n * If `false`, it will not emit the first value from the source Observable at the\n * start of the \"throttling\" process.\n *\n * If not provided, defaults to: `true`.\n */\n leading?: boolean;\n /**\n * If `true`, the resulting Observable will emit the last value from the source\n * Observable at the **end** of the \"throttling\" process (when ending an internal\n * timer that prevents other emissions from the source to pass through).\n * If `false`, it will not emit the last value from the source Observable at the\n * end of the \"throttling\" process.\n *\n * If not provided, defaults to: `false`.\n */\n trailing?: boolean;\n}\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for a duration determined by another Observable, then repeats this\n * process.\n *\n * <span class=\"informal\">It's like {@link throttleTime}, but the silencing\n * duration is determined by a second Observable.</span>\n *\n * ![](throttle.svg)\n *\n * `throttle` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled by calling the `durationSelector` function with the source value,\n * which returns the \"duration\" Observable. When the duration Observable emits a\n * value, the timer is disabled, and this process repeats for the\n * next source value.\n *\n * ## Example\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, throttle, interval } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttle(() => interval(1000)));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link audit}\n * @see {@link debounce}\n * @see {@link delayWhen}\n * @see {@link sample}\n * @see {@link throttleTime}\n *\n * @param durationSelector A function that receives a value from the source\n * Observable, for computing the silencing duration for each source value,\n * returned as an `ObservableInput`.\n * @param config A configuration object to define `leading` and `trailing`\n * behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return A function that returns an Observable that performs the throttle\n * operation to limit the rate of emissions from the source.\n */\nexport function throttle<T>(durationSelector: (value: T) => ObservableInput<any>, config?: ThrottleConfig): MonoTypeOperatorFunction<T> {\n return operate((source, subscriber) => {\n const { leading = true, trailing = false } = config ?? {};\n let hasValue = false;\n let sendValue: T | null = null;\n let throttled: Subscription | null = null;\n let isComplete = false;\n\n const endThrottling = () => {\n throttled?.unsubscribe();\n throttled = null;\n if (trailing) {\n send();\n isComplete && subscriber.complete();\n }\n };\n\n const cleanupThrottling = () => {\n throttled = null;\n isComplete && subscriber.complete();\n };\n\n const startThrottle = (value: T) =>\n (throttled = innerFrom(durationSelector(value)).subscribe(createOperatorSubscriber(subscriber, endThrottling, cleanupThrottling)));\n\n const send = () => {\n if (hasValue) {\n // Ensure we clear out our value and hasValue flag\n // before we emit, otherwise reentrant code can cause\n // issues here.\n hasValue = false;\n const value = sendValue!;\n sendValue = null;\n // Emit the value.\n subscriber.next(value);\n !isComplete && startThrottle(value);\n }\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n // Regarding the presence of throttled.closed in the following\n // conditions, if a synchronous duration selector is specified - weird,\n // but legal - an already-closed subscription will be assigned to\n // throttled, so the subscription's closed property needs to be checked,\n // too.\n (value) => {\n hasValue = true;\n sendValue = value;\n !(throttled && !throttled.closed) && (leading ? send() : startThrottle(value));\n },\n () => {\n isComplete = true;\n !(trailing && hasValue && throttled && !throttled.closed) && subscriber.complete();\n }\n )\n );\n });\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { throttle, ThrottleConfig } from './throttle';\nimport { MonoTypeOperatorFunction, SchedulerLike } from '../types';\nimport { timer } from '../observable/timer';\n\n/**\n * Emits a value from the source Observable, then ignores subsequent source\n * values for `duration` milliseconds, then repeats this process.\n *\n * <span class=\"informal\">Lets a value pass, then ignores source values for the\n * next `duration` milliseconds.</span>\n *\n * ![](throttleTime.png)\n *\n * `throttleTime` emits the source Observable values on the output Observable\n * when its internal timer is disabled, and ignores source values when the timer\n * is enabled. Initially, the timer is disabled. As soon as the first source\n * value arrives, it is forwarded to the output Observable, and then the timer\n * is enabled. After `duration` milliseconds (or the time unit determined\n * internally by the optional `scheduler`) has passed, the timer is disabled,\n * and this process repeats for the next source value. Optionally takes a\n * {@link SchedulerLike} for managing timers.\n *\n * ## Examples\n *\n * ### Limit click rate\n *\n * Emit clicks at a rate of at most one click per second\n *\n * ```ts\n * import { fromEvent, throttleTime } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(throttleTime(1000));\n *\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link auditTime}\n * @see {@link debounceTime}\n * @see {@link delay}\n * @see {@link sampleTime}\n * @see {@link throttle}\n *\n * @param duration Time to wait before emitting another value after\n * emitting the last value, measured in milliseconds or the time unit determined\n * internally by the optional `scheduler`.\n * @param scheduler The {@link SchedulerLike} to use for\n * managing the timers that handle the throttling. Defaults to {@link asyncScheduler}.\n * @param config A configuration object to define `leading` and\n * `trailing` behavior. Defaults to `{ leading: true, trailing: false }`.\n * @return A function that returns an Observable that performs the throttle\n * operation to limit the rate of emissions from the source.\n */\nexport function throttleTime<T>(\n duration: number,\n scheduler: SchedulerLike = asyncScheduler,\n config?: ThrottleConfig\n): MonoTypeOperatorFunction<T> {\n const duration$ = timer(duration, scheduler);\n return throttle(() => duration$, config);\n}\n","import { asyncScheduler } from '../scheduler/async';\nimport { SchedulerLike, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Emits an object containing the current value, and the time that has\n * passed between emitting the current value and the previous value, which is\n * calculated by using the provided `scheduler`'s `now()` method to retrieve\n * the current time at each emission, then calculating the difference. The `scheduler`\n * defaults to {@link asyncScheduler}, so by default, the `interval` will be in\n * milliseconds.\n *\n * <span class=\"informal\">Convert an Observable that emits items into one that\n * emits indications of the amount of time elapsed between those emissions.</span>\n *\n * ![](timeInterval.png)\n *\n * ## Example\n *\n * Emit interval between current value with the last value\n *\n * ```ts\n * import { interval, timeInterval } from 'rxjs';\n *\n * const seconds = interval(1000);\n *\n * seconds\n * .pipe(timeInterval())\n * .subscribe(value => console.log(value));\n *\n * // NOTE: The values will never be this precise,\n * // intervals created with `interval` or `setInterval`\n * // are non-deterministic.\n *\n * // { value: 0, interval: 1000 }\n * // { value: 1, interval: 1000 }\n * // { value: 2, interval: 1000 }\n * ```\n *\n * @param scheduler Scheduler used to get the current time.\n * @return A function that returns an Observable that emits information about\n * value and interval.\n */\nexport function timeInterval<T>(scheduler: SchedulerLike = asyncScheduler): OperatorFunction<T, TimeInterval<T>> {\n return operate((source, subscriber) => {\n let last = scheduler.now();\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n const now = scheduler.now();\n const interval = now - last;\n last = now;\n subscriber.next(new TimeInterval(value, interval));\n })\n );\n });\n}\n\n// TODO(benlesh): make this an interface, export the interface, but not the implemented class,\n// there's no reason users should be manually creating this type.\n\nexport class TimeInterval<T> {\n /**\n * @deprecated Internal implementation detail, do not construct directly. Will be made an interface in v8.\n */\n constructor(public value: T, public interval: number) {}\n}\n","import { async } from '../scheduler/async';\nimport { isValidDate } from '../util/isDate';\nimport { ObservableInput, OperatorFunction, SchedulerLike } from '../types';\nimport { timeout } from './timeout';\n\n/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(someDate, a$, scheduler)`, use the configuration object\n * `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8. */\nexport function timeoutWith<T, R>(dueBy: Date, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n/** @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use the configuration object\n * `timeout({ each: 100, with: () => a$, scheduler })`. Will be removed in v8. */\nexport function timeoutWith<T, R>(waitFor: number, switchTo: ObservableInput<R>, scheduler?: SchedulerLike): OperatorFunction<T, T | R>;\n\n/**\n * When the passed timespan elapses before the source emits any given value, it will unsubscribe from the source,\n * and switch the subscription to another observable.\n *\n * <span class=\"informal\">Used to switch to a different observable if your source is being slow.</span>\n *\n * Useful in cases where:\n *\n * - You want to switch to a different source that may be faster.\n * - You want to notify a user that the data stream is slow.\n * - You want to emit a custom error rather than the {@link TimeoutError} emitted\n * by the default usage of {@link timeout}.\n *\n * If the first parameter is passed as Date and the time of the Date arrives before the first value arrives from the source,\n * it will unsubscribe from the source and switch the subscription to another observable.\n *\n * <span class=\"informal\">Use Date object to switch to a different observable if the first value doesn't arrive by a specific time.</span>\n *\n * Can be used to set a timeout only for the first value, however it's recommended to use the {@link timeout} operator with\n * the `first` configuration to get the same effect.\n *\n * ## Examples\n *\n * Fallback to a faster observable\n *\n * ```ts\n * import { interval, timeoutWith } from 'rxjs';\n *\n * const slow$ = interval(1000);\n * const faster$ = interval(500);\n *\n * slow$\n * .pipe(timeoutWith(900, faster$))\n * .subscribe(console.log);\n * ```\n *\n * Emit your own custom timeout error\n *\n * ```ts\n * import { interval, timeoutWith, throwError } from 'rxjs';\n *\n * class CustomTimeoutError extends Error {\n * constructor() {\n * super('It was too slow');\n * this.name = 'CustomTimeoutError';\n * }\n * }\n *\n * const slow$ = interval(1000);\n *\n * slow$\n * .pipe(timeoutWith(900, throwError(() => new CustomTimeoutError())))\n * .subscribe({\n * error: err => console.error(err.message)\n * });\n * ```\n *\n * @see {@link timeout}\n *\n * @param due When passed a number, used as the time (in milliseconds) allowed between each value from the source before timeout\n * is triggered. When passed a Date, used as the exact time at which the timeout will be triggered if the first value does not arrive.\n * @param withObservable The observable to switch to when timeout occurs.\n * @param scheduler The scheduler to use with time-related operations within this operator. Defaults to {@link asyncScheduler}\n * @return A function that returns an Observable that mirrors behaviour of the\n * source Observable, unless timeout happens when it starts emitting values\n * from the `ObservableInput` passed as a second parameter.\n * @deprecated Replaced with {@link timeout}. Instead of `timeoutWith(100, a$, scheduler)`, use {@link timeout} with the configuration\n * object: `timeout({ each: 100, with: () => a$, scheduler })`. Instead of `timeoutWith(someDate, a$, scheduler)`, use {@link timeout}\n * with the configuration object: `timeout({ first: someDate, with: () => a$, scheduler })`. Will be removed in v8.\n */\nexport function timeoutWith<T, R>(\n due: number | Date,\n withObservable: ObservableInput<R>,\n scheduler?: SchedulerLike\n): OperatorFunction<T, T | R> {\n let first: number | Date | undefined;\n let each: number | undefined;\n let _with: () => ObservableInput<R>;\n scheduler = scheduler ?? async;\n\n if (isValidDate(due)) {\n first = due;\n } else if (typeof due === 'number') {\n each = due;\n }\n\n if (withObservable) {\n _with = () => withObservable;\n } else {\n throw new TypeError('No observable provided to switch to');\n }\n\n if (first == null && each == null) {\n // Ensure timeout was provided at runtime.\n throw new TypeError('No timeout provided.');\n }\n\n return timeout<T, ObservableInput<R>>({\n first,\n each,\n scheduler,\n with: _with,\n });\n}\n","import { OperatorFunction, TimestampProvider, Timestamp } from '../types';\nimport { dateTimestampProvider } from '../scheduler/dateTimestampProvider';\nimport { map } from './map';\n\n/**\n * Attaches a timestamp to each item emitted by an observable indicating when it was emitted\n *\n * The `timestamp` operator maps the *source* observable stream to an object of type\n * `{value: T, timestamp: R}`. The properties are generically typed. The `value` property contains the value\n * and type of the *source* observable. The `timestamp` is generated by the schedulers `now` function. By\n * default, it uses the `asyncScheduler` which simply returns `Date.now()` (milliseconds since 1970/01/01\n * 00:00:00:000) and therefore is of type `number`.\n *\n * ![](timestamp.png)\n *\n * ## Example\n *\n * In this example there is a timestamp attached to the document's click events\n *\n * ```ts\n * import { fromEvent, timestamp } from 'rxjs';\n *\n * const clickWithTimestamp = fromEvent(document, 'click').pipe(\n * timestamp()\n * );\n *\n * // Emits data of type { value: PointerEvent, timestamp: number }\n * clickWithTimestamp.subscribe(data => {\n * console.log(data);\n * });\n * ```\n *\n * @param timestampProvider An object with a `now()` method used to get the current timestamp.\n * @return A function that returns an Observable that attaches a timestamp to\n * each item emitted by the source Observable indicating when it was emitted.\n */\nexport function timestamp<T>(timestampProvider: TimestampProvider = dateTimestampProvider): OperatorFunction<T, Timestamp<T>> {\n return map((value: T) => ({ value, timestamp: timestampProvider.now() }));\n}\n","import { Observable } from '../Observable';\nimport { OperatorFunction, ObservableInput } from '../types';\nimport { Subject } from '../Subject';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Branch out the source Observable values as a nested Observable whenever\n * `windowBoundaries` emits.\n *\n * <span class=\"informal\">It's like {@link buffer}, but emits a nested Observable\n * instead of an array.</span>\n *\n * ![](window.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping\n * windows. It emits the current window and opens a new one whenever the\n * `windowBoundaries` emits an item. `windowBoundaries` can be any type that\n * `ObservableInput` accepts. It internally gets converted to an Observable.\n * Because each window is an Observable, the output is a higher-order Observable.\n *\n * ## Example\n *\n * In every window of 1 second each, emit at most 2 click events\n *\n * ```ts\n * import { fromEvent, interval, window, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const sec = interval(1000);\n * const result = clicks.pipe(\n * window(sec),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link buffer}\n *\n * @param windowBoundaries An `ObservableInput` that completes the\n * previous window and starts a new window.\n * @return A function that returns an Observable of windows, which are\n * Observables emitting values of the source Observable.\n */\nexport function window<T>(windowBoundaries: ObservableInput<any>): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n let windowSubject: Subject<T> = new Subject<T>();\n\n subscriber.next(windowSubject.asObservable());\n\n const errorHandler = (err: any) => {\n windowSubject.error(err);\n subscriber.error(err);\n };\n\n // Subscribe to our source\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => windowSubject?.next(value),\n () => {\n windowSubject.complete();\n subscriber.complete();\n },\n errorHandler\n )\n );\n\n // Subscribe to the window boundaries.\n innerFrom(windowBoundaries).subscribe(\n createOperatorSubscriber(\n subscriber,\n () => {\n windowSubject.complete();\n subscriber.next((windowSubject = new Subject()));\n },\n noop,\n errorHandler\n )\n );\n\n return () => {\n // Unsubscribing the subject ensures that anyone who has captured\n // a reference to this window that tries to use it after it can\n // no longer get values from the source will get an ObjectUnsubscribedError.\n windowSubject?.unsubscribe();\n windowSubject = null!;\n };\n });\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\n\n/**\n * Branch out the source Observable values as a nested Observable with each\n * nested Observable emitting at most `windowSize` values.\n *\n * <span class=\"informal\">It's like {@link bufferCount}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowCount.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows every `startWindowEvery`\n * items, each containing no more than `windowSize` items. When the source\n * Observable completes or encounters an error, the output Observable emits\n * the current window and propagates the notification from the source\n * Observable. If `startWindowEvery` is not provided, then new windows are\n * started immediately at the start of the source and when each window completes\n * with size `windowSize`.\n *\n * ## Examples\n *\n * Ignore every 3rd click event, starting from the first one\n *\n * ```ts\n * import { fromEvent, windowCount, map, skip, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(3),\n * map(win => win.pipe(skip(1))), // skip first of every 3 clicks\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Ignore every 3rd click event, starting from the third one\n *\n * ```ts\n * import { fromEvent, windowCount, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowCount(2, 3),\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferCount}\n *\n * @param windowSize The maximum number of values emitted by each window.\n * @param startWindowEvery Interval at which to start a new window. For example\n * if `startWindowEvery` is `2`, then a new window will be started on every\n * other value from the source. A new window is started at the beginning of the\n * source by default.\n * @return A function that returns an Observable of windows, which in turn are\n * Observable of values.\n */\nexport function windowCount<T>(windowSize: number, startWindowEvery: number = 0): OperatorFunction<T, Observable<T>> {\n const startEvery = startWindowEvery > 0 ? startWindowEvery : windowSize;\n\n return operate((source, subscriber) => {\n let windows = [new Subject<T>()];\n let starts: number[] = [];\n let count = 0;\n\n // Open the first window.\n subscriber.next(windows[0].asObservable());\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Emit the value through all current windows.\n // We don't need to create a new window yet, we\n // do that as soon as we close one.\n for (const window of windows) {\n window.next(value);\n }\n // Here we're using the size of the window array to figure\n // out if the oldest window has emitted enough values. We can do this\n // because the size of the window array is a function of the values\n // seen by the subscription. If it's time to close it, we complete\n // it and remove it.\n const c = count - windowSize + 1;\n if (c >= 0 && c % startEvery === 0) {\n windows.shift()!.complete();\n }\n\n // Look to see if the next count tells us it's time to open a new window.\n // TODO: We need to figure out if this really makes sense. We're technically\n // emitting windows *before* we have a value to emit them for. It's probably\n // more expected that we should be emitting the window when the start\n // count is reached -- not before.\n if (++count % startEvery === 0) {\n const window = new Subject<T>();\n windows.push(window);\n subscriber.next(window.asObservable());\n }\n },\n () => {\n while (windows.length > 0) {\n windows.shift()!.complete();\n }\n subscriber.complete();\n },\n (err) => {\n while (windows.length > 0) {\n windows.shift()!.error(err);\n }\n subscriber.error(err);\n },\n () => {\n starts = null!;\n windows = null!;\n }\n )\n );\n });\n}\n","import { Subject } from '../Subject';\nimport { asyncScheduler } from '../scheduler/async';\nimport { Observable } from '../Observable';\nimport { Subscription } from '../Subscription';\nimport { Observer, OperatorFunction, SchedulerLike } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { arrRemove } from '../util/arrRemove';\nimport { popScheduler } from '../util/args';\nimport { executeSchedule } from '../util/executeSchedule';\n\nexport function windowTime<T>(windowTimeSpan: number, scheduler?: SchedulerLike): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(\n windowTimeSpan: number,\n windowCreationInterval: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, Observable<T>>;\nexport function windowTime<T>(\n windowTimeSpan: number,\n windowCreationInterval: number | null | void,\n maxWindowSize: number,\n scheduler?: SchedulerLike\n): OperatorFunction<T, Observable<T>>;\n\n/**\n * Branch out the source Observable values as a nested Observable periodically\n * in time.\n *\n * <span class=\"informal\">It's like {@link bufferTime}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowTime.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable starts a new window periodically, as\n * determined by the `windowCreationInterval` argument. It emits each window\n * after a fixed timespan, specified by the `windowTimeSpan` argument. When the\n * source Observable completes or encounters an error, the output Observable\n * emits the current window and propagates the notification from the source\n * Observable. If `windowCreationInterval` is not provided, the output\n * Observable starts a new window when the previous window of duration\n * `windowTimeSpan` completes. If `maxWindowCount` is provided, each window\n * will emit at most fixed number of values. Window will complete immediately\n * after emitting last value and next one still will open as specified by\n * `windowTimeSpan` and `windowCreationInterval` arguments.\n *\n * ## Examples\n *\n * In every window of 1 second each, emit at most 2 click events\n *\n * ```ts\n * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Every 5 seconds start a window 1 second long, and emit at most 2 click events per window\n *\n * ```ts\n * import { fromEvent, windowTime, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * Same as example above but with `maxWindowCount` instead of `take`\n *\n * ```ts\n * import { fromEvent, windowTime, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowTime(1000, 5000, 2), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowToggle}\n * @see {@link windowWhen}\n * @see {@link bufferTime}\n *\n * @param windowTimeSpan The amount of time, in milliseconds, to fill each window.\n * @param windowCreationInterval The interval at which to start new\n * windows.\n * @param maxWindowSize Max number of\n * values each window can emit before completion.\n * @param scheduler The scheduler on which to schedule the\n * intervals that determine window boundaries.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowTime<T>(windowTimeSpan: number, ...otherArgs: any[]): OperatorFunction<T, Observable<T>> {\n const scheduler = popScheduler(otherArgs) ?? asyncScheduler;\n const windowCreationInterval = (otherArgs[0] as number) ?? null;\n const maxWindowSize = (otherArgs[1] as number) || Infinity;\n\n return operate((source, subscriber) => {\n // The active windows, their related subscriptions, and removal functions.\n let windowRecords: WindowRecord<T>[] | null = [];\n // If true, it means that every time we close a window, we want to start a new window.\n // This is only really used for when *just* the time span is passed.\n let restartOnClose = false;\n\n const closeWindow = (record: { window: Subject<T>; subs: Subscription }) => {\n const { window, subs } = record;\n window.complete();\n subs.unsubscribe();\n arrRemove(windowRecords, record);\n restartOnClose && startWindow();\n };\n\n /**\n * Called every time we start a new window. This also does\n * the work of scheduling the job to close the window.\n */\n const startWindow = () => {\n if (windowRecords) {\n const subs = new Subscription();\n subscriber.add(subs);\n const window = new Subject<T>();\n const record = {\n window,\n subs,\n seen: 0,\n };\n windowRecords.push(record);\n subscriber.next(window.asObservable());\n executeSchedule(subs, scheduler, () => closeWindow(record), windowTimeSpan);\n }\n };\n\n if (windowCreationInterval !== null && windowCreationInterval >= 0) {\n // The user passed both a windowTimeSpan (required), and a creation interval\n // That means we need to start new window on the interval, and those windows need\n // to wait the required time span before completing.\n executeSchedule(subscriber, scheduler, startWindow, windowCreationInterval, true);\n } else {\n restartOnClose = true;\n }\n\n startWindow();\n\n /**\n * We need to loop over a copy of the window records several times in this operator.\n * This is to save bytes over the wire more than anything.\n * The reason we copy the array is that reentrant code could mutate the array while\n * we are iterating over it.\n */\n const loop = (cb: (record: WindowRecord<T>) => void) => windowRecords!.slice().forEach(cb);\n\n /**\n * Used to notify all of the windows and the subscriber in the same way\n * in the error and complete handlers.\n */\n const terminate = (cb: (consumer: Observer<any>) => void) => {\n loop(({ window }) => cb(window));\n cb(subscriber);\n subscriber.unsubscribe();\n };\n\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Notify all windows of the value.\n loop((record) => {\n record.window.next(value);\n // If the window is over the max size, we need to close it.\n maxWindowSize <= ++record.seen && closeWindow(record);\n });\n },\n // Complete the windows and the downstream subscriber and clean up.\n () => terminate((consumer) => consumer.complete()),\n // Notify the windows and the downstream subscriber of the error and clean up.\n (err) => terminate((consumer) => consumer.error(err))\n )\n );\n\n // Additional finalization. This will be called when the\n // destination tears down. Other finalizations are registered implicitly\n // above via subscription.\n return () => {\n // Ensure that the buffer is released.\n windowRecords = null!;\n };\n });\n}\n\ninterface WindowRecord<T> {\n seen: number;\n window: Subject<T>;\n subs: Subscription;\n}\n","import { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { Subscription } from '../Subscription';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { innerFrom } from '../observable/innerFrom';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { noop } from '../util/noop';\nimport { arrRemove } from '../util/arrRemove';\n\n/**\n * Branch out the source Observable values as a nested Observable starting from\n * an emission from `openings` and ending when the output of `closingSelector`\n * emits.\n *\n * <span class=\"informal\">It's like {@link bufferToggle}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowToggle.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits windows that contain those items\n * emitted by the source Observable between the time when the `openings`\n * Observable emits an item and when the Observable returned by\n * `closingSelector` emits an item.\n *\n * ## Example\n *\n * Every other second, emit the click events from the next 500ms\n *\n * ```ts\n * import { fromEvent, interval, windowToggle, EMPTY, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const openings = interval(1000);\n * const result = clicks.pipe(\n * windowToggle(openings, i => i % 2 ? interval(500) : EMPTY),\n * mergeAll()\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowWhen}\n * @see {@link bufferToggle}\n *\n * @param openings An observable of notifications to start new windows.\n * @param closingSelector A function that takes the value emitted by the\n * `openings` observable and returns an Observable, which, when it emits a next\n * notification, signals that the associated window should complete.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowToggle<T, O>(\n openings: ObservableInput<O>,\n closingSelector: (openValue: O) => ObservableInput<any>\n): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n const windows: Subject<T>[] = [];\n\n const handleError = (err: any) => {\n while (0 < windows.length) {\n windows.shift()!.error(err);\n }\n subscriber.error(err);\n };\n\n innerFrom(openings).subscribe(\n createOperatorSubscriber(\n subscriber,\n (openValue) => {\n const window = new Subject<T>();\n windows.push(window);\n const closingSubscription = new Subscription();\n const closeWindow = () => {\n arrRemove(windows, window);\n window.complete();\n closingSubscription.unsubscribe();\n };\n\n let closingNotifier: Observable<any>;\n try {\n closingNotifier = innerFrom(closingSelector(openValue));\n } catch (err) {\n handleError(err);\n return;\n }\n\n subscriber.next(window.asObservable());\n\n closingSubscription.add(closingNotifier.subscribe(createOperatorSubscriber(subscriber, closeWindow, noop, handleError)));\n },\n noop\n )\n );\n\n // Subscribe to the source to get things started.\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value: T) => {\n // Copy the windows array before we emit to\n // make sure we don't have issues with reentrant code.\n const windowsCopy = windows.slice();\n for (const window of windowsCopy) {\n window.next(value);\n }\n },\n () => {\n // Complete all of our windows before we complete.\n while (0 < windows.length) {\n windows.shift()!.complete();\n }\n subscriber.complete();\n },\n handleError,\n () => {\n // Add this finalization so that all window subjects are\n // disposed of. This way, if a user tries to subscribe\n // to a window *after* the outer subscription has been unsubscribed,\n // they will get an error, instead of waiting forever to\n // see if a value arrives.\n while (0 < windows.length) {\n windows.shift()!.unsubscribe();\n }\n }\n )\n );\n });\n}\n","import { Subscriber } from '../Subscriber';\nimport { Observable } from '../Observable';\nimport { Subject } from '../Subject';\nimport { ObservableInput, OperatorFunction } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\n\n/**\n * Branch out the source Observable values as a nested Observable using a\n * factory function of closing Observables to determine when to start a new\n * window.\n *\n * <span class=\"informal\">It's like {@link bufferWhen}, but emits a nested\n * Observable instead of an array.</span>\n *\n * ![](windowWhen.png)\n *\n * Returns an Observable that emits windows of items it collects from the source\n * Observable. The output Observable emits connected, non-overlapping windows.\n * It emits the current window and opens a new one whenever the Observable\n * produced by the specified `closingSelector` function emits an item. The first\n * window is opened immediately when subscribing to the output Observable.\n *\n * ## Example\n *\n * Emit only the first two clicks events in every window of [1-5] random seconds\n *\n * ```ts\n * import { fromEvent, windowWhen, interval, map, take, mergeAll } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const result = clicks.pipe(\n * windowWhen(() => interval(1000 + Math.random() * 4000)),\n * map(win => win.pipe(take(2))), // take at most 2 emissions from each window\n * mergeAll() // flatten the Observable-of-Observables\n * );\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link window}\n * @see {@link windowCount}\n * @see {@link windowTime}\n * @see {@link windowToggle}\n * @see {@link bufferWhen}\n *\n * @param closingSelector A function that takes no arguments and returns an\n * {@link ObservableInput} (that gets converted to Observable) that signals\n * (on either `next` or `complete`) when to close the previous window and\n * start a new one.\n * @return A function that returns an Observable of windows, which in turn are\n * Observables.\n */\nexport function windowWhen<T>(closingSelector: () => ObservableInput<any>): OperatorFunction<T, Observable<T>> {\n return operate((source, subscriber) => {\n let window: Subject<T> | null;\n let closingSubscriber: Subscriber<any> | undefined;\n\n /**\n * When we get an error, we have to notify both the\n * destination subscriber and the window.\n */\n const handleError = (err: any) => {\n window!.error(err);\n subscriber.error(err);\n };\n\n /**\n * Called every time we need to open a window.\n * Recursive, as it will start the closing notifier, which\n * inevitably *should* call openWindow -- but may not if\n * it is a \"never\" observable.\n */\n const openWindow = () => {\n // We need to clean up our closing subscription,\n // we only cared about the first next or complete notification.\n closingSubscriber?.unsubscribe();\n\n // Close our window before starting a new one.\n window?.complete();\n\n // Start the new window.\n window = new Subject<T>();\n subscriber.next(window.asObservable());\n\n // Get our closing notifier.\n let closingNotifier: Observable<any>;\n try {\n closingNotifier = innerFrom(closingSelector());\n } catch (err) {\n handleError(err);\n return;\n }\n\n // Subscribe to the closing notifier, be sure\n // to capture the subscriber (aka Subscription)\n // so we can clean it up when we close the window\n // and open a new one.\n closingNotifier.subscribe((closingSubscriber = createOperatorSubscriber(subscriber, openWindow, openWindow, handleError)));\n };\n\n // Start the first window.\n openWindow();\n\n // Subscribe to the source\n source.subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => window!.next(value),\n () => {\n // The source completed, close the window and complete.\n window!.complete();\n subscriber.complete();\n },\n handleError,\n () => {\n // Be sure to clean up our closing subscription\n // when this tears down.\n closingSubscriber?.unsubscribe();\n window = null!;\n }\n )\n );\n });\n}\n","import { OperatorFunction, ObservableInputTuple } from '../types';\nimport { operate } from '../util/lift';\nimport { createOperatorSubscriber } from './OperatorSubscriber';\nimport { innerFrom } from '../observable/innerFrom';\nimport { identity } from '../util/identity';\nimport { noop } from '../util/noop';\nimport { popResultSelector } from '../util/args';\n\nexport function withLatestFrom<T, O extends unknown[]>(...inputs: [...ObservableInputTuple<O>]): OperatorFunction<T, [T, ...O]>;\n\nexport function withLatestFrom<T, O extends unknown[], R>(\n ...inputs: [...ObservableInputTuple<O>, (...value: [T, ...O]) => R]\n): OperatorFunction<T, R>;\n\n/**\n * Combines the source Observable with other Observables to create an Observable\n * whose values are calculated from the latest values of each, only when the\n * source emits.\n *\n * <span class=\"informal\">Whenever the source Observable emits a value, it\n * computes a formula using that value plus the latest values from other input\n * Observables, then emits the output of that formula.</span>\n *\n * ![](withLatestFrom.png)\n *\n * `withLatestFrom` combines each value from the source Observable (the\n * instance) with the latest values from the other input Observables only when\n * the source emits a value, optionally using a `project` function to determine\n * the value to be emitted on the output Observable. All input Observables must\n * emit at least one value before the output Observable will emit a value.\n *\n * ## Example\n *\n * On every click event, emit an array with the latest timer event plus the click event\n *\n * ```ts\n * import { fromEvent, interval, withLatestFrom } from 'rxjs';\n *\n * const clicks = fromEvent(document, 'click');\n * const timer = interval(1000);\n * const result = clicks.pipe(withLatestFrom(timer));\n * result.subscribe(x => console.log(x));\n * ```\n *\n * @see {@link combineLatest}\n *\n * @param inputs An input Observable to combine with the source Observable. More\n * than one input Observables may be given as argument. If the last parameter is\n * a function, it will be used as a projection function for combining values\n * together. When the function is called, it receives all values in order of the\n * Observables passed, where the first parameter is a value from the source\n * Observable. (e.g.\n * `a.pipe(withLatestFrom(b, c), map(([a1, b1, c1]) => a1 + b1 + c1))`). If this\n * is not passed, arrays will be emitted on the output Observable.\n * @return A function that returns an Observable of projected values from the\n * most recent values from each input Observable, or an array of the most\n * recent values from each input Observable.\n */\nexport function withLatestFrom<T, R>(...inputs: any[]): OperatorFunction<T, R | any[]> {\n const project = popResultSelector(inputs) as ((...args: any[]) => R) | undefined;\n\n return operate((source, subscriber) => {\n const len = inputs.length;\n const otherValues = new Array(len);\n // An array of whether or not the other sources have emitted. Matched with them by index.\n // TODO: At somepoint, we should investigate the performance implications here, and look\n // into using a `Set()` and checking the `size` to see if we're ready.\n let hasValue = inputs.map(() => false);\n // Flipped true when we have at least one value from all other sources and\n // we are ready to start emitting values.\n let ready = false;\n\n // Other sources. Note that here we are not checking `subscriber.closed`,\n // this causes all inputs to be subscribed to, even if nothing can be emitted\n // from them. This is an important distinction because subscription constitutes\n // a side-effect.\n for (let i = 0; i < len; i++) {\n innerFrom(inputs[i]).subscribe(\n createOperatorSubscriber(\n subscriber,\n (value) => {\n otherValues[i] = value;\n if (!ready && !hasValue[i]) {\n // If we're not ready yet, flag to show this observable has emitted.\n hasValue[i] = true;\n // Intentionally terse code.\n // If all of our other observables have emitted, set `ready` to `true`,\n // so we know we can start emitting values, then clean up the `hasValue` array,\n // because we don't need it anymore.\n (ready = hasValue.every(identity)) && (hasValue = null!);\n }\n },\n // Completing one of the other sources has\n // no bearing on the completion of our result.\n noop\n )\n );\n }\n\n // Source subscription\n source.subscribe(\n createOperatorSubscriber(subscriber, (value) => {\n if (ready) {\n // We have at least one value from the other sources. Go ahead and emit.\n const values = [value, ...otherValues];\n subscriber.next(project ? project(...values) : values);\n }\n })\n );\n });\n}\n","import { OperatorFunction, ObservableInput } from '../types';\nimport { zip } from '../observable/zip';\nimport { joinAllInternals } from './joinAllInternals';\n\n/**\n * Collects all observable inner sources from the source, once the source completes,\n * it will subscribe to all inner sources, combining their values by index and emitting\n * them.\n *\n * @see {@link zipWith}\n * @see {@link zip}\n */\nexport function zipAll<T>(): OperatorFunction<ObservableInput<T>, T[]>;\nexport function zipAll<T>(): OperatorFunction<any, T[]>;\nexport function zipAll<T, R>(project: (...values: T[]) => R): OperatorFunction<ObservableInput<T>, R>;\nexport function zipAll<R>(project: (...values: Array<any>) => R): OperatorFunction<any, R>;\n\nexport function zipAll<T, R>(project?: (...values: T[]) => R) {\n return joinAllInternals(zip, project);\n}\n","import { zip as zipStatic } from '../observable/zip';\nimport { ObservableInput, ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { operate } from '../util/lift';\n\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[]>(otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[], R>(\n otherInputsAndProject: [...ObservableInputTuple<A>],\n project: (...values: Cons<T, A>) => R\n): OperatorFunction<T, R>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[]>(...otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>>;\n/** @deprecated Replaced with {@link zipWith}. Will be removed in v8. */\nexport function zip<T, A extends readonly unknown[], R>(\n ...otherInputsAndProject: [...ObservableInputTuple<A>, (...values: Cons<T, A>) => R]\n): OperatorFunction<T, R>;\n\n/**\n * @deprecated Replaced with {@link zipWith}. Will be removed in v8.\n */\nexport function zip<T, R>(...sources: Array<ObservableInput<any> | ((...values: Array<any>) => R)>): OperatorFunction<T, any> {\n return operate((source, subscriber) => {\n zipStatic(source as ObservableInput<any>, ...(sources as Array<ObservableInput<any>>)).subscribe(subscriber);\n });\n}\n","import { ObservableInputTuple, OperatorFunction, Cons } from '../types';\nimport { zip } from './zip';\n\n/**\n * Subscribes to the source, and the observable inputs provided as arguments, and combines their values, by index, into arrays.\n *\n * What is meant by \"combine by index\": The first value from each will be made into a single array, then emitted,\n * then the second value from each will be combined into a single array and emitted, then the third value\n * from each will be combined into a single array and emitted, and so on.\n *\n * This will continue until it is no longer able to combine values of the same index into an array.\n *\n * After the last value from any one completed source is emitted in an array, the resulting observable will complete,\n * as there is no way to continue \"zipping\" values together by index.\n *\n * Use-cases for this operator are limited. There are memory concerns if one of the streams is emitting\n * values at a much faster rate than the others. Usage should likely be limited to streams that emit\n * at a similar pace, or finite streams of known length.\n *\n * In many cases, authors want `combineLatestWith` and not `zipWith`.\n *\n * @param otherInputs other observable inputs to collate values from.\n * @return A function that returns an Observable that emits items by index\n * combined from the source Observable and provided Observables, in form of an\n * array.\n */\nexport function zipWith<T, A extends readonly unknown[]>(...otherInputs: [...ObservableInputTuple<A>]): OperatorFunction<T, Cons<T, A>> {\n return zip(...otherInputs);\n}\n","//////////////////////////////////////////////////////////\n// Here we need to reference our other deep imports\n// so VS code will figure out where they are\n// see conversation here:\n// https://github.com/microsoft/TypeScript/issues/43034\n//////////////////////////////////////////////////////////\n\n// tslint:disable: no-reference\n// It's tempting to add references to all of the deep-import locations, but\n// adding references to those that require DOM types breaks Node projects.\n/// <reference path=\"./operators/index.ts\" />\n/// <reference path=\"./testing/index.ts\" />\n// tslint:enable: no-reference\n\n/* Observable */\nexport { Observable } from './internal/Observable';\nexport { ConnectableObservable } from './internal/observable/ConnectableObservable';\nexport { GroupedObservable } from './internal/operators/groupBy';\nexport { Operator } from './internal/Operator';\nexport { observable } from './internal/symbol/observable';\nexport { animationFrames } from './internal/observable/dom/animationFrames';\n\n/* Subjects */\nexport { Subject } from './internal/Subject';\nexport { BehaviorSubject } from './internal/BehaviorSubject';\nexport { ReplaySubject } from './internal/ReplaySubject';\nexport { AsyncSubject } from './internal/AsyncSubject';\n\n/* Schedulers */\nexport { asap, asapScheduler } from './internal/scheduler/asap';\nexport { async, asyncScheduler } from './internal/scheduler/async';\nexport { queue, queueScheduler } from './internal/scheduler/queue';\nexport { animationFrame, animationFrameScheduler } from './internal/scheduler/animationFrame';\nexport { VirtualTimeScheduler, VirtualAction } from './internal/scheduler/VirtualTimeScheduler';\nexport { Scheduler } from './internal/Scheduler';\n\n/* Subscription */\nexport { Subscription } from './internal/Subscription';\nexport { Subscriber } from './internal/Subscriber';\n\n/* Notification */\nexport { Notification, NotificationKind } from './internal/Notification';\n\n/* Utils */\nexport { pipe } from './internal/util/pipe';\nexport { noop } from './internal/util/noop';\nexport { identity } from './internal/util/identity';\nexport { isObservable } from './internal/util/isObservable';\n\n/* Promise Conversion */\nexport { lastValueFrom } from './internal/lastValueFrom';\nexport { firstValueFrom } from './internal/firstValueFrom';\n\n/* Error types */\nexport { ArgumentOutOfRangeError } from './internal/util/ArgumentOutOfRangeError';\nexport { EmptyError } from './internal/util/EmptyError';\nexport { NotFoundError } from './internal/util/NotFoundError';\nexport { ObjectUnsubscribedError } from './internal/util/ObjectUnsubscribedError';\nexport { SequenceError } from './internal/util/SequenceError';\nexport { TimeoutError } from './internal/operators/timeout';\nexport { UnsubscriptionError } from './internal/util/UnsubscriptionError';\n\n/* Static observable creation exports */\nexport { bindCallback } from './internal/observable/bindCallback';\nexport { bindNodeCallback } from './internal/observable/bindNodeCallback';\nexport { combineLatest } from './internal/observable/combineLatest';\nexport { concat } from './internal/observable/concat';\nexport { connectable } from './internal/observable/connectable';\nexport { defer } from './internal/observable/defer';\nexport { empty } from './internal/observable/empty';\nexport { forkJoin } from './internal/observable/forkJoin';\nexport { from } from './internal/observable/from';\nexport { fromEvent } from './internal/observable/fromEvent';\nexport { fromEventPattern } from './internal/observable/fromEventPattern';\nexport { generate } from './internal/observable/generate';\nexport { iif } from './internal/observable/iif';\nexport { interval } from './internal/observable/interval';\nexport { merge } from './internal/observable/merge';\nexport { never } from './internal/observable/never';\nexport { of } from './internal/observable/of';\nexport { onErrorResumeNext } from './internal/observable/onErrorResumeNext';\nexport { pairs } from './internal/observable/pairs';\nexport { partition } from './internal/observable/partition';\nexport { race } from './internal/observable/race';\nexport { range } from './internal/observable/range';\nexport { throwError } from './internal/observable/throwError';\nexport { timer } from './internal/observable/timer';\nexport { using } from './internal/observable/using';\nexport { zip } from './internal/observable/zip';\nexport { scheduled } from './internal/scheduled/scheduled';\n\n/* Constants */\nexport { EMPTY } from './internal/observable/empty';\nexport { NEVER } from './internal/observable/never';\n\n/* Types */\nexport * from './internal/types';\n\n/* Config */\nexport { config, GlobalConfig } from './internal/config';\n\n/* Operators */\nexport { audit } from './internal/operators/audit';\nexport { auditTime } from './internal/operators/auditTime';\nexport { buffer } from './internal/operators/buffer';\nexport { bufferCount } from './internal/operators/bufferCount';\nexport { bufferTime } from './internal/operators/bufferTime';\nexport { bufferToggle } from './internal/operators/bufferToggle';\nexport { bufferWhen } from './internal/operators/bufferWhen';\nexport { catchError } from './internal/operators/catchError';\nexport { combineAll } from './internal/operators/combineAll';\nexport { combineLatestAll } from './internal/operators/combineLatestAll';\nexport { combineLatestWith } from './internal/operators/combineLatestWith';\nexport { concatAll } from './internal/operators/concatAll';\nexport { concatMap } from './internal/operators/concatMap';\nexport { concatMapTo } from './internal/operators/concatMapTo';\nexport { concatWith } from './internal/operators/concatWith';\nexport { connect, ConnectConfig } from './internal/operators/connect';\nexport { count } from './internal/operators/count';\nexport { debounce } from './internal/operators/debounce';\nexport { debounceTime } from './internal/operators/debounceTime';\nexport { defaultIfEmpty } from './internal/operators/defaultIfEmpty';\nexport { delay } from './internal/operators/delay';\nexport { delayWhen } from './internal/operators/delayWhen';\nexport { dematerialize } from './internal/operators/dematerialize';\nexport { distinct } from './internal/operators/distinct';\nexport { distinctUntilChanged } from './internal/operators/distinctUntilChanged';\nexport { distinctUntilKeyChanged } from './internal/operators/distinctUntilKeyChanged';\nexport { elementAt } from './internal/operators/elementAt';\nexport { endWith } from './internal/operators/endWith';\nexport { every } from './internal/operators/every';\nexport { exhaust } from './internal/operators/exhaust';\nexport { exhaustAll } from './internal/operators/exhaustAll';\nexport { exhaustMap } from './internal/operators/exhaustMap';\nexport { expand } from './internal/operators/expand';\nexport { filter } from './internal/operators/filter';\nexport { finalize } from './internal/operators/finalize';\nexport { find } from './internal/operators/find';\nexport { findIndex } from './internal/operators/findIndex';\nexport { first } from './internal/operators/first';\nexport { groupBy, BasicGroupByOptions, GroupByOptionsWithElement } from './internal/operators/groupBy';\nexport { ignoreElements } from './internal/operators/ignoreElements';\nexport { isEmpty } from './internal/operators/isEmpty';\nexport { last } from './internal/operators/last';\nexport { map } from './internal/operators/map';\nexport { mapTo } from './internal/operators/mapTo';\nexport { materialize } from './internal/operators/materialize';\nexport { max } from './internal/operators/max';\nexport { mergeAll } from './internal/operators/mergeAll';\nexport { flatMap } from './internal/operators/flatMap';\nexport { mergeMap } from './internal/operators/mergeMap';\nexport { mergeMapTo } from './internal/operators/mergeMapTo';\nexport { mergeScan } from './internal/operators/mergeScan';\nexport { mergeWith } from './internal/operators/mergeWith';\nexport { min } from './internal/operators/min';\nexport { multicast } from './internal/operators/multicast';\nexport { observeOn } from './internal/operators/observeOn';\nexport { onErrorResumeNextWith } from './internal/operators/onErrorResumeNextWith';\nexport { pairwise } from './internal/operators/pairwise';\nexport { pluck } from './internal/operators/pluck';\nexport { publish } from './internal/operators/publish';\nexport { publishBehavior } from './internal/operators/publishBehavior';\nexport { publishLast } from './internal/operators/publishLast';\nexport { publishReplay } from './internal/operators/publishReplay';\nexport { raceWith } from './internal/operators/raceWith';\nexport { reduce } from './internal/operators/reduce';\nexport { repeat, RepeatConfig } from './internal/operators/repeat';\nexport { repeatWhen } from './internal/operators/repeatWhen';\nexport { retry, RetryConfig } from './internal/operators/retry';\nexport { retryWhen } from './internal/operators/retryWhen';\nexport { refCount } from './internal/operators/refCount';\nexport { sample } from './internal/operators/sample';\nexport { sampleTime } from './internal/operators/sampleTime';\nexport { scan } from './internal/operators/scan';\nexport { sequenceEqual } from './internal/operators/sequenceEqual';\nexport { share, ShareConfig } from './internal/operators/share';\nexport { shareReplay, ShareReplayConfig } from './internal/operators/shareReplay';\nexport { single } from './internal/operators/single';\nexport { skip } from './internal/operators/skip';\nexport { skipLast } from './internal/operators/skipLast';\nexport { skipUntil } from './internal/operators/skipUntil';\nexport { skipWhile } from './internal/operators/skipWhile';\nexport { startWith } from './internal/operators/startWith';\nexport { subscribeOn } from './internal/operators/subscribeOn';\nexport { switchAll } from './internal/operators/switchAll';\nexport { switchMap } from './internal/operators/switchMap';\nexport { switchMapTo } from './internal/operators/switchMapTo';\nexport { switchScan } from './internal/operators/switchScan';\nexport { take } from './internal/operators/take';\nexport { takeLast } from './internal/operators/takeLast';\nexport { takeUntil } from './internal/operators/takeUntil';\nexport { takeWhile } from './internal/operators/takeWhile';\nexport { tap, TapObserver } from './internal/operators/tap';\nexport { throttle, ThrottleConfig } from './internal/operators/throttle';\nexport { throttleTime } from './internal/operators/throttleTime';\nexport { throwIfEmpty } from './internal/operators/throwIfEmpty';\nexport { timeInterval } from './internal/operators/timeInterval';\nexport { timeout, TimeoutConfig, TimeoutInfo } from './internal/operators/timeout';\nexport { timeoutWith } from './internal/operators/timeoutWith';\nexport { timestamp } from './internal/operators/timestamp';\nexport { toArray } from './internal/operators/toArray';\nexport { window } from './internal/operators/window';\nexport { windowCount } from './internal/operators/windowCount';\nexport { windowTime } from './internal/operators/windowTime';\nexport { windowToggle } from './internal/operators/windowToggle';\nexport { windowWhen } from './internal/operators/windowWhen';\nexport { withLatestFrom } from './internal/operators/withLatestFrom';\nexport { zipAll } from './internal/operators/zipAll';\nexport { zipWith } from './internal/operators/zipWith';\n","/**\n * Job Queue Type Definitions - Discriminated Union Design\n *\n * Jobs represent async work that can be queued, processed, and monitored.\n * Uses TypeScript discriminated unions to enforce valid state transitions.\n *\n * Design principles:\n * - Each job status has specific valid fields\n * - Type narrowing works automatically via status discriminant\n * - No optional fields that may or may not exist\n * - State machine is explicit and type-safe\n */\n\nimport type { JobId, EntityType, ResourceId, UserId, GenerationJobParams, TagSchema, UnitCursor, components } from '@semiont/core';\nimport type { JobReferenceAnnotationResult, JobHighlightAnnotationResult, JobCommentAnnotationResult, JobAssessmentAnnotationResult, JobTagAnnotationResult } from '@semiont/core';\n\nexport type JobType = components['schemas']['JobType'];\nexport type JobStatus = components['schemas']['Job']['status'];\n\n// ============================================================================\n// Core Metadata and Parameters\n// ============================================================================\n\n/**\n * Job metadata - common to all states\n */\nexport interface JobMetadata {\n id: JobId;\n type: JobType;\n /**\n * Who requested the job: the verified DID the gateway stamped on the\n * `job:create`, and the ONLY identity a job carries. The dispatcher\n * records it as the requester on `job:assigned`, which is what lets a\n * write citing this job be attributed — so nothing else about the\n * requester needs to travel with the job, or be trusted from it.\n */\n userId: UserId;\n created: string;\n retryCount: number;\n maxRetries: number;\n /**\n * Checkpointed resume (ABANDONED-INFERENCE P2, HD1): the entity-type\n * units whose annotations were fully emitted by earlier failed\n * attempts. Written only by `failJob`, unioned across attempts — and\n * because `failJob` rebuilds the retried record by spreading metadata,\n * the checkpoint survives every subsequent rebuild for free. A retried\n * claim skips these units, so completed work is neither redone nor\n * duplicated.\n */\n completedUnits?: string[];\n /**\n * The finer grain `completedUnits` cannot express (CHUNK-GRAIN-RESUME P2):\n * how far each UNFINISHED unit got, keyed by unit. Written per committed\n * chunk, so a job that dies mid-unit resumes there rather than at the top —\n * which for a one-unit job (every motivation job, and the 1958 document's\n * single `Person` type) is the difference between resuming and restarting.\n *\n * A unit here is in progress, never complete; the two sets are disjoint by\n * construction in `checkpointUnits`. Merged monotonically per unit, never\n * unioned — see `mergeUnitCursors`.\n */\n unitCursors?: Record<string, UnitCursor>;\n}\n\n/**\n * Locale conventions for detection/generation params.\n *\n * Two independent locales flow through these jobs:\n *\n * - `language` — *annotation body* locale. The BCP-47 tag the LLM should\n * write generated body text in (comment text, assessment text, generated\n * resource content, tag category label). Sourced from the user's UI\n * locale. Stamped onto the W3C `TextualBody.language` field.\n *\n * - `sourceLanguage` — *source resource* locale. The BCP-47 tag of the\n * content being analyzed. Sourced from `ResourceDescriptor` (carried as\n * `Representation.language` on the primary representation). Used in\n * prompts so the LLM analyzes non-English source correctly even when\n * the user's UI locale differs.\n *\n * Examples: a German user analyzing an English document → `language='de'`,\n * `sourceLanguage='en'`. An English user detecting entities in a French\n * document → `language='en'` (unused for entity references), `sourceLanguage='fr'`.\n */\n\n/**\n * Detection job parameters\n */\nexport type DetectionParams = {\n resourceId: ResourceId;\n entityTypes: EntityType[];\n includeDescriptiveReferences?: boolean;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n};\n\n\n/**\n * Highlight detection job parameters\n */\nexport type HighlightDetectionParams = {\n resourceId: ResourceId;\n instructions?: string;\n density?: number;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n};\n\n/**\n * Assessment detection job parameters\n */\nexport type AssessmentDetectionParams = {\n resourceId: ResourceId;\n instructions?: string;\n tone?: 'analytical' | 'critical' | 'balanced' | 'constructive';\n density?: number;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n};\n\n/**\n * Comment detection job parameters\n */\nexport type CommentDetectionParams = {\n resourceId: ResourceId;\n instructions?: string;\n tone?: 'scholarly' | 'explanatory' | 'conversational' | 'technical';\n density?: number;\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n};\n\n/**\n * Tag detection job parameters.\n *\n * Carries the *full* `TagSchema` (not just an id). The dispatcher resolves\n * the caller-supplied `schemaId` against the per-KB tag-schema projection\n * at job-creation time and embeds the resolved schema here, keeping the\n * worker independent of the registry.\n */\nexport type TagDetectionParams = {\n resourceId: ResourceId;\n schema: TagSchema;\n categories: string[];\n /** Annotation body locale — see locale conventions above. */\n language?: string;\n /** Source-resource locale — see locale conventions above. */\n sourceLanguage?: string;\n};\n\n// ============================================================================\n// Generic Job State Types\n// ============================================================================\n\n/**\n * The progress a running job carries: the last its worker reported with\n * `job:report-progress`, or an empty object before the first report. One shape\n * for every job type, as the spec states it (JobRunning).\n */\nexport type StoredProgress = components['schemas']['JobStoredProgress'];\n\n/**\n * Pending job - just created, waiting to be picked up\n */\nexport interface PendingJob<P> {\n status: 'pending';\n metadata: JobMetadata;\n params: P;\n}\n\n/**\n * Running job - actively being processed\n */\nexport interface RunningJob<P> {\n status: 'running';\n metadata: JobMetadata;\n params: P;\n startedAt: string;\n progress: StoredProgress;\n}\n\n/**\n * Complete job - successfully finished\n */\nexport interface CompleteJob<P, R> {\n status: 'complete';\n metadata: JobMetadata;\n params: P;\n startedAt: string;\n completedAt: string;\n result: R;\n}\n\n/**\n * Failed job - encountered an error\n */\nexport interface FailedJob<P> {\n status: 'failed';\n metadata: JobMetadata;\n params: P;\n startedAt?: string;\n completedAt: string;\n error: string;\n}\n\n/**\n * Cancelled job - stopped by user\n */\nexport interface CancelledJob<P> {\n status: 'cancelled';\n metadata: JobMetadata;\n params: P;\n startedAt?: string;\n completedAt: string;\n}\n\n/**\n * Generic job - discriminated union of all states\n */\nexport type Job<P, R> =\n | PendingJob<P>\n | RunningJob<P>\n | CompleteJob<P, R>\n | FailedJob<P>\n | CancelledJob<P>;\n\n// ============================================================================\n// Concrete Job Types\n// ============================================================================\n\nexport type DetectionJob = Job<DetectionParams, JobReferenceAnnotationResult>;\n/** A generation job's params carry the resource the dispatcher derived from the context's focus. */\nexport type GenerationJob = Job<GenerationJobParams & { resourceId: ResourceId }, components['schemas']['JobGenerationResult']>;\nexport type HighlightDetectionJob = Job<HighlightDetectionParams, JobHighlightAnnotationResult>;\nexport type AssessmentDetectionJob = Job<AssessmentDetectionParams, JobAssessmentAnnotationResult>;\nexport type CommentDetectionJob = Job<CommentDetectionParams, JobCommentAnnotationResult>;\nexport type TagDetectionJob = Job<TagDetectionParams, JobTagAnnotationResult>;\n\n/**\n * Discriminated union of all job types\n */\nexport type AnyJob = DetectionJob | GenerationJob | HighlightDetectionJob | AssessmentDetectionJob | CommentDetectionJob | TagDetectionJob;\n\n/** A job of any type, running: what a claim returns. */\nexport type RunningAnyJob = Extract<AnyJob, { status: 'running' }>;\n\n// ============================================================================\n// Type Guards\n// ============================================================================\n\n/**\n * Narrow bus-delivered job params to the shape a processor expects.\n *\n * Job params cross the bus as `Record<string, unknown>`. Every params type in\n * this file requires exactly one field — `resourceId` — with the rest\n * optional, so that is what gets verified; absent optionals are legitimately\n * absent, not a validation failure. Callers pass the params type for the job\n * they have already branched on.\n */\nexport function asJobParams<T extends { resourceId: ResourceId }>(\n params: Record<string, unknown>,\n): T {\n if (typeof params.resourceId !== 'string') {\n throw new Error('Job params are missing a resourceId');\n }\n return params as unknown as T;\n}\n\n// Generation params are deliberately NOT covered: generation is the one job\n// that does not read a source resource (it mints one), so it requires no\n// `resourceId` and there is nothing to verify.\n\nexport function isPendingJob(job: AnyJob): job is PendingJob<any> {\n return job.status === 'pending';\n}\n\nexport function isRunningJob(job: AnyJob): job is RunningJob<any> {\n return job.status === 'running';\n}\n\nexport function isCompleteJob(job: AnyJob): job is CompleteJob<any, any> {\n return job.status === 'complete';\n}\n\nexport function isFailedJob(job: AnyJob): job is FailedJob<any> {\n return job.status === 'failed';\n}\n\nexport function isCancelledJob(job: AnyJob): job is CancelledJob<any> {\n return job.status === 'cancelled';\n}\n\n","/**\n * Bounded inference calls — WORKER-LIVENESS.md P2 (G1: prevention).\n *\n * The claim loop's only unbounded await is the model call: bus\n * operations gained transport timeouts in 0.5.6, the inference HTTP\n * request did not. One request that never settles used to wedge the\n * worker forever — the adapter ignores announcements while\n * `isProcessing`, so a single stuck call silenced the whole agent.\n * Bounding the call converts that silent hang into an ordinary job\n * failure that flows through the existing `job:fail` path (and the\n * gateway's retry budget — a timeout is transient-shaped, so retrying\n * is correct) and frees the claim loop.\n *\n * This is a timeout AND a cancellation (ABANDONED-INFERENCE P1): on expiry\n * the bound aborts the underlying request through the `InferenceClient`\n * signal, so the transport — and, on the Anthropic path, the SDK's internal\n * retry loop — is torn down rather than left running as a billed zombie\n * (P0 caught one completing 24–34 minutes after its job was gone). The\n * timeout stays as the last line either way, exactly as before; the abort is\n * the addition, not the replacement (D1). The eventual settlement of the\n * aborted promise is still swallowed so it cannot surface as an unhandled\n * rejection.\n */\n\nimport type { ElementSchema, InferenceClient, InferenceResponse, StructuredResponse } from '@semiont/inference';\nimport type { Logger } from '@semiont/core';\nimport { withSpan } from '@semiont/observability';\n\n/**\n * Generous single-call bound. Slow local models on large prompts run\n * minutes, not tens of minutes; the stall watchdog (P3) sits above\n * this at 15 minutes, and the gateway's dead-worker janitor above\n * that at 30. Fixed by design — no env knob.\n */\nexport const INFERENCE_TIMEOUT_MS = 10 * 60_000;\n\n/**\n * The bound's own rejection, typed so classification (ABANDONED-INFERENCE\n * P3) never string-matches our own error message. A timeout says nothing\n * about the request — it classifies transient.\n */\nexport class InferenceTimeoutError extends Error {\n override readonly name = 'InferenceTimeoutError';\n}\n\n/**\n * How often an in-flight call reports that it is still alive\n * (DETECTION-HEARTBEAT D2).\n *\n * Detection's other liveness signal — the chunk-boundary heartbeat — emits\n * `N − 1` events for `N` chunks, which is ZERO for the single-chunk case that\n * every realistic document falls into (the derived input budget is ~935 K\n * tokens). A 7-minute call then emits nothing at all, and the client's\n * *inter-emission* timeout (`mark-state-unit`, 180 s) kills a perfectly\n * healthy job.\n *\n * Sized against that consumer: 15 s gives ~12 beats of margin inside the\n * 180 s window. Fixed by design, like the bound above — no env knob.\n */\nexport const INFERENCE_HEARTBEAT_MS = 15_000;\n\n/**\n * Called while a provider call is still in flight. Liveness only — the\n * caller repeats its current stage rather than inventing an advancing\n * percentage (D3): nothing here knows how far a single model call has got.\n */\nexport type InferenceHeartbeat = () => void;\n\n/**\n * One span per provider call. Before this, a 411-second detection job was a\n * SINGLE span with no children on a fully instrumented stack — it was not\n * possible to tell extraction from inference from telemetry, which is what\n * made the sibling silent-empty bug expensive to find. Attributes stay to\n * what is known before the answer arrives; token counts are recorded by\n * `recordInferenceUsage` in the client.\n */\nfunction spanned<T>(client: InferenceClient, kind: string, maxTokens: number, work: () => Promise<T>): Promise<T> {\n return withSpan(`inference:${kind}`, work, {\n attrs: {\n 'inference.provider': client.type,\n 'inference.model': client.modelId,\n 'inference.max_tokens': maxTokens,\n },\n });\n}\n\nasync function withTimeout<T>(\n work: (signal: AbortSignal) => Promise<T>,\n meta: { provider: string; model: string; label: string },\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<T> {\n const controller = new AbortController();\n let timer!: ReturnType<typeof setTimeout>;\n const timedOut = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n // True cancellation: tear the request down at the transport so it\n // cannot keep running (and billing) against a job that no longer\n // exists — and name the abort in the log, because an invisible\n // abandonment is what let a zombie burn 24+ minutes unrecorded (D3).\n logger?.warn('Aborting in-flight inference call at the timeout bound', {\n provider: meta.provider,\n model: meta.model,\n label: meta.label,\n boundMs: INFERENCE_TIMEOUT_MS,\n });\n controller.abort();\n reject(new InferenceTimeoutError(\n `Inference call timed out after ${INFERENCE_TIMEOUT_MS / 60_000} minutes (${meta.label}) — failing the job to keep the claim loop live`,\n ));\n }, INFERENCE_TIMEOUT_MS);\n timer.unref?.();\n });\n\n // One timer at one site covers every provider call, present and future —\n // putting it in the detection loops instead would re-couple liveness to\n // detection's own structure, which is the coupling this exists to undo.\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n if (onHeartbeat) {\n heartbeat = setInterval(() => {\n try {\n onHeartbeat();\n } catch {\n // A failing progress emit must never take down the inference call\n // it is merely reporting on.\n }\n }, INFERENCE_HEARTBEAT_MS);\n heartbeat.unref?.();\n }\n\n const pending = work(controller.signal);\n try {\n return await Promise.race([pending, timedOut]);\n } catch (err) {\n // The aborted call settles promptly now (AbortError from the transport)\n // rather than minutes later — but its rejection still lands after the\n // race is lost, so it is still swallowed here to keep it from surfacing\n // as an unhandled one and killing the process.\n pending.catch(() => {});\n throw err;\n } finally {\n clearTimeout(timer);\n // Cleared with the timeout, in the same finally: a leaked interval would\n // beat forever on a completed job.\n if (heartbeat) clearInterval(heartbeat);\n }\n}\n\nexport function boundedGenerateWithMetadata(\n client: InferenceClient,\n prompt: string,\n maxTokens: number,\n temperature: number,\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<InferenceResponse> {\n return spanned(client, 'text', maxTokens, () => withTimeout(\n (signal) => client.generateTextWithMetadata(prompt, maxTokens, temperature, signal),\n { provider: client.type, model: client.modelId, label: `${client.type}:${client.modelId}` },\n onHeartbeat,\n logger,\n ));\n}\n\nexport function boundedGenerateStructured<T>(\n client: InferenceClient,\n prompt: string,\n maxTokens: number,\n temperature: number,\n elementSchema: ElementSchema,\n onHeartbeat?: InferenceHeartbeat,\n logger?: Logger,\n): Promise<StructuredResponse<T>> {\n return spanned(client, 'structured', maxTokens, () => withTimeout(\n (signal) => client.generateStructured<T>(prompt, maxTokens, temperature, elementSchema, signal),\n { provider: client.type, model: client.modelId, label: `${client.type}:${client.modelId}` },\n onHeartbeat,\n logger,\n ));\n}\n","/**\n * Failure classification — ABANDONED-INFERENCE P3 (A4, HD2).\n *\n * A retried deterministic failure always costs exactly double: the second\n * attempt of the same request cannot succeed. HD2's ruling is one-sided —\n * only KNOWN-deterministic failures skip the retry budget; everything\n * unrecognized stays retryable (`undefined`), because mis-classifying a\n * transient failure as deterministic silently halves reliability, while the\n * reverse merely costs one wasted attempt (today's behavior).\n *\n * Classification happens HERE, in the worker, where errors are still typed —\n * at the gateway's `job:fail` handler the failure is already a flattened\n * string, and message-regex classification is the drift this module exists\n * to avoid. The class rides the `job:fail` payload; `failJob` consumes it.\n */\n\nimport { isNumber, isObject, isString, RETRY_RULES, type components } from '@semiont/core';\nimport { StructuredReadError } from '@semiont/inference';\nimport { InferenceTimeoutError } from './workers/inference-call';\n\n/** Derived from the spec, not restated: the wire owns this vocabulary\n * (`FailureClass.json`, referenced by job:fail and job:failed alike). */\nexport type FailureClass = components['schemas']['FailureClass'];\n\n/**\n * Marker for failures WE know cannot succeed on a second identical attempt —\n * thrown at the sites that judge the work itself rather than the transport:\n * response truncation despite the derived budget, a media type with nothing\n * to extract. Throw it instead of `Error` wherever that knowledge exists.\n */\nexport class DeterministicJobError extends Error {\n // Typed string, not the literal: subclasses (YieldCollapseError) carry\n // their own name — classification is instanceof, never name-matching.\n override readonly name: string = 'DeterministicJobError';\n}\n\n/**\n * The taxonomy, and its provider coupling — THE part that will drift:\n *\n * - `@anthropic-ai/sdk` errors carry a numeric `status`, and WHICH statuses are\n * worth another attempt is not decided here: it is `RETRY_RULES.job`\n * (RETRY-CLASSIFICATION P2). This file used to restate the same three\n * conditions, which made it a second opinion on a question core already\n * answered — and the census that found it showed that where a bare list and a\n * reasoned rule disagree, the list wins silently. The rule carries the\n * reasoning; this file carries the ONE thing the rule cannot know: that\n * anything else at or above 400 is a rejected request, and re-sending it\n * unchanged is guaranteed waste → deterministic.\n * - Aborts (`APIUserAbortError` from the SDK, `AbortError` from fetch/mock)\n * are our own bound or shutdown tearing the transport down — nothing was\n * judged → transient.\n * - Ollama surfaces plain `Error`s (no status) and network failures as\n * `TypeError: fetch failed`; the SDK's `MessageStream terminated` is a\n * dropped connection. All land `undefined` → retryable, the safe default.\n * - `@semiont/inference`'s `StructuredReadError` carries the stop reason\n * because the cause classifies differently: `max_tokens` is truncation of\n * an over-demanded answer — the adapter throws before the caller's\n * `assertNotTruncated` can see the stop reason, so the classification\n * must happen on the typed error itself (measured live 2026-09-02) —\n * while any other reason is model misbehavior a retry may fix.\n */\nexport function classifyFailure(error: unknown): FailureClass | undefined {\n if (error instanceof DeterministicJobError) return 'deterministic';\n if (error instanceof InferenceTimeoutError) return 'transient';\n if (error instanceof StructuredReadError && error.stopReason === 'max_tokens') return 'deterministic';\n // A `StructuredReadError` with any OTHER stop reason falls through to\n // `undefined` — retryable, and DECIDED rather than defaulted\n // (RETRY-CLASSIFICATION P2, 2026-09-12).\n //\n // It only reaches here having exhausted `MAX_SUBDIVISION_DEPTH`, so\n // `subdividable()` has already argued the opposite: at\n // `DETECTION_TEMPERATURE` 0 the identical call returns the identical failure.\n // That argument was decisive while chunk boundaries were fixed up front. It is\n // not any more — CHUNK-GRAIN-RESUME HD2 (option C) seeds a resumed unit's size\n // from the checkpoint and then takes one shrink step, so the retry re-cuts the\n // poison piece at a DIFFERENT size and can genuinely come out differently. The\n // price of being wrong fell with it: one chunk, not the whole prefix.\n //\n // It stays `undefined` rather than becoming `'transient'` on purpose. The wire\n // vocabulary has two values, and this is neither: it is not weather, it is\n // \"retryable because the next attempt reads different input\". Claiming\n // `transient` would assert an environmental cause nobody established, and\n // absent already means exactly what is true — unrecognised, so retryable.\n if (!isObject(error)) return undefined;\n\n const name = isString(error.name) ? error.name : '';\n if (name === 'DeterministicJobError') return 'deterministic';\n if (name === 'APIUserAbortError' || name === 'AbortError') return 'transient';\n\n const status = isNumber(error.status) ? error.status : undefined;\n if (status !== undefined) {\n if (RETRY_RULES.job.retryable({ status })) return 'transient';\n if (status >= 400) return 'deterministic';\n }\n\n return undefined;\n}\n","/**\n * Adaptive chunk sizing (DETECTION-QUALITY-THROUGHPUT P2) — the sizing RULE.\n *\n * `deriveDetectionBudget` picks ONE input size for every document from provider\n * limits alone. It cannot see the document, so it is sized for a worst-case\n * dense one (input = half the output budget) — and a sparse document then pays\n * that pessimism as many tiny, overhead-dominated calls. This adjusts the chunk\n * size AS THE UNIT RUNS, from what each call actually produced, so a document\n * that turns out sparse grows into bigger chunks and a dense stretch pulls back.\n *\n * It steers ONE number: how full of the output budget each chunk came in. That\n * is the whole model, and it is enough because both hard failures are already\n * caught downstream by `callChunkSubdividing` — a chunk that truncates is\n * halved-and-retried, a chunk that outruns the guillotine times out and is\n * halved-and-retried. So the sizer does not model truncation or duration; it\n * only keeps chunks in a band that uses the budget well, and the net below it\n * forgives an overshoot. `bounds.ceiling` is therefore the WINDOW fit, not either\n * derived input size: on a shared window both of those come back at exactly the\n * density guess this function exists to replace, leaving nothing to grow into. That safety net is why this is a step rule and not a\n * control loop (user direction, 2026-09-04: keep it simple).\n *\n * \"Maximize, don't predict\": the only thing that grows a chunk is a MEASURED\n * under-use of the budget. No document statistic, no a-priori density model\n * (#1121's ban). Re-evaluated every chunk, so it tracks a gradient (sparse\n * intro → dense index) rather than betting the run on the first sample.\n *\n * Pure and feedback-only — unit-testable in isolation. The loop that applies it is\n * `runAdaptiveChunks` in `detection-chunking.ts`, which both detection paths drive:\n * `extractEntities` (reference) and `detectInChunks` (highlight, comment, assessment,\n * tag). It cuts chunk N+1 only after chunk N has reported, which is the only ordering\n * in which this function's output can reach anything.\n */\n\n/** What one chunk's call produced — the minimum the sizer needs. Duration and\n * input are NOT here: the guillotine and truncation are the hard bounds, both\n * backstopped by subdivision, so utilization is the only signal that sizing\n * acts on. (P1 telemetry records the fuller picture separately.) */\nexport interface CallOutcome {\n /** Provider-reported output tokens for the chunk, ABSENT when the provider\n * reported none.\n *\n * Absent is not zero. `usage` is optional on the inference interface and both\n * real clients emit it conditionally, so a run against a provider that stays\n * silent would read as \"this chunk produced nothing\", i.e. 0%% of the budget,\n * i.e. grow — every chunk, to the ceiling, on no evidence whatsoever. That is\n * the precise inverse of \"maximize, don't predict\". Unmeasured holds. */\n outputTokens?: number;\n /** The chunk hit a size-shaped bound (truncation or the guillotine), even if\n * subdivision then recovered it. Forces a shrink regardless of the count —\n * the signal that the last size was too big for this stretch. */\n truncated: boolean;\n}\n\n/** Provider-DERIVED sizing bounds for one job — not tuning, not policy. From\n * `deriveDetectionBudget` and the model's window; recomputed per job, never\n * user-facing. */\nexport interface SizingBounds {\n /** Smallest useful input chunk (tokens) — the overlap-derived floor. */\n floor: number;\n /** Largest input chunk (tokens) — the window-fit safety cap; never exceeded. */\n ceiling: number;\n /** The output budget one call is given. Utilization is measured against it. */\n outputBudget: number;\n}\n\n/**\n * The tuning knobs — the numbers that decide how aggressively chunk size chases\n * measured output usage. Grouped and named deliberately, because these are\n * POLICY, not derivation, and the likely future is that they become\n * user/admin-tunable, perhaps per inference provider (a fast, cheap model\n * tolerates more aggressive growth than a slow, dear one).\n *\n * That future changes where a `ChunkSizingPolicy` comes FROM — provider config,\n * a settings surface — not the sizing function, which already takes it as a\n * value, nor the caller's shape. There is exactly ONE today, the default below.\n * No config system, no env var, no per-provider map yet: just a single named\n * home, so when the need is real there is one obvious thing to make configurable\n * and one obvious place to select it (the caller holds the `InferenceClient`,\n * hence the provider).\n */\nexport interface ChunkSizingPolicy {\n /** Below this fraction of the output budget, the chunk left room — grow. */\n growBelow: number;\n /** Above this fraction, the chunk is near the edge — ease off before it\n * truncates and costs a subdivision retry. */\n shrinkAbove: number;\n /** Geometric step when growing (>1). Geometric so a genuinely sparse document\n * reaches its ceiling in a few steps and a bad step costs one correction. */\n growFactor: number;\n /** Geometric step when easing off (<1). Also the response to a truncation. */\n shrinkFactor: number;\n}\n\n/** The one policy in effect today. Coarse on purpose — subdivision forgives a\n * wrong guess — and every value is a candidate for the tunable surface above. */\nexport const DEFAULT_CHUNK_SIZING_POLICY: ChunkSizingPolicy = {\n growBelow: 0.5,\n shrinkAbove: 0.8,\n growFactor: 1.5,\n shrinkFactor: 0.7,\n};\n\nfunction clamp(value: number, lo: number, hi: number): number {\n return Math.max(lo, Math.min(hi, value));\n}\n\n/**\n * Propose the next chunk's input size from what the last chunk produced.\n *\n * A truncated chunk, or one whose output filled more than `shrinkAbove` of the\n * budget, eases the next chunk down; one that used less than `growBelow` grows\n * it; in between — or with nothing measured at all — hold. Always clamped to `[floor, ceiling]`. That is the whole\n * rule — the hard bounds are subdivision's job, not this function's.\n */\nexport function nextChunkSize(\n outcome: CallOutcome,\n current: number,\n bounds: SizingBounds,\n policy: ChunkSizingPolicy = DEFAULT_CHUNK_SIZING_POLICY,\n): number {\n const grow = () => clamp(Math.floor(current * policy.growFactor), bounds.floor, bounds.ceiling);\n const shrink = () => clamp(Math.floor(current * policy.shrinkFactor), bounds.floor, bounds.ceiling);\n const hold = () => clamp(current, bounds.floor, bounds.ceiling);\n\n if (outcome.truncated) return shrink();\n // No measurement, no move. A truncation above is evidence even without a\n // count; an absent count on its own is not.\n if (outcome.outputTokens === undefined) return hold();\n // A zero/absent budget cannot inform utilization; hold rather than divide by\n // zero or grow blindly.\n if (bounds.outputBudget <= 0) return hold();\n\n const utilization = outcome.outputTokens / bounds.outputBudget;\n if (utilization < policy.growBelow) return grow();\n if (utilization > policy.shrinkAbove) return shrink();\n return hold();\n}\n","/**\n * Detection budget derivation — pure window arithmetic over the inference\n * provider's published limits. No hand-tuned chunk constants, no density or\n * yield modeling: document content never enters this arithmetic. The guard\n * for the pathological tail (a chunk whose annotation JSON still overflows\n * the output budget) is `assertNotTruncated` below — invoked per chunk by\n * the callers on every response, not a prediction here.\n *\n * Provider shapes (see `@semiont/inference` interface.ts):\n * - Shared window (Ollama): the provider publishes\n * `maxOutputTokens === contextTokens` — prompt and response share one\n * `num_ctx`. What remains after the prompt scaffold is split\n * input:output = 1:2 (annotation JSON echoes each span plus a fixed\n * key/context envelope, so output needs the larger share). The 1:2 ratio\n * is the plan's one allocation policy — doc-independent, tuned only on\n * live evidence.\n * - Separate ceilings (Anthropic): output takes its full ceiling (duration-\n * capped below), and input follows the same 1:2 allocation — never more\n * than half the output budget. Input does NOT get \"the rest of the\n * window\": measured 2026-09-02, a window-sized chunk of entity-dense text\n * demands more output than any budget holds, so the model grinds toward\n * max_tokens for minutes (killed at the call bound as a \"stall\") or\n * collapses to the degenerate []. Large documents chunk; that is the fix,\n * not a cost.\n */\n\nimport { chunkText, cutChunk, type ChunkingConfig, type Logger, type UnitCursor } from '@semiont/core';\nimport { StructuredReadError, type InferenceLimits, type TokenUsage } from '@semiont/inference';\nimport { recordDetectionCall } from '@semiont/observability';\nimport { DeterministicJobError } from '../../failure-class';\nimport { INFERENCE_TIMEOUT_MS, InferenceTimeoutError } from '../inference-call';\nimport { nextChunkSize, type CallOutcome, type SizingBounds } from './chunk-size-controller';\n\n/**\n * A `max_tokens` stop reason means the model's JSON was cut off mid-stream.\n * Structured output serializes whatever was generated, so that still yields\n * a syntactically-valid but incomplete array — it would parse cleanly and\n * silently under-report. Fail the job loudly instead. With derived budgets\n * this fires only on pathological annotation density.\n *\n * ONE decider for every detection path (entity extraction and the four\n * motivations) — the classification must not diverge between them: same\n * input truncates the same way, so a retry is guaranteed waste and the\n * throw carries the deterministic class (ABANDONED-INFERENCE P3, A4).\n */\nexport function assertNotTruncated(response: { stopReason: string }, label: string, at: number, totalChars: number, outputBudget: number): void {\n if (response.stopReason === 'max_tokens') {\n throw new DeterministicJobError(`${label} response truncated (max_tokens) at character ${at} of ${totalChars} despite the derived output budget of ${outputBudget} tokens — failing the job rather than under-reporting annotations.`);\n }\n}\n\n/**\n * `reconcileSelector` disambiguates a span with up to 64 chars of prefix and\n * 64 of suffix (the annotation-selector schema). Overlap must let a span\n * sitting at a chunk boundary carry that context — plus a span allowance of\n * the same order — into the adjacent chunk. Schema-derived, not tuned.\n */\nconst SELECTOR_CONTEXT_CHARS = 64;\nconst OVERLAP_CHARS =\n SELECTOR_CONTEXT_CHARS + // prefix\n SELECTOR_CONTEXT_CHARS + // suffix\n 2 * SELECTOR_CONTEXT_CHARS; // span allowance\n/** ~4 chars/token — the same heuristic `estimateTokens`/`chunkText` use. */\nconst OVERLAP_TOKENS = Math.ceil(OVERLAP_CHARS / 4);\n\n/**\n * One temperature for every detection call. Detection copies spans verbatim\n * against a closed type vocabulary — a fidelity task, so determinism is the\n * right default (reproducible re-runs). Measured equal to hotter settings\n * on yield and consistency at production call sizes.\n */\nexport const DETECTION_TEMPERATURE = 0;\n\n/**\n * Assumed worst-case output rate for providers that publish none\n * (OLLAMA-DETECTION-TESTING P3b, from F9). Rate-silent providers (Ollama —\n * local hardware, rate unknowable a priori) previously got NO duration bound:\n * capacity-sizing handed a 262K-window model a ~174K-token output budget, and\n * a repetition loop then burned the full 10-minute guillotine as TRANSIENT —\n * retried identically. Under a duration-shaped cap the same loop dies in\n * minutes as max_tokens → deterministic → subdividable: the useful failure.\n *\n * 30 tok/s. P2 measured 36–90 tok/s across three local model families\n * (qwen3.5:9b ~36, gemma4:26b ~50, gemma4:e2b ~90), and the half-bound rule\n * in the cap below means real rates down to 15 tok/s still finish inside the\n * guillotine — anything slower is wedged, not working, which is exactly what\n * the guillotine is for. A conservative floor, deliberately NOT per-model:\n * F8 showed per-model thresholds chase noise. Owned policy constant, same\n * status as the 1:2 split and DETECTION_TEMPERATURE.\n */\nexport const ASSUMED_OUTPUT_TOKENS_PER_HOUR = 108_000;\n\n/**\n * The count-verifier band (OLLAMA-DETECTION-TESTING P3c, user-ratified\n * 2026-09-05): an extraction that found fewer than 1/BAND of the mentions a\n * cheap count call reports is flagged as silent yield collapse (F7). The band\n * is LOAD-BEARING at 2: F12 measured the same model flipping between\n * entity-like and mention-like enumeration on the same corpus, and that\n * legitimate judgment spread must fit INSIDE the band — probe evidence (n=6)\n * put every healthy ratio at 0.68–0.88 and every collapse at 0.18–0.41.\n */\nexport const YIELD_COLLAPSE_BAND = 2;\n\n/**\n * The silent-yield-collapse verdict (F7): a schema-clean, done-reason-clean\n * extraction that found a fraction of what a cheap count call says is present.\n * Extends DeterministicJobError because the collapse is MEASURED deterministic\n * — bit-identical across retries and across budget regimes — so a retry is\n * guaranteed waste; the classification and the size-floored subdivision\n * descent both follow from the base class. It diverges from truncation at the\n * size floor: NO re-roll (a same-size re-roll provably returns the identical\n * collapse), and — ruled 2026-09-05 after P4 attempt 1, amending the original\n * fail-the-job invariant — the floor ACCEPTS the flagged piece's `salvage`\n * loudly rather than failing the unit: one hostile ~530-char stretch had\n * discarded ~20 chunks of good extraction, and at floor sizes the count's\n * evidence sits far below anything the probe validated. The warning and the\n * 'collapsed' telemetry rows are the durable record; re-detection heals.\n */\n/** A floor-accepted piece's evidence: what extraction found against what a\n * count call reported, over a piece of this size. Facts only — never a\n * judgment against an expected yield. */\nexport interface UnderReportedPiece {\n found: number;\n counted: number;\n pieceChars: number;\n}\n\nexport class YieldCollapseError extends DeterministicJobError {\n override readonly name = 'YieldCollapseError';\n /** What the flagged extraction DID find — every span write-time-verified,\n * so discarding it at the floor would add loss on top of the under-report.\n * Carried on the error because the flag site cannot know whether descent\n * remains possible; the floor is the subdivider's knowledge. The verdict\n * rides beside it so an acceptance can report evidence, not a message\n * string. */\n constructor(message: string, readonly salvage: unknown[], readonly verdict: UnderReportedPiece) {\n super(message);\n }\n}\n\nexport interface DetectionBudget {\n /** The chunk size a run OPENS at (tokens), plus the overlap every cut keeps.\n * Opening, not fixed: `runAdaptiveChunks` moves the size within `bounds` as\n * the document reports what it actually costs. */\n chunking: ChunkingConfig;\n /** Pass as `maxTokens` on every per-chunk inference call. */\n outputBudget: number;\n /** How far the sizer may move the chunk size, in either direction. Derived\n * from the same provider arithmetic — never tuning. */\n bounds: SizingBounds;\n}\n\n/**\n * Derive the per-call input/output token budgets for a detection job from the\n * provider's actual limits and the measured prompt scaffold.\n *\n * @param limits - the provider's published ceilings (`client.limits()`)\n * @param scaffoldTokens - tokens of the prompt template around the content,\n * measured from the actually-built template (e.g. `estimateTokens(build(''))`)\n * @param typesPerCall - how many entity types (or equivalent span families)\n * ONE call asks for: output demand scales with it, so the allocation\n * divides by it. The per-type loop passes 1; a future multi-type batch\n * passes its batch size.\n * @throws when the window is too small to hold the scaffold plus a useful\n * chunk — fail-loud, same family as the truncation and window guards.\n */\nexport function deriveDetectionBudget(\n limits: InferenceLimits,\n scaffoldTokens: number,\n typesPerCall: number,\n): DetectionBudget {\n const { contextTokens, maxOutputTokens } = limits;\n const available = contextTokens - scaffoldTokens;\n\n let inputBudget: number;\n let outputBudget: number;\n\n if (maxOutputTokens >= contextTokens) {\n // Shared window: 1:2 input:output split of what the scaffold leaves.\n inputBudget = Math.floor(available / 3);\n outputBudget = available - inputBudget;\n } else {\n outputBudget = maxOutputTokens;\n inputBudget = contextTokens - outputBudget - scaffoldTokens;\n if (inputBudget <= 0) {\n // Degenerate separate-ceilings shape (output ceiling nearly fills the\n // window): fall back to the shared split rather than starving input.\n inputBudget = Math.floor(available / 3);\n outputBudget = available - inputBudget;\n }\n }\n\n // Duration floor (ABANDONED-INFERENCE P4 HD3; universalized by\n // OLLAMA-DETECTION-TESTING P3b): cap each call's output at what the\n // provider's worst-case rate finishes inside our own inference bound — a\n // call projected past the 10-minute guillotine is planned-to-fail — and\n // scale input by the same factor, so the input:output ratio (and with it\n // the per-chunk truncation risk profile) is exactly the capacity\n // solution's. Capacity says what CAN fit in one call; this says what\n // SHOULD. EVERY provider gets the bound: the published rate when there is\n // one, the conservative assumed floor when there is not — a rate-silent\n // provider with no bound turned repetition loops into hour-long transient\n // burns (F9; see ASSUMED_OUTPUT_TOKENS_PER_HOUR). It is a floor on chunk\n // count, never a raise (a tighter capacity budget is left alone). Side\n // effect worth knowing: on Anthropic this lands every detection call at\n // or under the SDK's non-streaming threshold — off the MessageStream path\n // the original `terminated` failure arrived on.\n const outputTokensPerHour = limits.outputTokensPerHour ?? ASSUMED_OUTPUT_TOKENS_PER_HOUR;\n {\n // Half the bound, not all of it: at the full bound the slowest\n // legitimate full-budget generation lands exactly on the guillotine.\n // At half, the guillotine fires only on calls at least 2× slower than\n // the provider's own worst-case model — wedged, not working.\n const durationSafeOutput = Math.floor(outputTokensPerHour * (INFERENCE_TIMEOUT_MS / 2) / 3_600_000);\n if (outputBudget > durationSafeOutput) {\n inputBudget = Math.floor(inputBudget * (durationSafeOutput / outputBudget));\n outputBudget = durationSafeOutput;\n }\n }\n\n // The 1:2 allocation policy, applied to every provider shape (the shared\n // split satisfies it by construction; separate ceilings did not). Output\n // must hold an annotation echo of every span in the chunk plus its\n // key/context envelope, so a chunk larger than half the output budget is\n // a call whose honest answer cannot fit — the failure measured live on\n // 2026-09-02 (silent multi-minute grinds to max_tokens, degenerate []).\n // The demand is PER TYPE ASKED FOR, so a K-type call divides the input\n // share by K. Still no density modeling: same one policy, content never\n // enters.\n // The window fit: the largest input that still leaves the WHOLE output budget\n // room beside it. This is the sizer's ceiling, and it is the only hard bound\n // on input there is — the two derivations above are not.\n //\n // The 1:2 rule below is a GUESS about how much output a chunk will demand,\n // and on a shared window it is baked into the 1:3 split as well, which is why\n // the ceiling cannot be read off either of them (both come back at exactly\n // the guess, leaving no room to grow into on precisely the self-hosted\n // providers the live gate runs). The duration bound is real but bounds\n // GENERATION, so it belongs to `outputBudget`; it reaches input only through\n // the same ratio guess. `nextChunkSize` exists to replace that guess with\n // measurement, so the guess opens the run and the window caps it.\n const capacityInput = contextTokens - scaffoldTokens - outputBudget;\n\n inputBudget = Math.min(inputBudget, Math.floor(outputBudget / (2 * typesPerCall)));\n\n if (inputBudget <= OVERLAP_TOKENS) {\n throw new Error(\n `Inference window too small for detection: context ${contextTokens} tokens minus scaffold ${scaffoldTokens} leaves an input budget of ${inputBudget} (need > ${OVERLAP_TOKENS}). Use a model with a larger context window or reduce the prompt scaffold.`,\n );\n }\n\n return {\n chunking: { chunkSize: inputBudget, overlap: OVERLAP_TOKENS },\n outputBudget,\n bounds: {\n // Two overlaps: at the floor a chunk is still half text it has not seen\n // before, so the cursor keeps making progress rather than re-reading its\n // own tail. Clamped under the opening size, because a cramped window can\n // derive an opening below even that — and a floor above the opening would\n // clamp every proposal upward, silently reversing the sizer.\n floor: Math.min(inputBudget, 2 * OVERLAP_TOKENS),\n // Never below the opening: a degenerate window can make the fit\n // arithmetic smaller than the size already chosen, and a ceiling under\n // the opening would clamp every proposal DOWN on the first call.\n ceiling: Math.max(inputBudget, capacityInput),\n outputBudget,\n },\n };\n}\n\n/** One chunk handed out by `runAdaptiveChunks`, with the cursor either side of\n * it. `at`/`next` over `totalChars` is exact progress — and, once\n * CHUNK-GRAIN-RESUME lands, the checkpoint identity a variable boundary forces\n * (an ordinal cannot name a chunk whose size is decided while the job runs). */\n/**\n * The half of a `UnitCursor` the DETECTION layer can honestly report: where the\n * walk stands and how it is cutting. The tallies belong to the processor, which\n * owns unit identity and unit counts — this loop counts chunks, not annotations,\n * and a zero it invented would be indistinguishable from a real one.\n */\nexport type ChunkCursor = Pick<UnitCursor, 'next' | 'size'>;\n\nexport interface AdaptiveChunk {\n piece: string;\n /** The token size this piece was cut at. Hand it to `callChunkSubdividing`:\n * a descent halves from the size that actually failed, not from the size the\n * run opened at, which adaptivity has long since left behind. */\n size: number;\n /** Characters consumed BEFORE this chunk — the in-flight liveness position. */\n at: number;\n /** Characters consumed once this chunk completes — the boundary position. */\n next: number;\n /** The document's length. */\n totalChars: number;\n}\n\n/**\n * Walk a document in chunks whose size is decided by the chunks before them.\n *\n * `chunkText` fixes every boundary up front from provider limits alone, which\n * is why the sizing rule could exist for a week and change nothing: a\n * measurement taken on chunk N had nowhere to land. Here chunk N+1 is cut only\n * after chunk N has reported, so the run opens at the static density guess and\n * then moves — a sparse document climbing toward the window's real capacity\n * (fewer, bigger calls), a dense one easing off before it pays a subdivision.\n *\n * `onChunk` returns what the chunk cost. It is awaited, so the caller's own\n * durability (committing the chunk's annotations) still gates the next cut, and\n * a throw stops the walk where it stands rather than advancing past unprocessed\n * text.\n *\n * `resume` restarts a unit an earlier attempt left partway (CHUNK-GRAIN-RESUME\n * P3) — the checkpoint P2 made durable, spent. Both halves of it matter and they\n * are spent differently: the position is taken as given, while the size is\n * seeded and then stepped ONCE, as if the last outcome had been a failure. It\n * was: the job died. Opening at the budget instead would throw away the\n * calibration the dead attempt paid for over its earlier chunks, and seeding\n * unchanged would re-cut the identical piece — which at `DETECTION_TEMPERATURE`\n * 0 returns the identical answer, failure included (HD2, option C).\n */\nexport async function runAdaptiveChunks(\n text: string,\n budget: DetectionBudget,\n onChunk: (chunk: AdaptiveChunk) => Promise<CallOutcome>,\n resume?: UnitCursor,\n): Promise<void> {\n let at = resume?.next ?? 0;\n let size = resume\n ? nextChunkSize({ truncated: true }, resume.size, budget.bounds)\n : budget.chunking.chunkSize;\n\n while (at < text.length) {\n const { piece, next } = cutChunk(text, at, { chunkSize: size, overlap: budget.chunking.overlap });\n const outcome = await onChunk({ piece, size, at, next, totalChars: text.length });\n at = next;\n size = nextChunkSize(outcome, size, budget.bounds);\n }\n}\n\n/**\n * Depth cap for TIMEOUTS only: a call still timing out on a quarter-sized\n * chunk is not a size problem, and timeouts classify transient — the\n * job-level retry is their second chance. Truncations descend by size\n * instead (see `callChunkSubdividing`).\n */\nexport const MAX_SUBDIVISION_DEPTH = 2;\n\n/** The failures a smaller chunk can plausibly fix. An unreadable response\n * that stopped naturally is model misbehavior, not size. */\n/** The F3 shape: unreadable output whose stop reason is UNKNOWN (done_reason\n * absent). Held not-subdividable through P3a for lack of evidence; the live\n * gate then reproduced it twice on real text (2026-09-03 at ~21K chars, P4\n * attempt 2 at ~4.5K, mid-descent, adjacent to max_tokens truncations that\n * healed by subdividing) and measured the retry-at-same-size alternative as a\n * deterministic 34 s burn. Size-shaped on the evidence — descends like\n * truncation, but with no floor re-roll (near-deterministic, nothing salvaged)\n * and unchanged retryable classification (a genuinely broken server still\n * deserves its budget). */\nfunction unknownUnreadable(error: unknown): boolean {\n return error instanceof StructuredReadError && error.stopReason === 'unknown';\n}\n\n/**\n * The model FINISHED and still emitted unparseable JSON — not cut off, not\n * stopped for an unknown reason. Subdividable, but DEPTH-capped rather than\n * size-floored, and the two halves of that are separately earned:\n *\n * Subdividable, because one of these killed a 26-minute attempt at chunk 25 of\n * 49 while the preceding 24 chunks parsed cleanly on the same prompt and model\n * — so the malformation was content-triggered drift, which changing the input\n * can fix. A same-size retry cannot: DETECTION_TEMPERATURE is 0, so the\n * identical call returns the identical response (the same reason a collapse\n * verdict gets no re-roll).\n *\n * Depth-capped rather than size-floored, because if the drift is instead\n * systematic — the model answering this prompt shape wrongly everywhere — every\n * extra level re-reads the same content for the same verdict. Measured, the two\n * settings often coincide (the descent aborts at the first failing sub-piece\n * instead of exploring siblings, so cost is linear in depth, not geometric),\n * and where they differ the cap is the cheaper wrong answer. Timeouts are\n * capped on the same reasoning.\n */\nfunction unreadableDespiteFinishing(error: unknown): boolean {\n return error instanceof StructuredReadError && error.stopReason === 'end_turn';\n}\n\nfunction subdividable(error: unknown): boolean {\n return error instanceof InferenceTimeoutError || truncation(error)\n || unknownUnreadable(error) || unreadableDespiteFinishing(error);\n}\n\n/** Truncation in either surface: parsed-but-flagged (`assertNotTruncated`'s\n * `DeterministicJobError`) or cut off mid-JSON (`StructuredReadError` with\n * `max_tokens`). */\nfunction truncation(error: unknown): boolean {\n return (\n error instanceof DeterministicJobError ||\n (error instanceof StructuredReadError && error.stopReason === 'max_tokens')\n );\n}\n\n/**\n * Run one chunk's inference call, subdividing IN PLACE when it fails in a\n * way a smaller chunk can fix — instead of burning the whole attempt to\n * come back at the same size. Sub-pieces re-use the caller's overlap, so\n * spans straddling a split are caught twice and fall to the downstream\n * span-keyed dedupe. On a failure subdivision cannot fix, the ORIGINAL\n * error propagates so classification sees what actually happened.\n */\n/** What `callChunkSubdividing` produced AND what it cost — the second half is\n * what `runAdaptiveChunks` sizes the next chunk from. Accumulated across the\n * whole descent, because the caller's own `call` closure sees one piece at a\n * time and cannot know a subdivision happened at all. */\nexport interface SubdividedCall<T> {\n items: T[];\n outcome: CallOutcome;\n}\n\nexport interface ChunkCallResult<T> {\n items: T[];\n /** The provider's own token counts, when it reported any. Never estimated. */\n usage?: TokenUsage;\n /** The count-verifier's expectation for this piece, when one was priced. */\n counted?: number;\n}\n\n/** Which shape of failure this was — they demand opposite responses, so the\n * history must tell them apart: truncation descends by size, a timeout fails\n * fast, anything else is not size-shaped at all. */\nfunction outcomeOf(error: unknown): 'truncated' | 'timeout' | 'collapsed' | 'error' {\n // Collapse before truncation: it IS a DeterministicJobError (so the\n // truncation check would swallow it), but in the history the two are\n // different facts — one is output overflow, the other silent under-report.\n if (error instanceof YieldCollapseError) return 'collapsed';\n if (truncation(error)) return 'truncated';\n if (error instanceof InferenceTimeoutError) return 'timeout';\n return 'error';\n}\n\nexport async function callChunkSubdividing<T>(\n label: string,\n chunk: string,\n chunking: ChunkingConfig,\n call: (piece: string) => Promise<ChunkCallResult<T>>,\n logger?: Logger,\n /** A floor-accepted piece's evidence, as it is accepted. Only the floor\n * reports: a collapse healed by descent is telemetry, not result. */\n onUnderReport?: (verdict: UnderReportedPiece) => void,\n /** Each ACCEPTED piece's count-verifier expectation — successes, floor\n * re-rolls, floor-accepted salvage. A flagged piece that descends reports\n * nothing: its children's counts replace it, or the same text is priced\n * twice. */\n onCounted?: (counted: number) => void,\n): Promise<SubdividedCall<T>> {\n // The chunk's cost, summed over however many calls its descent takes. Both\n // are recorded where EVERY call passes, so a subdivision cannot hide from\n // them.\n let outputTokens = 0;\n let sizeShaped = false;\n // A descent's calls must ALL report usage for the sum to mean anything: a\n // partial sum under-counts, and under-counting biases toward growth — the\n // one direction that costs a truncation to discover was wrong.\n let callsMade = 0;\n let callsMeasured = 0;\n // One telemetry record per model call, successes AND failures\n // (DETECTION-QUALITY-THROUGHPUT P1). This is the only place `depth` and\n // `reroll` exist, so it is the only place a complete record can be written.\n async function recorded(piece: string, depth: number, reroll: boolean): Promise<ChunkCallResult<T>> {\n const start = performance.now();\n try {\n const result = await call(piece);\n callsMade += 1;\n if (result.usage) {\n callsMeasured += 1;\n outputTokens += result.usage.outputTokens;\n }\n recordDetectionCall({\n label, pieceChars: piece.length, durationMs: performance.now() - start,\n items: result.items.length, depth, reroll, outcome: 'success',\n ...(result.usage ? { inputTokens: result.usage.inputTokens, outputTokens: result.usage.outputTokens } : {}),\n });\n // A success is always accepted — only failures subdivide.\n if (result.counted !== undefined) onCounted?.(result.counted);\n return result;\n } catch (error) {\n // A failed call still cost its input and its wall time — the descent's\n // price is invisible without it.\n recordDetectionCall({\n label, pieceChars: piece.length, durationMs: performance.now() - start,\n items: 0, depth, reroll, outcome: outcomeOf(error),\n });\n throw error;\n }\n }\n\n async function attempt(piece: string, chunkSize: number, depth: number): Promise<T[]> {\n try {\n return (await recorded(piece, depth, false)).items;\n } catch (error) {\n if (!subdividable(error)) throw error;\n // Size-shaped, so the size was wrong — true whether or not the descent\n // below rescues it. The next chunk must not be cut at a size this one\n // already paid to discover was too big.\n sizeShaped = true;\n const half = Math.floor(chunkSize / 2);\n // Truncation descends by SIZE: demand halves with each subdivision,\n // so descent terminates — and list-dense text (registers, indexes)\n // honestly yields several times its input in annotation output, so\n // the descent must go as deep as the content demands. The floor\n // derives from the overlap constant; below it even solid names fit\n // the budget. Timeouts stay depth-capped and fail fast.\n //\n // A descent must also actually CHANGE the input: once a piece fits\n // inside the smaller chunk size, re-chunking returns it unchanged, and\n // at temperature 0 the identical call returns the identical failure —\n // measured live (P4 attempt 1: one 572-char piece \"descended\" through\n // three depths, same verdict each time). A piece that cannot shrink is\n // AT its floor, whatever the arithmetic floor says.\n const pieces = chunkText(piece, { chunkSize: half, overlap: chunking.overlap });\n const shrinks = pieces.length > 1 || pieces[0] !== piece;\n // Size-shaped failures (truncation, collapse, the F3 unknown-unreadable)\n // descend to the SIZE floor; only timeouts are depth-capped — the F3 fix\n // must reach failures that first appear mid-descent (measured at depth 3).\n const canDescend = shrinks && (truncation(error) || unknownUnreadable(error)\n ? half > 2 * OVERLAP_TOKENS\n : depth < MAX_SUBDIVISION_DEPTH);\n if (!canDescend) {\n // A collapse verdict at the floor is ACCEPTED, loudly (ruled\n // 2026-09-05): its salvage flows through with a warning instead of\n // one hostile piece discarding the whole unit's work. No re-roll —\n // the collapse is deterministic, a same-size retry changes nothing.\n if (error instanceof YieldCollapseError) {\n logger?.warn('Floor-size piece still flagged as collapsed — accepting its under-reported salvage and continuing', {\n pieceChars: piece.length,\n salvaged: error.salvage.length,\n error: error.message,\n });\n onUnderReport?.(error.verdict);\n onCounted?.(error.verdict.counted);\n return error.salvage as T[];\n }\n // At the size floor honest overflow is impossible, so truncation\n // here is a degeneration loop — a sampling accident. One same-size\n // re-roll; a second truncation propagates. Timeouts get no re-roll.\n if (!truncation(error)) throw error;\n logger?.warn('Floor-size piece truncated — re-rolling once before giving up', {\n pieceChars: piece.length,\n error: error instanceof Error ? error.message : String(error),\n });\n return (await recorded(piece, depth, true)).items;\n }\n logger?.warn('Chunk call failed at a size-shaped bound — subdividing and retrying smaller', {\n depth: depth + 1,\n pieceChars: piece.length,\n nextChunkSizeTokens: half,\n error: error instanceof Error ? error.message : String(error),\n });\n const collected: T[] = [];\n for (const p of pieces) {\n collected.push(...(await attempt(p, half, depth + 1)));\n }\n return collected;\n }\n }\n const items = await attempt(chunk, chunking.chunkSize, 0);\n const measured = callsMade > 0 && callsMeasured === callsMade;\n return {\n items,\n outcome: { truncated: sizeShaped, ...(measured ? { outputTokens } : {}) },\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 * Locale handling: builders take two optional BCP-47 tags. `language` is the\n * locale the *generated body text* should be written in (sourced from the user's\n * UI locale); `sourceLanguage` is the locale of the *text being analyzed*\n * (sourced from `ResourceDescriptor` / its primary representation). They are\n * independent — see `types.ts` \"Locale conventions\" for the full discussion.\n */\n\nimport { getLocaleEnglishName } from '@semiont/core';\n\nfunction languageName(tag: string): string {\n return getLocaleEnglishName(tag) || tag;\n}\n\n/** Returns \"Source text language: <Name>.\" or empty string. */\nfunction sourceLanguageGuidance(sourceLanguage?: string): string {\n if (!sourceLanguage) return '';\n return `\\n\\nSource text language: ${languageName(sourceLanguage)}.`;\n}\n\n/** Returns \"Write your <kind> in <Name>.\" or empty string. */\nfunction bodyLanguageGuidance(language: string | undefined, kind: string): string {\n if (!language || language === 'en') return '';\n return `\\n\\nIMPORTANT: Write your ${kind} in ${languageName(language)}.`;\n}\n\nexport class MotivationPrompts {\n /**\n * Build a prompt for detecting comment-worthy passages\n *\n * @param content - The text content to analyze — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 language?: string,\n sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n const bodyLang = bodyLanguageGuidance(language, 'comments');\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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"comment\": your comment following the instructions above\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"the quarterly review meeting\", \"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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"comment\": your explanatory comment (1-3 sentences, provide context/background/clarification)\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"Ouranos\", \"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 — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\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}${sourceLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"revenue grew 45% year-over-year\", \"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}${sourceLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"we will discontinue support for legacy systems by March 2025\", \"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 — a chunk sized by the\n * caller from derived provider limits; NEVER re-truncated here (a\n * builder-level clip is silent input loss — see #738)\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 language?: string,\n sourceLanguage?: string\n ): string {\n let prompt: string;\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n const bodyLang = bodyLanguageGuidance(language, 'assessments');\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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"assessment\": your assessment following the instructions above\n\nRespond with a valid JSON array.\n\nExample:\n[\n {\"exact\": \"the quarterly revenue target\", \"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}${sourceLang}${bodyLang}\n\nText to analyze:\n---\n${content}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n- \"assessment\": your analytical assessment (1-3 sentences, evaluate validity/strength/implications)\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"AI will replace most jobs by 2030\", \"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 sourceLanguage?: string\n ): string {\n // Tags are schema-defined identifiers (\"Issue\", \"Rule\") — the LLM doesn't\n // generate the category label, so there's no body-language guidance here.\n // Only `sourceLanguage` is wired into the prompt; `language` (body locale)\n // is consumed at the body-stamp site in `processors.ts`.\n const sourceLang = sourceLanguageGuidance(sourceLanguage);\n\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)${sourceLang}\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- \"prefix\": up to 64 characters of text immediately before the passage\n- \"suffix\": up to 64 characters of text immediately after the passage\n\nRespond with a valid JSON array.\n\nExample format:\n[\n {\"exact\": \"What duty did the defendant owe?\", \"prefix\": \"The central question is: \", \"suffix\": \" This question must be\"},\n {\"exact\": \"In tort law, a duty of care is established when...\", \"prefix\": \"Legal framework:\\\\n\", \"suffix\": \"\\\\n\\\\nApplying this standard\"}\n]`;\n\n return prompt;\n }\n}\n","import type { AnchorMethod, Logger } from '@semiont/core';\nimport { recordAnchorOutcome } from '@semiont/observability';\n\n/**\n * The anchoring methods that picked a plausible occurrence rather than a\n * certain one: `first-of-many` had several candidates and no usable context,\n * `fuzzy-match` recovered through case/whitespace/Levenshtein. Neither is an\n * error — the write-time selector invariant still holds — but both are places\n * the span could be the wrong instance.\n *\n * ONE decider, deliberately. This classification lived in two places (the\n * reference path's inline warn and the motivation parsers' logger) that\n * happened to agree; two copies of a risk judgement is one copy too many.\n */\nconst DEGRADED: ReadonlySet<string> = new Set<AnchorMethod>(['first-of-many', 'fuzzy-match']);\n\n/**\n * Audit one anchoring outcome: counted always, warned only when degraded.\n *\n * Counting EVERY outcome is the point (P5). A warning tells an operator that\n * one anchor was uncertain; only a rate over all anchors says whether the\n * detection run was precise, and the rate is what the plan asks to put beside\n * the yield numbers.\n */\nexport function noteAnchor(label: string, exact: string, method: AnchorMethod, logger?: Logger): void {\n recordAnchorOutcome(label, method);\n if (!DEGRADED.has(method)) return;\n const detail = { text: exact, anchorMethod: method };\n if (logger) logger.warn('Annotation anchored via degraded method', { label, ...detail });\n else console.warn(`[${label}] anchored via ${method}: \"${exact}\"`);\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 { reconcileSelector, isObject, isString, type AnchorMethod } from '@semiont/core';\nimport type { ElementSchema } from '@semiont/inference';\nimport { noteAnchor } from './anchor-audit';\n\n// Parsers receive ALREADY-PARSED elements (`unknown[]`) from the structured\n// inference surface — `generateStructured` returns `T[]` or throws, so\n// \"could not read the model\" never reaches this layer and there is no string\n// to parse here (the former strict `parseJsonArray` moved into that contract,\n// as the earlier tolerant walker moved into it before). What remains here is\n// per-element structural validation (STRUCTURED-INFERENCE D5 — the last line\n// on the Ollama path and the schema/type drift guard) plus reconciliation\n// against the full document.\n//\n// Each element schema is declared ADJACENT to the Match interface it mirrors:\n// the schema constrains the wire, the interface is what the code consumes,\n// and nothing verifies they agree — adjacency is the drift guard.\n// `prefix`/`suffix` stay OUT of `required` deliberately: requiring them turns\n// \"sometimes absent\" into \"always present, sometimes empty\" (measured\n// 2026-08-06), an anchoring-path change Phase 3 examines before anyone\n// relies on it.\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/** Wire schema for one comment element — keep in lockstep with `CommentMatch`. */\nexport const COMMENT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n comment: { type: 'string' },\n },\n required: ['exact', 'comment'],\n additionalProperties: false,\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/** Wire schema for one highlight element — keep in lockstep with `HighlightMatch`. */\nexport const HIGHLIGHT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact'],\n additionalProperties: false,\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/** Wire schema for one assessment element — keep in lockstep with `AssessmentMatch`. */\nexport const ASSESSMENT_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n assessment: { type: 'string' },\n },\n required: ['exact', 'assessment'],\n additionalProperties: false,\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\n/**\n * Wire schema for one tag element — keep in lockstep with `RawTagInput`\n * (the category is stamped by the caller, not emitted by the model).\n */\nexport const TAG_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact'],\n additionalProperties: false,\n};\n\nexport class MotivationParsers {\n /**\n * Validate and reconcile structured comment elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated comment matches\n */\n static parseComments(parsed: unknown[], content: string): CommentMatch[] {\n\n const valid = parsed.filter((c): c is { exact: string; prefix?: string; suffix?: string; comment: string } =>\n isObject(c) &&\n isString(c.exact) &&\n isString(c.comment) &&\n c.comment.trim().length > 0\n );\n\n console.log(`[MotivationParsers] Parsed ${valid.length} valid comments from ${parsed.length} total`);\n\n const validatedComments: CommentMatch[] = [];\n for (const comment of valid) {\n const reconciled = reconcileSelector(content, {\n exact: comment.exact,\n ...(typeof comment.prefix === 'string' ? { prefix: comment.prefix } : {}),\n ...(typeof comment.suffix === 'string' ? { suffix: comment.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated comment \"${comment.exact}\"`);\n continue;\n }\n logAnchorMethod('comment', comment.exact, reconciled.anchorMethod);\n validatedComments.push({\n comment: comment.comment,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedComments;\n }\n\n /**\n * Validate and reconcile structured highlight elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated highlight matches\n */\n static parseHighlights(parsed: unknown[], content: string): HighlightMatch[] {\n\n const highlights = parsed.filter((h): h is { exact: string; prefix?: string; suffix?: string } =>\n isObject(h) && isString(h.exact)\n );\n\n const validatedHighlights: HighlightMatch[] = [];\n for (const highlight of highlights) {\n const reconciled = reconcileSelector(content, {\n exact: highlight.exact,\n ...(typeof highlight.prefix === 'string' ? { prefix: highlight.prefix } : {}),\n ...(typeof highlight.suffix === 'string' ? { suffix: highlight.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated highlight \"${highlight.exact}\"`);\n continue;\n }\n logAnchorMethod('highlight', highlight.exact, reconciled.anchorMethod);\n validatedHighlights.push({\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedHighlights;\n }\n\n /**\n * Validate and reconcile structured assessment elements.\n *\n * @param parsed - Already-parsed elements from the structured surface\n * @param content - Original content to validate offsets against\n * @returns Array of validated assessment matches\n */\n static parseAssessments(parsed: unknown[], content: string): AssessmentMatch[] {\n\n const assessments = parsed.filter((a): a is { exact: string; prefix?: string; suffix?: string; assessment: string } =>\n isObject(a) && isString(a.exact) && isString(a.assessment)\n );\n\n const validatedAssessments: AssessmentMatch[] = [];\n for (const assessment of assessments) {\n const reconciled = reconcileSelector(content, {\n exact: assessment.exact,\n ...(typeof assessment.prefix === 'string' ? { prefix: assessment.prefix } : {}),\n ...(typeof assessment.suffix === 'string' ? { suffix: assessment.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated assessment \"${assessment.exact}\"`);\n continue;\n }\n logAnchorMethod('assessment', assessment.exact, reconciled.anchorMethod);\n validatedAssessments.push({\n assessment: assessment.assessment,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n\n return validatedAssessments;\n }\n\n /**\n * Validate structured tag elements into raw, pre-reconciliation tag inputs.\n * Reconciliation happens in `validateTagOffsets`, which adds `start`/`end`\n * by anchoring `exact` against the source content.\n *\n * @param parsed - Already-parsed elements from the structured surface\n */\n static parseTags(parsed: unknown[]): RawTagInput[] {\n\n const valid = parsed.filter((t): t is RawTagInput =>\n isObject(t) && isString(t.exact) && 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 }\n\n /**\n * Anchor raw tag inputs against source content and add category.\n */\n static validateTagOffsets(\n tags: RawTagInput[],\n content: string,\n category: string\n ): TagMatch[] {\n const validatedTags: TagMatch[] = [];\n for (const tag of tags) {\n const reconciled = reconcileSelector(content, {\n exact: tag.exact,\n ...(typeof tag.prefix === 'string' ? { prefix: tag.prefix } : {}),\n ...(typeof tag.suffix === 'string' ? { suffix: tag.suffix } : {}),\n });\n if (!reconciled) {\n console.warn(`[MotivationParsers] Dropped hallucinated tag \"${tag.exact}\" for category \"${category}\"`);\n continue;\n }\n logAnchorMethod('tag', tag.exact, reconciled.anchorMethod);\n validatedTags.push({\n category,\n exact: reconciled.exact,\n start: reconciled.start,\n end: reconciled.end,\n ...(reconciled.prefix !== undefined ? { prefix: reconciled.prefix } : {}),\n ...(reconciled.suffix !== undefined ? { suffix: reconciled.suffix } : {}),\n });\n }\n return validatedTags;\n }\n}\n\n/** Raw LLM-emitted tag, pre-reconciliation. */\nexport interface RawTagInput {\n exact: string;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * Audit one anchor-method classification. Forwards to the single decider\n * shared with the reference path (`anchor-audit.ts`) — which methods count as\n * risky is one judgement, and this file used to hold a second copy of it.\n */\nfunction logAnchorMethod(motivation: string, exact: string, anchorMethod: AnchorMethod): void {\n noteAnchor(motivation, exact, anchorMethod);\n}\n","/**\n * Annotation Detection\n *\n * Orchestrates the full annotation detection pipeline:\n * 1. Build AI prompts using MotivationPrompts\n * 2. Call AI inference\n * 3. Parse and validate results using MotivationParsers\n *\n * All methods take content as a string parameter — the worker process\n * fetches it and hands it in.\n */\n\nimport type { ElementSchema, InferenceClient } from '@semiont/inference';\nimport { estimateTokens, type UnitCursor } from '@semiont/core';\nimport { boundedGenerateStructured } from './inference-call';\nimport { assertNotTruncated, callChunkSubdividing, deriveDetectionBudget, runAdaptiveChunks, type ChunkCursor, DETECTION_TEMPERATURE } from './detection/detection-chunking';\nimport { MotivationPrompts } from './detection/motivation-prompts';\nimport {\n MotivationParsers,\n COMMENT_ELEMENT_SCHEMA,\n HIGHLIGHT_ELEMENT_SCHEMA,\n ASSESSMENT_ELEMENT_SCHEMA,\n TAG_ELEMENT_SCHEMA,\n type CommentMatch,\n type HighlightMatch,\n type AssessmentMatch,\n type TagMatch,\n} from './detection/motivation-parsers';\nimport type { TagSchema } from '@semiont/core';\n\n/**\n * Per-chunk detection loop shared by the four motivations.\n *\n * Budgets derive from the provider's actual limits plus the measured prompt\n * scaffold (`buildPrompt('')`) — no literals. The prompt receives one chunk;\n * `parse` reconciles against the FULL document (the callers close over it),\n * so offsets index into the whole resource with no re-anchoring arithmetic.\n * Overlap duplicates pass through — the processor's span-keyed seen-set is\n * the single dedupe point.\n *\n * `onActivity` fires whenever the detection is demonstrably alive: at each\n * chunk boundary (the count advances) AND periodically while one inference\n * call is in flight (the count repeats — liveness, not progress). Progress is\n * the worker's liveness heartbeat AND the client's inter-emission timeout\n * signal, so a silent single-chunk run kills a healthy job\n * (DETECTION-HEARTBEAT).\n */\nasync function detectInChunks<T>(\n client: InferenceClient,\n content: string,\n buildPrompt: (chunk: string) => string,\n motivation: string,\n elementSchema: ElementSchema,\n parse: (items: unknown[]) => T[],\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /**\n * This chunk's parsed matches, awaited before the loop continues: the\n * caller commits them, and the loop must not run ahead of durability.\n * Unlike `onActivity` (a liveness heartbeat, which may repeat), this fires\n * exactly once per chunk, including the last.\n *\n * `cursor` is where the run stands once this chunk is committed — handed over\n * WITH the results so a caller cannot record a position it has not made\n * durable (CHUNK-GRAIN-RESUME P2).\n */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3).\n * Before the callback below, which stays last. */\n resume?: UnitCursor,\n onChunkResults?: (parsed: T[], cursor: ChunkCursor) => Promise<void>,\n): Promise<T[]> {\n const limits = await client.limits();\n const scaffoldTokens = estimateTokens(buildPrompt(''));\n // One motivation's spans per call — the single span family this prompt\n // asks for, the motivation-path analogue of one entity type.\n const budget = deriveDetectionBudget(limits, scaffoldTokens, 1);\n const { outputBudget } = budget;\n\n const collected: T[] = [];\n await runAdaptiveChunks(content, budget, async ({ piece: chunk, size, at, next, totalChars }) => {\n // Structured surface: parsed elements or a throw — an unreadable model\n // response fails the job rather than reading as an empty detection. A\n // size-shaped failure (duration bound, truncation) subdivides in place\n // and retries smaller before it is allowed to fail the job.\n const { items, outcome } = await callChunkSubdividing<unknown>(\n motivation, chunk, { chunkSize: size, overlap: budget.chunking.overlap },\n async (piece) => {\n const response = await boundedGenerateStructured<unknown>(\n client, buildPrompt(piece), outputBudget, DETECTION_TEMPERATURE, elementSchema,\n // Still alive, same position (a long single call is otherwise silent).\n () => onActivity?.(at, totalChars),\n );\n assertNotTruncated(response, `${motivation} detection`, at, totalChars, outputBudget);\n // Usage rides back so the telemetry record carries what the call COST\n // beside what it yielded — the provider's own counts, not an estimate.\n return { items: response.items, ...(response.usage ? { usage: response.usage } : {}) };\n },\n );\n const fromChunk = parse(items);\n collected.push(...fromChunk);\n await onChunkResults?.(fromChunk, { next, size });\n // Chunk boundary: the cursor advances (real progress). Only when text\n // remains — the final cut has no boundary after it, and the caller reports\n // the unit's completion itself.\n if (next < totalChars) onActivity?.(next, totalChars);\n return outcome;\n }, resume);\n return collected;\n}\n\nexport class AnnotationDetection {\n\n /**\n * Detect comments in content.\n *\n * `language` is the locale the LLM should write comment text in (annotation\n * body locale). `sourceLanguage` is the locale of the content being analyzed\n * (source-resource locale). See `types.ts` \"Locale conventions\" for the\n * full discussion.\n */\n static async detectComments(\n content: string,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number,\n language?: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: CommentMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<CommentMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildCommentPrompt(chunk, instructions, tone, density, language, sourceLanguage),\n 'comment', COMMENT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseComments(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect highlights in content.\n *\n * Highlights have no body — only `sourceLanguage` (source-resource locale)\n * applies, used in the prompt so the LLM analyzes non-English source\n * correctly.\n */\n static async detectHighlights(\n content: string,\n client: InferenceClient,\n instructions?: string,\n density?: number,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: HighlightMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<HighlightMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildHighlightPrompt(chunk, instructions, density, sourceLanguage),\n 'highlight', HIGHLIGHT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseHighlights(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect assessments in content.\n *\n * `language` is the locale the LLM should write assessment text in\n * (annotation body locale). `sourceLanguage` is the locale of the content\n * being analyzed (source-resource locale).\n */\n static async detectAssessments(\n content: string,\n client: InferenceClient,\n instructions?: string,\n tone?: string,\n density?: number,\n language?: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** This chunk's matches, as the chunk completes. */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: AssessmentMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<AssessmentMatch[]> {\n return detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildAssessmentPrompt(chunk, instructions, tone, density, language, sourceLanguage),\n 'assessment', ASSESSMENT_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseAssessments(items, content),\n onActivity,\n resume,\n onChunkResults,\n );\n }\n\n /**\n * Detect tags in content for a specific category.\n *\n * The full `TagSchema` is supplied by the dispatcher (resolved against\n * the per-KB tag-schema projection at job-creation time) so the worker\n * is independent of the registry.\n *\n * `sourceLanguage` is the locale of the content being analyzed. Body-locale\n * (`language`) doesn't influence the tag prompt — categories are schema\n * identifiers, not LLM-generated text — so it's consumed at the body-stamp\n * site, not here.\n */\n static async detectTags(\n content: string,\n client: InferenceClient,\n schema: TagSchema,\n category: string,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /**\n * This chunk's matches, ANCHORED before they leave: `parse` here yields\n * raw tags, so this path runs `validateTagOffsets` per chunk — a per-item\n * anchor against the full document, so partitioning changes nothing.\n */\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). */\n resume?: UnitCursor,\n /** This chunk's matches, as the chunk completes. Kept LAST. */\n onChunkResults?: (matches: TagMatch[], cursor: ChunkCursor) => Promise<void>,\n ): Promise<TagMatch[]> {\n const categoryInfo = schema.tags.find((t) => t.name === category);\n if (!categoryInfo) {\n throw new Error(`Invalid category \"${category}\" for schema ${schema.id}`);\n }\n\n // Parse per chunk; anchor once against the full document afterward.\n const parsedTags = await detectInChunks(\n client, content,\n (chunk) => MotivationPrompts.buildTagPrompt(\n chunk,\n category,\n schema.name,\n schema.description,\n schema.domain,\n categoryInfo.description,\n categoryInfo.examples,\n sourceLanguage\n ),\n 'tag', TAG_ELEMENT_SCHEMA,\n (items) => MotivationParsers.parseTags(items),\n onActivity,\n resume,\n onChunkResults\n ? async (raw, cursor) => onChunkResults(MotivationParsers.validateTagOffsets(raw, content, category), cursor)\n : undefined,\n );\n return MotivationParsers.validateTagOffsets(parsedTags, content, category);\n }\n}\n","import type { ElementSchema, InferenceClient } from '@semiont/inference';\nimport { estimateTokens, getLocaleEnglishName, isObject, isString, type Logger, type UnitCursor } from '@semiont/core';\nimport { boundedGenerateStructured, boundedGenerateWithMetadata } from '../inference-call';\nimport { assertNotTruncated, callChunkSubdividing, deriveDetectionBudget, runAdaptiveChunks, type ChunkCursor, DETECTION_TEMPERATURE, YIELD_COLLAPSE_BAND, YieldCollapseError, type UnderReportedPiece } from './detection-chunking';\n\n/**\n * Entity reference extracted from text — pre-reconciliation.\n *\n * The LLM emits `exact` (verbatim text span), `entityType`, and optional\n * `prefix` / `suffix` context for disambiguation. Offsets are not asked\n * for — `reconcileSelector` computes them by anchoring `exact` against\n * the source content in the calling processor.\n */\nexport interface ExtractedEntity {\n exact: string;\n entityType: string;\n prefix?: string;\n suffix?: string;\n}\n\n/**\n * JSON Schema for one extracted entity — the provider-enforced shape.\n *\n * Declared adjacent to `ExtractedEntity` deliberately: the schema is what\n * constrains the wire and the interface is what the code consumes, and\n * nothing verifies they agree — adjacency is the drift guard. The\n * per-element `isObject`/`isString` checks below stay as the structural\n * backstop (STRUCTURED-INFERENCE D5).\n *\n * `prefix`/`suffix` are deliberately NOT in `required`: with all four\n * required, models return `\"prefix\": \"\"` instead of omitting the key\n * (measured 2026-08-06), turning \"sometimes absent\" into \"always present,\n * sometimes empty\" — an anchoring-path change Phase 3 re-examines before\n * anyone relies on it.\n */\nconst ENTITY_ELEMENT_SCHEMA: ElementSchema = {\n type: 'object',\n properties: {\n exact: { type: 'string' },\n entityType: { type: 'string' },\n prefix: { type: 'string' },\n suffix: { type: 'string' },\n },\n required: ['exact', 'entityType'],\n additionalProperties: false,\n};\n\n/**\n * Extract entity references from text using AI.\n *\n * Locale: entity references' bodies are entity-type identifiers (not\n * LLM-generated natural-language text), so only `sourceLanguage` (source-\n * resource locale) is meaningful here — it's used in the prompt so the LLM\n * analyzes non-English source correctly. There's no body-locale parameter.\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 - Logger for entity-extraction diagnostics (parse failures,\n * anchor decisions, drops). Required so dropped/filtered entities never\n * disappear silently.\n * @param sourceLanguage - BCP-47 tag for the source content's language\n * @param onActivity - Invoked with (consumedChars, totalChars) whenever the\n * extraction is demonstrably alive: at each chunk boundary (the cursor\n * advances) AND periodically while a single inference call is in flight\n * (the position repeats — liveness, not progress). Characters, not chunk\n * ordinals: chunk sizing is decided as the run goes, so there is no chunk\n * total to divide by — and the cursor was always the more honest numerator,\n * since boundary-seeking already made chunks unequal. The caller MUST forward\n * this to its progress channel: progress is the worker's liveness\n * heartbeat for the stall watchdog, and the client's timeout is an\n * INTER-EMISSION one, so a silent single-chunk run kills a healthy job\n * (DETECTION-HEARTBEAT).\n * @returns Array of extracted entities with their character offsets\n */\n/** Output cap for the count call: the answer is one number (≤7 digits), and a\n * tiny cap is itself the safety — a ~5-token output structurally cannot loop\n * or truncate the way the extraction's array can. */\nconst COUNT_MAX_TOKENS = 16;\n\n/** The count answer, read as its leading integer. \"Respond with only the\n * number\" is the prompt's contract, but a model that pads it (\"There are 50\")\n * still yields its verdict; anything with no integer yields none. */\nfunction parseCount(text: string): number | undefined {\n const m = text.trim().match(/\\d+/);\n return m ? Number(m[0]) : undefined;\n}\n\n/**\n * The count-verifier (OLLAMA-DETECTION-TESTING P3c): guard a SUCCESSFUL\n * extraction against silent yield collapse (F7) — a schema-clean response\n * carrying a fraction of the mentions present, measured deterministic and\n * classification-invisible, so nothing else can catch it.\n *\n * A cheap count call (\"respond with only the number\") sets the expectation\n * FROM THE SAME TEXT — corpus-free, per the no-input-assumptions principle.\n * An extraction under 1/BAND of the count throws the collapse verdict, which\n * subdivision treats like truncation (descend by size) except at the floor,\n * where it fails the job loudly (user-ratified).\n *\n * The verifier's own failure — count call errors, or answers with no number —\n * disables it for the chunk (warn, pass through): a safety net's outage must\n * not take down a healthy extraction. Known limit, documented in the bug\n * report: the count saturates past ~8K chars, so margins are cleanest at\n * post-descent sizes; it still flagged every measured collapse at 16K/32K.\n */\nasync function assertYieldNotCollapsed(\n client: InferenceClient,\n piece: string,\n items: readonly unknown[],\n entityTypesDescription: string,\n logger: Logger,\n): Promise<number | undefined> {\n const prompt = `Count every mention of: ${entityTypesDescription} in the following text. Repeated mentions of the same entity count separately. Respond with only the number.\n\nText:\n\"\"\"\n${piece}\n\"\"\"`;\n\n let counted: number | undefined;\n try {\n const response = await boundedGenerateWithMetadata(client, prompt, COUNT_MAX_TOKENS, DETECTION_TEMPERATURE, undefined, logger);\n counted = parseCount(response.text);\n } catch (err) {\n logger.warn('Count-verifier call failed — yield check skipped for this chunk', {\n pieceChars: piece.length,\n error: err instanceof Error ? err.message : String(err),\n });\n return undefined;\n }\n if (counted === undefined) {\n logger.warn('Count-verifier answer carried no number — yield check skipped for this chunk', { pieceChars: piece.length });\n return undefined;\n }\n if (items.length * YIELD_COLLAPSE_BAND < counted) {\n // The salvage rides the error: descent discards it (a smaller re-run does\n // better), the floor accepts it (better than nothing, and every span is\n // write-time-verified).\n throw new YieldCollapseError(\n `Extraction found ${items.length} entities where a count call reports ~${counted} mentions (band ×${YIELD_COLLAPSE_BAND}) on a ${piece.length}-char chunk — silent yield collapse (F7): deterministic — a same-size retry returns the identical under-report.`,\n [...items],\n { found: items.length, counted, pieceChars: piece.length },\n );\n }\n return counted;\n}\n\nexport async function extractEntities(\n exact: string,\n entityTypes: string[] | { type: string; examples?: string[] }[],\n client: InferenceClient,\n includeDescriptiveReferences: boolean,\n logger: Logger,\n sourceLanguage?: string,\n onActivity?: (consumedChars: number, totalChars: number) => void,\n /** A floor-accepted piece's evidence, as it is accepted. */\n onUnderReport?: (verdict: UnderReportedPiece) => void,\n /** Each accepted piece's count-verifier expectation — the denominator. */\n onCounted?: (counted: number) => void,\n /** Where an earlier attempt left this unit (CHUNK-GRAIN-RESUME P3). Absent on\n * a first attempt, and then the run opens at the top exactly as before.\n * Deliberately BEFORE the callback below, which stays last. */\n resume?: UnitCursor,\n /**\n * This chunk's entities, awaited before the loop continues: the caller\n * commits them, and the loop must not run ahead of durability. Unlike\n * `onActivity` (a liveness heartbeat, which may repeat), this fires exactly\n * once per chunk, including the last. Kept LAST on every detection seam —\n * test harnesses read it as the final positional argument, so a parameter\n * appended after it silently starves them of results.\n *\n * `cursor` is where the run stands ONCE THIS CHUNK IS COMMITTED — the pair\n * CHUNK-GRAIN-RESUME checkpoints. It is handed over with the results rather\n * than reported separately so the two cannot drift: a caller that records the\n * position without durably committing the annotations would checkpoint ahead\n * of the log.\n */\n onChunkResults?: (items: ExtractedEntity[], cursor: ChunkCursor) => Promise<void>,\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 sourceLangGuidance = sourceLanguage\n ? `\\nSource text language: ${getLocaleEnglishName(sourceLanguage) || sourceLanguage}.\\n`\n : '';\n\n // The LLM is asked for `exact`, `prefix`, and `suffix` — no character\n // offsets. Offsets get computed by `reconcileSelector` against the\n // source content. Asking the model for offsets wastes tokens and\n // encourages it to fabricate where it shouldn't.\n const buildPrompt = (text: string): string => `Identify entity references in the following text. Look for mentions of: ${entityTypesDescription}.\n${descriptiveReferenceGuidance}${sourceLangGuidance}\nText to analyze:\n\"\"\"\n${text}\n\"\"\"\n\nRespond with a JSON array of entities found. Each entity should have:\n- exact: the exact text span from the input (quoted verbatim — character-for-character)\n- entityType: one of the provided entity types\n- prefix: up to 64 characters of text immediately before the entity (used to disambiguate when the same text appears more than once)\n- suffix: up to 64 characters of text immediately after the entity (same purpose)\n\nIf no entities are found, respond with an empty array [].\n\nExample output:\n[{\"exact\":\"Alice\",\"entityType\":\"Person\",\"prefix\":\"\",\"suffix\":\" went to\"},{\"exact\":\"Paris\",\"entityType\":\"Location\",\"prefix\":\"went to \",\"suffix\":\" yesterday\"}]`;\n\n // Budgets derive from the provider's actual limits + the measured scaffold\n // (the template around the content) — no literals. Input is chunked only\n // when the derived budget forces it; small documents make one call, as\n // before.\n const limits = await client.limits();\n // The provider DECLARES whether its extractions get count-verified\n // (universal for real providers since the 2026-09-05 ruling — unverified\n // completeness is not a savings). Jobs does no provider-specific switching:\n // whatever varies by provider is a capability on the InferenceClient\n // contract, read here like `maxConcurrency`.\n const verifyYield = client.verifyDetectionYield;\n const scaffoldTokens = estimateTokens(buildPrompt(''));\n // One call asks for every type in `entityTypes` — the processor's per-type\n // loop passes one, so this is 1 in production today.\n const budget = deriveDetectionBudget(limits, scaffoldTokens, entityTypes.length);\n const { chunking, outputBudget } = budget;\n\n logger.debug('Sending entity extraction request', {\n entityTypes: entityTypesDescription,\n chars: exact.length,\n // The size the run OPENS at, and how far measured yield may move it. The\n // chunk COUNT is deliberately absent: with sizing decided as the run goes,\n // there is no honest total until the cursor reaches the end.\n openingChunkSizeTokens: chunking.chunkSize,\n ceilingChunkSizeTokens: budget.bounds.ceiling,\n outputBudget,\n });\n\n const collected: ExtractedEntity[] = [];\n await runAdaptiveChunks(exact, budget, async ({ piece: chunk, size, at, next, totalChars }) => {\n // The structured surface returns parsed elements or THROWS — an\n // unreadable model response is a job failure, never a silent []. A\n // size-shaped failure (duration bound, truncation) subdivides in place\n // and retries smaller before it is allowed to fail the job.\n const { items, outcome } = await callChunkSubdividing<unknown>(\n 'reference', chunk, { chunkSize: size, overlap: chunking.overlap },\n async (piece) => {\n const response = await boundedGenerateStructured<unknown>(\n client,\n buildPrompt(piece),\n outputBudget,\n DETECTION_TEMPERATURE,\n ENTITY_ELEMENT_SCHEMA,\n // Still alive, same position: a long single call would otherwise emit\n // nothing at all between start and finish.\n () => onActivity?.(at, totalChars),\n logger,\n );\n logger.debug('Got entity extraction response', {\n at,\n totalChars,\n chunkSizeTokens: size,\n pieceChars: piece.length,\n items: response.items.length,\n });\n\n // Truncation is data loss, not \"no entities\" — check it BEFORE\n // consuming: a truncated structured response can still carry a valid\n // partial array, so the items themselves cannot signal the loss.\n assertNotTruncated(response, 'Entity extraction', at, totalChars, outputBudget);\n // And a CLEAN response can still be a silent under-report (F7) — the\n // count-verifier is the only signal for that, and a flag throws the\n // collapse verdict so subdivision changes the input.\n const counted = verifyYield\n ? await assertYieldNotCollapsed(client, piece, response.items, entityTypesDescription, logger)\n : undefined;\n // Usage rides back so the telemetry record carries what the call COST\n // beside what it yielded — the provider's own counts, not an estimate.\n return {\n items: response.items,\n ...(response.usage ? { usage: response.usage } : {}),\n ...(counted !== undefined ? { counted } : {}),\n };\n },\n logger, onUnderReport, onCounted,\n );\n\n const fromChunk: ExtractedEntity[] = [];\n for (const e of items) {\n // No dedupe here: overlap duplicates from adjacent chunks pass through\n // to the caller's decider — the single dedupe point.\n if (isObject(e) && isString(e.exact) && isString(e.entityType)) {\n fromChunk.push({\n exact: e.exact,\n entityType: e.entityType,\n ...(isString(e.prefix) ? { prefix: e.prefix } : {}),\n ...(isString(e.suffix) ? { suffix: e.suffix } : {}),\n });\n } else {\n logger.debug('Dropped malformed LLM entity', { entity: e });\n }\n }\n collected.push(...fromChunk);\n await onChunkResults?.(fromChunk, { next, size });\n\n // Chunk boundary: the cursor advances (real progress). Only when text\n // remains — the final cut has no boundary after it, and the caller reports\n // the unit's completion itself.\n if (next < totalChars) onActivity?.(next, totalChars);\n return outcome;\n }, resume);\n\n return collected;\n}\n","/**\n * Resource Generation\n *\n * Generates markdown resources from topics using AI inference.\n */\n\nimport { getLocaleEnglishName, deriveViews } from '@semiont/core';\nimport type { GatheredContext, Logger, SupportedMediaType } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\nimport { boundedGenerateWithMetadata } from '../inference-call';\n\n\nfunction getLanguageName(locale: string): string {\n return getLocaleEnglishName(locale) || locale;\n}\n\n// Prompt-embedding caps — bound the context fed to the model (CONTEXT-IDENTIFIERS\n// D4: named constants; promote to caller-tunable options only if a consumer\n// actually hits the wall). A fact past these bounds never reaches the model.\nconst RESOURCE_CONTENT_CAP = 4000;\nconst SEMANTIC_MATCH_LIMIT = 3;\nconst SEMANTIC_MATCH_CHARS = 240;\n\n/**\n * Model-visible identifier handle for an embedded excerpt — the ONE bracket\n * convention across all context sections (CONTEXT-IDENTIFIERS D1/D2): resource id\n * always, annotation id as a suffix when the excerpt is annotation-derived.\n */\nfunction idLabel(resourceId: string, annotationId?: string): string {\n return `[${resourceId}${annotationId ? `/${annotationId}` : ''}]`;\n}\n\n/**\n * The canonical gateway default for maxTokens — a short-definition size. The\n * UI also initialises its field to 500 as a UX convenience, but the\n * authoritative fallback lives here so direct API callers get a sensible\n * limit when they omit the parameter. Exported so error messages elsewhere\n * can name the ceiling that actually applied (one constant, no drift).\n */\nexport const DEFAULT_MAX_TOKENS = 500;\n\n/**\n * Generate resource content using inference.\n *\n * Locale parameters: `locale` is the *body* locale — the language the\n * generated resource should be written in (sourced from the user's UI\n * locale). `sourceLanguage` is the *source* locale — the language of the\n * referenced resource whose context (selected passage, surrounding text)\n * is embedded into the prompt. They're independent: a German user can\n * generate German content from an English source resource. See\n * `types.ts` \"Locale conventions\" for the full discussion.\n */\nexport async function generateResourceFromTopic(\n topic: string,\n entityTypes: string[],\n client: InferenceClient,\n logger: Logger,\n userPrompt?: string,\n locale?: string,\n context?: GatheredContext,\n temperature?: number,\n maxTokens?: number,\n sourceLanguage?: string,\n outputMediaType: SupportedMediaType = 'text/markdown',\n task: string = 'resource',\n structure?: string,\n cite: boolean = false,\n repair?: { source: string; error: string }\n): Promise<{ title: string; content: string; truncated: boolean }> {\n logger.debug('Generating resource from topic', {\n topicPreview: topic.substring(0, 100),\n entityTypes,\n hasUserPrompt: !!userPrompt,\n locale,\n sourceLanguage,\n hasContext: !!context,\n temperature,\n maxTokens,\n outputMediaType,\n task,\n structure\n });\n\n // Use provided values or defaults.\n const finalTemperature = temperature ?? 0.7;\n const finalMaxTokens = maxTokens ?? DEFAULT_MAX_TOKENS;\n\n // Determine language instructions. Body locale (\"write the resource in X\")\n // and source locale (\"the embedded source text is in Y\") are independent —\n // a German user can ask for a German write-up of an English source.\n const languageInstruction = locale && locale !== 'en'\n ? `\\n\\nIMPORTANT: Write the entire resource in ${getLanguageName(locale)}.`\n : '';\n const sourceLanguageInstruction = sourceLanguage\n ? `\\n\\nThe source resource and embedded context are in ${getLanguageName(sourceLanguage)}.`\n : '';\n\n // ── Context sections — switch on the unified GatheredContext focus ─────────\n // Annotation focus drives the annotation + selected-passage sections; resource\n // focus drives a minimal resource anchor (the full grounding — summary,\n // suggestedReferences, content — is YIELD-FROM-RESOURCE Gap B). The graph and\n // semantic sections are shared base, rendered for either focus.\n let annotationSection = '';\n let contextSection = '';\n let resourceSection = '';\n let graphSection = '';\n\n if (context) {\n const { focus } = context;\n // The focal resource's id — equal to the id `buildKnowledgeGraph` (P3) anchored\n // the graph's main node on, so `deriveViews` resolves edges. Read directly off\n // the descriptor (a plain string on the generated type); there is no event id to\n // thread here as the matcher had.\n const mainResourceId =\n focus.kind === 'annotation'\n ? focus.sourceResource['@id']\n : focus.resource['@id'];\n const focalAnnotationId = focus.kind === 'annotation' ? focus.annotation.id : undefined;\n\n if (focus.kind === 'annotation') {\n const parts: string[] = [];\n parts.push(`- Annotation motivation: ${focus.annotation.motivation}`);\n parts.push(`- Source resource: ${focus.sourceResource.name} ${idLabel(mainResourceId)}`);\n // Include body text for commenting/assessing annotations\n const { motivation, body } = focus.annotation;\n if (motivation === 'commenting' || motivation === 'assessing') {\n const bodyItem = Array.isArray(body) ? body[0] : body;\n if (bodyItem && 'value' in bodyItem && bodyItem.value) {\n const label = motivation === 'commenting' ? 'Comment' : 'Assessment';\n parts.push(`- ${label}: ${bodyItem.value}`);\n }\n }\n // The wizard's Hint: supplements or replaces the selected text as the\n // subject signal (GatheredContext.json focus.userHint). The matcher folds\n // it into its search term the same way — the two consumers of one field.\n if (focus.userHint) {\n parts.push(`- User hint (steers what to generate): ${focus.userHint}`);\n }\n annotationSection = `\\n\\nAnnotation context:\\n${parts.join('\\n')}`;\n\n if (focus.selected) {\n const { before, text, after } = focus.selected;\n contextSection = `\\n\\nSource document context:\n---\n${before ? `...${before}` : ''}\n**[${text}]**\n${after ? `${after}...` : ''}\n---\n`;\n }\n } else {\n // Resource focus — ground in the focal resource's summary, suggested\n // references, and content (omit-empty). Content is capped per resource to\n // bound prompt size; the caller already chose breadth via gather.resource.\n const parts = [`- Resource: ${focus.resource.name} ${idLabel(mainResourceId)}`];\n if (focus.summary) parts.push(`- Summary: ${focus.summary}`);\n if (focus.suggestedReferences && focus.suggestedReferences.length > 0) {\n parts.push(`- Suggested references: ${focus.suggestedReferences.join(', ')}`);\n }\n resourceSection = `\\n\\nResource context:\\n${parts.join('\\n')}`;\n\n if (focus.content?.main) {\n resourceSection += `\\n\\nResource content:\\n---\\n${focus.content.main.slice(0, RESOURCE_CONTENT_CAP)}\\n---`;\n }\n const related = Object.entries(focus.content?.related ?? {});\n if (related.length > 0) {\n const blocks = related\n .map(([id, text]) => `[${id}]\\n${text.slice(0, RESOURCE_CONTENT_CAP)}`)\n .join('\\n\\n');\n resourceSection += `\\n\\nRelated resource content:\\n---\\n${blocks}\\n---`;\n }\n }\n\n // Shared base: graph-derived neighborhood (connections / citedBy / siblings)\n // plus the LLM relationship summary, recomputed from the unified graph.\n if (mainResourceId) {\n const views = deriveViews(context.graph, mainResourceId, focalAnnotationId);\n const parts: string[] = [];\n\n if (views.connections.length > 0) {\n const connList = views.connections\n .map(c => `${c.resourceName}${c.entityTypes.length ? ` (${c.entityTypes.join(', ')})` : ''} ${idLabel(c.resourceId)}`)\n .join(', ');\n parts.push(`- Connected resources: ${connList}`);\n }\n\n if (views.citedByCount > 0) {\n const citedNames = views.citedBy.map(c => `${c.resourceName} ${idLabel(c.resourceId)}`).join(', ');\n parts.push(`- This resource is cited by ${views.citedByCount} other resource${views.citedByCount > 1 ? 's' : ''}${citedNames ? `: ${citedNames}` : ''}`);\n }\n\n if (views.siblingEntityTypes.length > 0) {\n parts.push(`- Related entity types in this document: ${views.siblingEntityTypes.join(', ')}`);\n }\n\n if (context.inferredRelationshipSummary) {\n parts.push(`- Relationship summary: ${context.inferredRelationshipSummary}`);\n }\n\n if (parts.length > 0) {\n graphSection = `\\n\\nKnowledge graph context:\\n${parts.join('\\n')}`;\n }\n }\n }\n\n // Build semantic context section if available — the vector matches the gather\n // flow already retrieved for the focal passage, used to ground generation (RAG).\n // Capped and truncated to bound prompt cost (see the named caps above); the\n // gather step pre-filters to ≤10 matches above a 0.5 cosine threshold. Each\n // passage carries its source id so the model can attribute what it uses.\n // See .plans/SEMANTIC-CONTEXT-RAG.md + .plans/CONTEXT-IDENTIFIERS.md.\n let semanticContextSection = '';\n const similar = context?.semanticContext?.similar ?? [];\n if (similar.length > 0) {\n const lines = [...similar]\n .sort((a, b) => b.score - a.score)\n .slice(0, SEMANTIC_MATCH_LIMIT)\n .map(m => `- ${idLabel(m.resourceId, m.annotationId)} (${m.score.toFixed(2)})${m.machineRead ? ' [OCR]' : ''} ${m.text.slice(0, SEMANTIC_MATCH_CHARS)}`);\n // A passage marked [OCR] was recognized from a scanned image, so its\n // wording — and especially its digits — may be misread. Saying so is the\n // whole point of carrying the flag: the model is the only reader of these\n // passages, and it would otherwise quote a scanned figure as confidently\n // as a typed one.\n const ocrNote = similar.some(m => m.machineRead)\n ? '\\nPassages marked [OCR] were read from scanned images by character recognition; treat their exact wording and numbers as uncertain, and say so if you rely on one.'\n : '';\n semanticContextSection = `\\n\\nRelated passages from the knowledge base:\\n${lines.join('\\n')}${ocrNote}`;\n }\n\n // ── Task framing (YIELD-STRUCTURE D1): canonical tasks map to tested framings;\n // an unknown task string is used VERBATIM as the framing instruction (loud\n // degrade — warn, never a silent fallback to 'resource').\n let leadLine: string;\n if (task === 'resource') {\n leadLine = `Generate a concise, informative resource about \"${topic}\".`;\n } else if (task === 'answer') {\n leadLine = `Answer the following question directly and concisely, grounded in the provided context: \"${topic}\"`;\n } else if (task === 'summary') {\n leadLine = `Write a concise summary of \"${topic}\".`;\n } else {\n logger.warn('Unknown task — using it verbatim as the framing instruction', { task });\n leadLine = `${task}\\nTopic: \"${topic}\"`;\n }\n\n // ── Structure directive (YIELD-STRUCTURE D2/D4): emitted ONLY when the caller\n // sets one — unset means no directive at all (the task framing and the model\n // determine shape). Never derived from the token budget: maxTokens is length\n // only. The forced `# Title` heading exists only under canonical 'sections'.\n const isPlainText = outputMediaType === 'text/plain';\n // PDF output means the model authors Typst source (Q1, direct Typst); the\n // worker compiles it. The prompt therefore teaches Typst syntax, and the\n // markdown scaffolding never applies.\n const isPdf = outputMediaType === 'application/pdf';\n let structureRequirement = '';\n let titleRequirement = '';\n if (structure === 'sections') {\n structureRequirement = isPdf\n ? '\\n- Organize the content into titled sections (= Heading) with well-structured paragraphs'\n : isPlainText\n ? '\\n- Organize the content into titled sections with well-structured paragraphs'\n : '\\n- Organize the content into titled sections (## Section) with well-structured paragraphs';\n if (!isPlainText && !isPdf) {\n titleRequirement = '\\n- Start with a clear heading (# Title)';\n }\n } else if (structure === 'prose') {\n structureRequirement = '\\n- Write flowing, well-structured paragraphs with no section headings';\n } else if (structure === 'chat') {\n structureRequirement = '\\n- Structure the content as a conversational chat transcript — a sequence of alternating, speaker-labeled turns (no section headings)';\n } else if (structure) {\n logger.warn('Unknown structure — passing it through as freeform organization guidance', { structure });\n structureRequirement = `\\n- Organize the output as: ${structure}`;\n }\n\n // Citation instruction (INLINE-CITATIONS): ask the model to emit [[<id>]]\n // transport tokens next to each claim, citing only ids the context embedding\n // shows. The worker strips the tokens and reconciles them into linking\n // annotations — they never reach the stored content.\n const citeRequirement = cite\n ? '\\n- Ground every claim in the provided context. Immediately after each claim, cite its source by emitting [[<id>]], where <id> is an id shown in square brackets in the context above (for a passage labeled [abc], emit [[abc]]). Cite only ids that appear in the context.'\n : '';\n\n const formatRequirements = isPdf\n ? `- Write the response as Typst markup (the Typst typesetting language — not markdown, not LaTeX)\n- Headings are written as = Heading (deeper levels == Subheading); everything else is plain prose paragraphs\n- Do not emit markdown syntax or code fences`\n : isPlainText\n ? `- Write the response as plain text — no formatting markup (no #, *, backticks, headings, or links)\n- Begin with the title on its own first line`\n : `- Use markdown formatting\n- Write the response as markdown`;\n\n // Compile-repair context (PDF-GENERATION P3): the previous Typst source\n // failed to compile; the legible compiler diagnostics go back to the model\n // as an authoritative instruction to fix and re-emit the full document.\n const repairSection = repair\n ? `\\n\\nYour previous attempt failed to compile. Fix the error and return the complete corrected document — full source, not a diff.\nCompile error:\n${repair.error}\nPrevious source:\n${repair.source}`\n : '';\n\n // The caller's prompt is an authoritative leading Instruction (YIELD-STRUCTURE D3),\n // not background \"additional context\" — task = what to produce, prompt = how.\n const prompt = `${leadLine}\n${userPrompt ? `Instruction: ${userPrompt}` : ''}${repairSection}\n${entityTypes.length > 0 ? `Focus on these entity types: ${entityTypes.join(', ')}.` : ''}${annotationSection}${contextSection}${resourceSection}${graphSection}${semanticContextSection}${sourceLanguageInstruction}${languageInstruction}\n\nRequirements:\n- Aim for approximately ${finalMaxTokens} tokens of content\n- Be factual and informative${structureRequirement}${titleRequirement}${citeRequirement}\n${formatRequirements}`;\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') || content.startsWith('```typst')) {\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 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 boundedGenerateWithMetadata(client, prompt, finalMaxTokens, finalTemperature, undefined, logger);\n logger.debug('Got response from inference', { responseLength: response.text.length, stopReason: response.stopReason });\n\n const result = parseResponse(response.text);\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 // The provider's stopReason collapses to one protocol-owned bit HERE and\n // nowhere else (GENERATE-FROM-RESOURCE D6): 'max_tokens' means the artifact\n // is cut off, not complete; every other reason is a natural stop.\n return { ...result, truncated: response.stopReason === 'max_tokens' };\n}\n","/**\n * Typst compiler invocation (PDF-GENERATION P3).\n *\n * The model writes Typst source (Q1, settled 2026-08-04: direct Typst); this\n * module turns it into PDF bytes via the pinned binary the worker image ships\n * (P2 — `/usr/local/bin/typst`, v0.15.1, resolved through PATH so tests can\n * substitute a fake). Compile failures return the legible error text — Typst's\n * `file:line:col` + caret diagnostics are the load-bearing input to the bounded\n * repair loop in `processGenerationJob`.\n */\nimport { execFileSync } from 'node:child_process';\nimport { mkdtempSync, writeFileSync, readFileSync, rmSync } from 'node:fs';\nimport { tmpdir } from 'node:os';\nimport { join } from 'node:path';\n\n/**\n * Every compile pins the PDF creation timestamp. Unpinned compiles of\n * identical source produce different bytes every time (CreationDate/ModDate),\n * which churns the content checksum and makes the Smelter re-embed a document\n * that did not change — the spurious-re-embed failure S11/S12 exist to\n * prevent. The value is arbitrary; its fixity is the point.\n */\nexport const PINNED_CREATION_TIMESTAMP = 1700000000;\n\n/**\n * Model-authored source can fail to compile; the error is fed back for repair\n * a bounded number of times, then the job fails loudly with the compiler's\n * diagnostics. Bounded because generation is non-idempotent and paid per\n * attempt — this is a repair loop, not a retry loop.\n */\nexport const MAX_COMPILE_REPAIRS = 2;\n\nexport function compileTypst(source: string): { pdf: Uint8Array } | { error: string } {\n const dir = mkdtempSync(join(tmpdir(), 'typst-'));\n try {\n const inFile = join(dir, 'doc.typ');\n const outFile = join(dir, 'doc.pdf');\n writeFileSync(inFile, source);\n try {\n execFileSync(\n 'typst',\n ['compile', '--creation-timestamp', String(PINNED_CREATION_TIMESTAMP), inFile, outFile],\n { stdio: ['ignore', 'pipe', 'pipe'] },\n );\n } catch (err) {\n const stderr = (err as { stderr?: Buffer }).stderr;\n return { error: stderr?.length ? stderr.toString('utf8') : String(err) };\n }\n return { pdf: new Uint8Array(readFileSync(outFile)) };\n } finally {\n rmSync(dir, { recursive: true, force: true });\n }\n}\n","/**\n * Citation-token resolver (INLINE-CITATIONS P1).\n *\n * Under `cite`, the generation prompt asks the model to emit `[[<resourceId>]]` /\n * `[[<resourceId>/<annotationId>]]` transport tokens after each claim, citing ids\n * the context embedding put in front of it (CONTEXT-IDENTIFIERS). Tokens are\n * TRANSPORT, not content: this resolver parses them, validates each id against the\n * ids actually present in the embedded context (the hallucination guard — an\n * unknown id is dropped loudly, never silently linked), STRIPS them from the\n * content before upload, and returns claim-span citations the worker mints as W3C\n * linking annotations on the derived resource. See .plans/INLINE-CITATIONS.md.\n */\nimport { isResourceId, type GatheredContext, type Logger, type ResourceId } from '@semiont/core';\n\nexport interface GenerationCitation {\n /** The cited source resource (validated present in the embedded context). */\n resourceId: ResourceId;\n /** The contributing annotation, when the cited excerpt was annotation-derived. */\n annotationId?: string;\n /** Claim span in the FINAL (token-stripped) content; substring(start, end) === exact. */\n start: number;\n end: number;\n exact: string;\n}\n\n/** `[[rid]]` or `[[rid/annId]]` — ids are bare (no whitespace, brackets, or slashes). */\nconst CITATION_TOKEN = /\\[\\[([^\\s[\\]/]+)(?:\\/([^\\s[\\]/]+))?\\]\\]/g;\n\n/**\n * The ids the context embedding actually put in front of the model — the\n * hallucination guard's ground truth. Mirrors what the prompt renderers label:\n * the focal resource, graph resource nodes, semantic matches, related content.\n */\nexport function collectContextResourceIds(context: GatheredContext | undefined): Set<string> {\n const ids = new Set<string>();\n if (!context) return ids;\n\n const { focus } = context;\n ids.add(focus.kind === 'annotation' ? focus.sourceResource['@id'] : focus.resource['@id']);\n for (const node of context.graph.nodes) {\n if (node.type === 'resource') ids.add(node.id);\n }\n for (const m of context.semanticContext?.similar ?? []) ids.add(m.resourceId);\n if (focus.kind === 'resource') {\n for (const id of Object.keys(focus.content?.related ?? {})) ids.add(id);\n }\n return ids;\n}\n\nexport function resolveCitationTokens(\n content: string,\n validResourceIds: ReadonlySet<string>,\n logger: Logger,\n): { content: string; citations: GenerationCitation[] } {\n const citations: GenerationCitation[] = [];\n let clean = '';\n let last = 0;\n\n for (const match of content.matchAll(CITATION_TOKEN)) {\n const token = match[0];\n const citedResourceId = match[1]!;\n const annotationId = match[2];\n\n // Append the text before the token, dropping the whitespace run immediately\n // preceding it so stripping never leaves a dangling space.\n clean += content.slice(last, match.index).replace(/[ \\t]+$/, '');\n last = match.index! + token.length;\n\n if (!isResourceId(citedResourceId) || !validResourceIds.has(citedResourceId)) {\n logger.warn('Citation token references an id absent from the provided context — dropped', {\n resourceId: citedResourceId,\n });\n continue;\n }\n\n // Claim span: the sentence preceding the token, computed against the clean\n // content. Offsets are final — later appends never shift earlier positions.\n const end = clean.length;\n let start = 0;\n for (let i = end - 2; i >= 0; i--) {\n const ch = clean[i];\n if (ch === '.' || ch === '!' || ch === '?' || ch === '\\n') {\n start = i + 1;\n break;\n }\n }\n while (start < end && /\\s/.test(clean[start]!)) start++;\n const exact = clean.slice(start, end);\n if (exact.length === 0) {\n logger.warn('Citation token has no preceding claim text — dropped', {\n resourceId: citedResourceId,\n });\n continue;\n }\n\n citations.push({\n resourceId: citedResourceId,\n ...(annotationId ? { annotationId } : {}),\n start,\n end,\n exact,\n });\n }\n\n clean += content.slice(last);\n return { content: clean, citations };\n}\n","/**\n * Run `worker` over `items` with at most `limit` of them in flight at once\n * (DETECTION-QUALITY-THROUGHPUT P6). Hand-rolled rather than a dependency: the\n * need is exactly one bounded map, and the BOUND is the whole point — detection\n * parallelizes independent entity types, but unbounded fan-out just trades\n * sequential waiting for provider 429 thrash, so the cap is the feature.\n *\n * A fixed pool of `min(limit, items.length)` pumps, each pulling the next index\n * until the work is exhausted — so at most `limit` calls are ever awaiting at\n * once, whatever the item count. Results are returned in INPUT order (a caller\n * can zip them back to items); COMPLETION order is not input order — that is the\n * point of concurrency — so a caller that must act \"as each finishes\" does so\n * inside `worker`, not on the returned array.\n *\n * Failure matches the sequential loop it replaces: the first `worker` rejection\n * rejects the whole run. Pumps already awaiting finish (they cannot be\n * cancelled mid-await), but no new item is pulled once a rejection propagates.\n */\nexport async function runBounded<T, R>(\n items: readonly T[],\n limit: number,\n worker: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const results = new Array<R>(items.length);\n let next = 0;\n\n async function pump(): Promise<void> {\n while (true) {\n const i = next++;\n if (i >= items.length) return;\n results[i] = await worker(items[i]!, i);\n }\n }\n\n const poolSize = Math.max(1, Math.min(limit, items.length));\n await Promise.all(Array.from({ length: poolSize }, () => pump()));\n return results;\n}\n","/**\n * Job Processors\n *\n * Pure functions that take content + inference client + params,\n * report progress via callback, and return annotations + results.\n *\n * No EventBus, no queue, no side effects except calling inference.\n * Driven by the remote worker process (worker-process.ts), which claims\n * jobs over SSE and dispatches by jobType to these functions.\n */\n\nimport { AnnotationDetection } from './workers/annotation-detection';\nimport { extractEntities } from './workers/detection/entity-extractor';\nimport { DEFAULT_MAX_TOKENS, generateResourceFromTopic } from './workers/generation/resource-generation';\nimport { compileTypst, MAX_COMPILE_REPAIRS } from './workers/generation/typst-compiler';\nimport { withinByteBudget, MAX_PDF_BYTES } from '@semiont/content';\nimport { resolveCitationTokens, collectContextResourceIds, type GenerationCitation } from './workers/generation/citation-resolver';\nimport { annotationIdFor } from '@semiont/event-sourcing';\nimport { GENERATABLE_MEDIA_TYPES, type Annotation, type GenerationJobParams, type Logger, type ResourceId, type SupportedMediaType, type components, type JobReferenceAnnotationResult, type JobHighlightAnnotationResult, type JobCommentAnnotationResult, type JobAssessmentAnnotationResult, type JobTagAnnotationResult, type UnitCursor } from '@semiont/core';\nimport { reconcileSelector, createFragmentSelector, locate, type ReconciledSelector, type AnchoredText } from '@semiont/core';\nimport type { InferenceClient } from '@semiont/inference';\nimport type {\n HighlightDetectionParams,\n CommentDetectionParams,\n AssessmentDetectionParams,\n DetectionParams,\n TagDetectionParams,\n} from './types';\nimport { noteAnchor } from './workers/detection/anchor-audit';\nimport { runBounded } from './workers/detection/bounded-concurrency';\n\ntype Agent = components['schemas']['Agent'];\n\n/** A detected span — offsets into the extracted `.text`, plus optional context. */\nexport type SpanMatch = { exact: string; start: number; end: number; prefix?: string; suffix?: string };\n\n/**\n * The span half of an annotation's identity (JOB-RESTART-SAFETY P3).\n *\n * Shared by both builders because the span IS the same fact in both — the PDF\n * path additionally persists geometry for it, but that geometry is derived\n * from these offsets, so hashing it too would add no distinguishing power and\n * would make an id depend on a layout the text path cannot reproduce.\n *\n * `exact` is included, not just the offsets: after a content update the same\n * offsets cover different text, and that is a different annotation.\n */\nfunction spanAnchor(match: Pick<SpanMatch, 'start' | 'end' | 'exact'>): string {\n return `${match.start}:${match.end}:${match.exact}`;\n}\n\n/**\n * Turn a detected span into a stored annotation. The media type, resource, and\n * attribution context are closed over by the caller (see `prepareDetection`);\n * the detection processor supplies only the motivation, the span, and any\n * motivation-specific body. This is the single axis that varies by media type,\n * so the detection processors themselves stay media-agnostic.\n */\nexport type BuildAnnotation = (\n motivation: Motivation,\n match: SpanMatch,\n body?: Annotation['body'],\n) => Annotation;\n\n/**\n * Progress callback. The two positional args are the required `JobProgress`\n * fields (`percentage`, `message`). The third optional arg carries the\n * job-type-specific fields (`completedEntityTypes`, `requestParams`, etc.)\n * that the progress UI renders.\n *\n * Anything in `extra` describing the RUN rather than the moment must be passed\n * on EVERY call: the client's `progress$` replaces its value per event, so a\n * field sent once disappears on the next tick.\n *\n * `message` is a CODE plus typed params, never a prose sentence\n * (ASSIST-PROGRESS-CONSOLIDATION A6). The producer reports what happened;\n * each client renders it in the user's language — react-ui from its 29\n * locales, the Go launcher from its English map. The vocabulary is frozen\n * by the census of these call sites: adding a shape means adding a variant\n * to `JobProgressMessage.json` and copy in every client, not composing a\n * new sentence here.\n */\nexport type OnProgress = (\n percentage: number,\n message: JobProgressMessage,\n extra?: Partial<JobProgress>,\n) => void;\n\ntype JobProgress = components['schemas']['JobProgress'];\n/** Derived from the wire, never restated: the per-unit entry's shape is the\n * spec's, so a field added there reaches these accumulators by regeneration\n * rather than by someone remembering two places. */\ntype CompletedItem = NonNullable<JobProgress['completedItems']>[number];\ntype JobProgressMessage = components['schemas']['JobProgressMessage'];\n\n/** The five W3C motivations this system mints — a closed vocabulary, so it is\n * typed as one rather than as `string`. */\nexport type Motivation = Annotation['motivation'];\n\n/**\n * A detection processor returns only its result. Annotations leave through\n * `onChunkComplete`, per chunk — a return that also carried them would be a\n * second path to the same write.\n */\nexport interface ProcessorResult<R> {\n result: R;\n}\n\n/**\n * Strip the audit-only fields (`anchorMethod`, `llmOffsets`, `matchQuality`)\n * off a `ReconciledSelector` so the rest is shaped like a match input for\n * `buildTextAnnotation`. The audit info belongs in logs, not in storage.\n */\nfunction toMatch(r: ReconciledSelector): { exact: string; start: number; end: number; prefix?: string; suffix?: string } {\n return {\n exact: r.exact,\n start: r.start,\n end: r.end,\n ...(r.prefix !== undefined ? { prefix: r.prefix } : {}),\n ...(r.suffix !== undefined ? { suffix: r.suffix } : {}),\n };\n}\n\n/**\n * Identity key for a built annotation: motivation + anchored span + body.\n * Two annotations with the same key are the same event written twice.\n */\nfunction annotationDedupeKey(ann: Record<string, unknown>): string {\n const target = ann.target as\n | { selector?: Array<{ type: string; start?: number; end?: number; value?: string; exact?: string; prefix?: string; suffix?: string }> }\n | undefined;\n const selectors = Array.isArray(target?.selector) ? target.selector : [];\n const pos = selectors.find((s) => s.type === 'TextPositionSelector');\n // Anchor identity is media-specific. Text annotations carry a\n // TextPositionSelector (durable char offsets). PDF annotations have none —\n // their anchor is the per-line FragmentSelector viewrect geometry plus the\n // TextQuoteSelector text. Keying only on TextPositionSelector would collapse\n // every PDF annotation sharing a motivation+body onto one (its offsets fall\n // back to '?'), so e.g. multiple PDF highlights emit as a single annotation.\n let anchor: string;\n if (pos) {\n anchor = `pos:${pos.start ?? '?'}:${pos.end ?? '?'}`;\n } else {\n const frags = selectors.filter((s) => s.type === 'FragmentSelector').map((s) => s.value ?? '').join(',');\n const quote = selectors.find((s) => s.type === 'TextQuoteSelector');\n anchor = `frag:${frags}|quote:${quote?.exact ?? ''}:${quote?.prefix ?? ''}:${quote?.suffix ?? ''}`;\n }\n return [ann.motivation as string, anchor, JSON.stringify(ann.body ?? null)].join('|');\n}\n\n/**\n * Drop annotations that are identical in the fields that define an\n * annotation's meaning: motivation, anchored span, and body.\n *\n * Why this is needed: each LLM-emitted span is reconciled independently\n * (no cross-entry coordination), and `reconcileSelector`'s `first-of-many`\n * fallback anchors every undisambiguated entry at the *same* first\n * occurrence. So a phrase repeated in non-distinctive context can produce\n * several entries that all collapse onto one span — identical events. This\n * collapses them back to one.\n *\n * What it does NOT drop: same span, *different* body (e.g. the same text\n * tagged as two entity types, or two distinct comments on one passage).\n * Those are legitimately distinct annotations.\n *\n * Applied identically by every processor below.\n */\n/**\n * THE dedupe decider — one mechanism for all five detection types, held\n * across a stream of chunk batches: adjacent chunks overlap, so the same\n * span arrives twice, and there is no post-pass to collapse it in. Scope it\n * to one emission stream — per unit for reference detection, per job for the\n * four motivations. Never add a batch post-pass beside it (gated).\n */\nfunction makeSpanDeduper(): (annotations: Annotation[]) => Annotation[] {\n const seen = new Set<string>();\n return (annotations) => {\n const out: Annotation[] = [];\n for (const ann of annotations) {\n const key = annotationDedupeKey(ann);\n if (seen.has(key)) continue;\n seen.add(key);\n out.push(ann);\n }\n return out;\n };\n}\n\nexport function buildTextAnnotation(\n content: string,\n resourceId: ResourceId,\n generator: Agent,\n motivation: Motivation,\n match: { exact: string; start: number; end: number; prefix?: string; suffix?: string },\n // Body may be a single AnnotationBody object or a non-empty array of\n // them, OR omitted entirely. W3C treats body as optional; annotations\n // whose motivation alone conveys meaning (highlighting) legitimately\n // skip it. Every other motivation currently passes something; the\n // processor that calls this makes the choice per-motivation.\n body?: Annotation['body'],\n) {\n // Write-time invariant. Every selector that reaches storage must be\n // internally consistent with the source content. If a worker bypasses\n // `reconcileSelector` or a future change re-introduces overlap, the\n // throw fires loudly here instead of corrupting the KB.\n if (content.substring(match.start, match.end) !== match.exact) {\n throw new Error(\n `buildTextAnnotation invariant: content.substring(${match.start}, ${match.end}) !== exact ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n if (match.prefix !== undefined) {\n const actualPrefix = content.substring(Math.max(0, match.start - match.prefix.length), match.start);\n if (actualPrefix !== match.prefix) {\n throw new Error(\n `buildTextAnnotation invariant: content prefix-slice !== prefix ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n }\n if (match.suffix !== undefined) {\n const actualSuffix = content.substring(match.end, Math.min(content.length, match.end + match.suffix.length));\n if (actualSuffix !== match.suffix) {\n throw new Error(\n `buildTextAnnotation invariant: content suffix-slice !== suffix ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n }\n\n // The worker says WHAT produced this — `generator`, which carries the\n // model's parameters — and nothing about who asked. `creator` and\n // `wasAttributedTo` are derived by the Stower from the cited job's own\n // events (VERIFIED-PROVENANCE P2); a payload carrying them is refused.\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationIdFor({ resourceId: resourceId as string, motivation, anchor: spanAnchor(match), body }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: {\n type: 'SpecificResource' as const,\n source: resourceId,\n selector: [\n { type: 'TextPositionSelector' as const, start: match.start, end: match.end },\n {\n type: 'TextQuoteSelector' as const,\n exact: match.exact,\n ...(match.prefix && { prefix: match.prefix }),\n ...(match.suffix && { suffix: match.suffix }),\n },\n ],\n },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * PDF sibling of `buildTextAnnotation`. The model returns the same\n * `{ exact, start, end, prefix?, suffix? }` match over the extracted text\n * layer's `text`; geometry comes from the layer, never the model.\n *\n * `target.selector` = one `FragmentSelector` per line (`locate` unions the\n * overlapping text-layer items into per-line viewrects) plus a\n * `TextQuoteSelector` anchor. No `TextPositionSelector`: the extracted text\n * layer is a derived artifact, not the stored content, so its char offsets are\n * not a durable anchor.\n *\n * **And the `id` is hashed over exactly those offsets** — `annotationIdFor` gets\n * `spanAnchor(match)`, i.e. `${start}:${end}:${exact}`. That is worth stating\n * plainly, because it sits in tension with the paragraph above: identity here\n * depends on something the annotation refuses to store, on the grounds that it is\n * not durable. The consequence is not a corrupt write but an invisible one — an\n * extraction that moved would re-identify the same visual span, and the two\n * annotations would agree in every stored field (same rects, same quoted text) and\n * differ only in `id`, so every dedupe layer would correctly let both through.\n *\n * It is left as it is on evidence, not by oversight. The offsets come from a\n * derivation cached per content checksum and gated by a stamp that a release of\n * `@semiont/content`, the PDF engine or its traineddata busts by design; measured\n * across the caret-reachable engine move (pdfjs 6.2.108 → 6.3.289) over 1,192 pages\n * of real documents, they did not move, and `pdf-offset-stability.test.ts` in\n * `@semiont/content` now fails if they ever do. The OCR path is unmeasured, and a\n * scanned document takes its whole text from there. If that gate ever fires, this\n * is the line to revisit: hashing the DURABLE anchor instead (page geometry plus\n * `exact`) makes identity depend only on what the annotation carries — at the cost\n * of one round of new ids for every PDF annotation minted afterwards.\n *\n * Write-time invariant (geometry <-> text): geometry is item-level (word runs),\n * so the covered items' text must *contain* `exact` (whitespace-normalized) —\n * containment, not reconstruction. An empty cover (no overlapping items -> no\n * rects) also fails. Throws loudly, naming the resource + motivation, rather\n * than persisting geometry that doesn't back the quoted text.\n */\nexport function buildPdfAnnotation(\n anchored: AnchoredText,\n resourceId: ResourceId,\n generator: Agent,\n motivation: Motivation,\n match: { exact: string; start: number; end: number; prefix?: string; suffix?: string },\n body?: Annotation['body'],\n) {\n // `locate` returns both the per-line rects and the overlap items it found;\n // reuse `overlap` for the containment check rather than re-scanning layer.items.\n const { rects, overlap } = locate(anchored, match.start, match.end);\n\n const coveredText = overlap.length\n ? anchored.text.substring(\n Math.min(...overlap.map((i) => i.start)),\n Math.max(...overlap.map((i) => i.end)),\n )\n : '';\n const normalize = (s: string) => s.replace(/\\s+/g, ' ').trim();\n // Two distinct failures, reported distinctly. Merged, both printed \"covered\n // text does not contain exact\" — which sends anyone debugging an empty cover\n // to inspect text matching that never ran. Same class deliberately: both stay\n // plain `Error`, so `classifyFailure` leaves them unrecognized and therefore\n // retryable (ABANDONED-INFERENCE HD2 is one-sided — only KNOWN-deterministic\n // failures skip the budget). No rects LOOKS deterministic, but the stored map\n // is keyed by content checksum, so a retry after the bytes change reads a\n // different map and can legitimately succeed.\n if (rects.length === 0) {\n throw new Error(\n `buildPdfAnnotation invariant: no rects located for offsets ${match.start}-${match.end} ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n if (!normalize(coveredText).includes(normalize(match.exact))) {\n throw new Error(\n `buildPdfAnnotation invariant: covered text does not contain exact ` +\n `for resource ${resourceId}, motivation ${motivation}`,\n );\n }\n\n // As for the text builder: `generator` only; attribution is derived downstream.\n return {\n '@context': 'http://www.w3.org/ns/anno.jsonld' as const,\n 'type': 'Annotation' as const,\n 'id': annotationIdFor({ resourceId: resourceId as string, motivation, anchor: spanAnchor(match), body }),\n motivation,\n generator,\n created: new Date().toISOString(),\n target: {\n type: 'SpecificResource' as const,\n source: resourceId,\n selector: [\n ...rects.map((coord) => ({\n type: 'FragmentSelector' as const,\n conformsTo: 'http://tools.ietf.org/rfc/rfc3778' as const,\n value: createFragmentSelector(coord),\n })),\n {\n type: 'TextQuoteSelector' as const,\n exact: match.exact,\n ...(match.prefix && { prefix: match.prefix }),\n ...(match.suffix && { suffix: match.suffix }),\n },\n ],\n },\n ...(body !== undefined ? { body } : {}),\n };\n}\n\n/**\n * Where one unit stands once the chunk just handed over is durable\n * (CHUNK-GRAIN-RESUME P2).\n *\n * The unit is named HERE rather than in the detection layer, which knows about\n * chunks and nothing about jobs: for `reference-annotation` a unit is an entity\n * type, for `tag-annotation` a category — both loop over several — and for the\n * other three the job runs exactly one unit, its own motivation.\n */\nexport interface UnitCheckpoint {\n unit: string;\n cursor: UnitCursor;\n}\n\nexport async function processHighlightJob(\n content: string,\n inferenceClient: InferenceClient,\n params: HighlightDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobHighlightAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['highlighting'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectHighlights(\n content, inferenceClient, params.instructions, params.density, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['highlighting'],\n async (matches, cursor) => {\n found += matches.length;\n // Highlights carry no body — motivation:'highlighting' on a target\n // is a complete annotation per the W3C Web Annotation Model.\n const fresh = dedupe(matches.map((h) => buildAnnotation('highlighting', h)));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n // One motivation per job, so exactly one unit — and with only one, a\n // unit-grain checkpoint could record nothing until the whole document\n // was done. The cursor is the entire resume story for these three types.\n await onChunkComplete(fresh, { unit: 'highlighting', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'highlight' }, echo);\n\n return {\n result: { kind: 'highlight-annotation', highlightsFound: found, highlightsCreated: created },\n };\n}\n\n/**\n * The user's own inputs, echoed back for the progress widget. Labels are CODES\n * (the client localizes them); values are the user's words and are shown\n * verbatim. Absent or blank inputs are omitted rather than rendered as empty\n * rows — \"Instructions:\" with nothing after it is noise, not information.\n *\n * Returned as the `extra` object rather than a bare array because every\n * `onProgress` in the run passes it: `progress$` REPLACES its value per event\n * (mark-state-unit), so a field sent once would flash at 10% and disappear.\n * The parameters describe the whole run, so every event carries them — the\n * same convention `processReferenceJob` already follows for its entity types.\n */\nfunction detectionEcho(p: {\n instructions?: string;\n tone?: string;\n density?: number;\n}): Partial<JobProgress> {\n const requestParams: Array<{ label: 'instructions' | 'tone' | 'density'; value: string }> = [];\n if (p.instructions?.trim()) requestParams.push({ label: 'instructions', value: p.instructions.trim() });\n if (p.tone?.trim()) requestParams.push({ label: 'tone', value: p.tone.trim() });\n if (p.density !== undefined) requestParams.push({ label: 'density', value: String(p.density) });\n return requestParams.length > 0 ? { requestParams } : {};\n}\n\nexport async function processCommentJob(\n content: string,\n inferenceClient: InferenceClient,\n params: CommentDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobCommentAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n // The body's `language` reflects the locale the LLM was asked to write in\n // (`params.language` — the user's UI locale). Defaults to 'en' when the\n // caller didn't specify, matching what the LLM produces by default.\n const bodyLanguage = params.language ?? 'en';\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['commenting'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectComments(\n content, inferenceClient, params.instructions, params.tone, params.density,\n params.language, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['commenting'],\n async (comments, cursor) => {\n found += comments.length;\n const fresh = dedupe(comments.map((c) =>\n // Match the pre-#651 CommentAnnotationWorker: include format and\n // language on the body TextualBody. Optional in the schema, but\n // consumers that do language-aware rendering rely on them.\n buildAnnotation('commenting', c, [\n { type: 'TextualBody', value: c.comment, purpose: 'commenting', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n ]),\n ));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n await onChunkComplete(fresh, { unit: 'commenting', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'comment' }, echo);\n\n return {\n result: { kind: 'comment-annotation', commentsFound: found, commentsCreated: created },\n };\n}\n\nexport async function processAssessmentJob(\n content: string,\n inferenceClient: InferenceClient,\n params: AssessmentDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each unit (CHUNK-GRAIN-RESUME P3), keyed the\n * same way the checkpoint is. A unit absent here starts at the top, which is\n * every unit of a first attempt. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobAssessmentAnnotationResult>> {\n const echo = detectionEcho(params);\n\n onProgress(10, { code: 'loading' }, echo);\n onProgress(30, { code: 'analyzing' }, echo);\n\n const bodyLanguage = params.language ?? 'en';\n const dedupe = makeSpanDeduper();\n // Seeded from what an earlier attempt already counted for this unit, so a\n // resumed job's terminal record describes the document rather than the\n // remainder it happened to run (CHUNK-GRAIN-RESUME HD3).\n const prior = resumeCursors?.['assessing'];\n let found = prior?.found ?? 0;\n let created = prior?.emitted ?? 0;\n await AnnotationDetection.detectAssessments(\n content, inferenceClient, params.instructions, params.tone, params.density,\n params.language, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): 30–60 band.\n (consumedChars, totalChars) => onProgress(30 + Math.round((consumedChars / totalChars) * 30), { code: 'analyzing' }, echo),\n resumeCursors?.['assessing'],\n async (assessments, cursor) => {\n found += assessments.length;\n const fresh = dedupe(assessments.map((a) =>\n // Single-object body with purpose aligned to motivation, matching the\n // pre-#651 AssessmentAnnotationWorker's shape and the majority of\n // persisted assessments. Do not switch to an array or to\n // purpose='describing' — that loses the \"this is an assessment, not\n // a description\" signal and breaks existing readers that access\n // `body.value` directly on the object.\n buildAnnotation('assessing', a, {\n type: 'TextualBody', value: a.assessment, purpose: 'assessing', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage,\n }),\n ));\n created += fresh.length;\n onProgress(60, { code: 'creating-annotations', count: created }, echo);\n await onChunkComplete(fresh, { unit: 'assessing', cursor: { ...cursor, found, emitted: created } });\n },\n );\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'assessment' }, echo);\n\n return {\n result: { kind: 'assessment-annotation', assessmentsFound: found, assessmentsCreated: created },\n };\n}\n\n/**\n * Reference detection commits per UNIT — one entity type — through\n * `onUnitComplete` (ABANDONED-INFERENCE P2, checkpointed resume): the\n * callback receives the unit's deduped annotations, and only after it\n * resolves does the unit count as complete. Emission belongs to the\n * callback alone; the processor returns only the result — returning the\n * annotations as well would recreate the post-run batch that N2 showed\n * discards completed work wholesale.\n */\nexport async function processReferenceJob(\n content: string,\n inferenceClient: InferenceClient,\n params: DetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n logger: Logger,\n /**\n * The CHECKPOINT, fired once per unit after every one of its chunks has\n * committed. It carries no annotations — the effect already happened per\n * chunk through `onChunkComplete`, and a unit callback that also carried\n * them would be a second commit path.\n */\n onUnitComplete: (entityType: string) => Promise<void>,\n signal?: AbortSignal,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete?: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each entity-type unit (CHUNK-GRAIN-RESUME P3).\n * A unit absent here starts at the top; units already COMPLETE never reach\n * this function at all, the caller having filtered them out. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<{ result: JobReferenceAnnotationResult }> {\n const entityTypeNames = params.entityTypes.map(String);\n const requestParams = [{ label: 'entity-types' as const, value: entityTypeNames.join(', ') }];\n const completedItems: CompletedItem[] = [];\n // Seeded with what earlier attempts already counted for the units this\n // attempt is RESUMING. Units that completed earlier carry no cursor — they\n // are filtered out before this function sees them — so their share is still\n // missing from the job total. That is the pre-existing unit-grain gap, named\n // in CHUNK-GRAIN-RESUME rather than silently half-fixed here.\n let totalFound = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.found, 0);\n let totalEmitted = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.emitted, 0);\n let errors = 0;\n let totalUnderReportedPieces = 0;\n // The denominator: cumulative count-verifier expectations over accepted\n // pieces. Zero means no piece was priced — the frame then carries nothing.\n let totalExpected = 0;\n\n onProgress(10, { code: 'loading' }, { requestParams });\n\n const bodyLanguage = params.language ?? 'en';\n\n // Entity types run BOUNDED-CONCURRENT (DETECTION-QUALITY-THROUGHPUT P6).\n // They are independent units — own extraction, own commit, own checkpoint —\n // and a single sequential job used a sliver of the provider's rate limit, so\n // the old `for … await` was the 9×-sequential ≈ 2.5 h/document. The bound is\n // the point: unbounded fan-out just trades sequential waiting for 429 thrash.\n //\n // Shared counters and `completedItems` are mutated SYNCHRONOUSLY between\n // awaits inside the worker — safe under the single-threaded event loop (no\n // read-modify-write straddles an await), so no locking is needed. Progress is\n // now \"M of N done\" rather than \"on type i\": concurrent types finish out of\n // order, and `completedItems` already tolerates that.\n let completed = 0;\n const total = entityTypeNames.length;\n\n const emitTypeProgress = (entityTypeName: string): void => {\n const pct = 20 + Math.round((completed / total) * 60);\n onProgress(pct, { code: 'detecting-entities', entityType: entityTypeName }, {\n current: { kind: 'entity-type', value: entityTypeName },\n processed: completed,\n total,\n entitiesFound: totalFound,\n ...(totalExpected > 0 ? { entitiesExpected: totalExpected } : {}),\n entitiesEmitted: totalEmitted,\n completedItems: [...completedItems],\n requestParams,\n });\n };\n\n // Concurrency is the PROVIDER's capability, not a flat constant: a hosted\n // API parallelizes, a local single-model server does not (P6). Reading it\n // from the client is what makes the same code correct on both.\n await runBounded(entityTypeNames, inferenceClient.maxConcurrency, async (entityTypeName) => {\n if (!entityTypeName) return;\n // Cooperative cancellation (JOB-RESTART-SAFETY P4): once aborted, a pending\n // type is skipped when its turn comes; types already in flight finish and\n // commit, so committed units stay checkpointed. The caller reads\n // `signal.aborted` to move the job to cancelled/ rather than complete/.\n if (signal?.aborted) return;\n\n emitTypeProgress(entityTypeName);\n\n // Unresolved reference body: the entity type as a tagging TextualBody,\n // stamped with the body locale to match the comment/assess/tag pattern.\n // The bind flow later appends a SpecificResource (purpose: 'linking') via\n // mark:body-updated to produce the resolved shape. Emitting an empty body\n // would break the append contract.\n const unresolvedBody: Annotation['body'] = [\n { type: 'TextualBody' as const, value: entityTypeName, purpose: 'tagging' as const, format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n ];\n\n // One deduper per unit, held across its chunks.\n const dedupe = makeSpanDeduper();\n // Seeded from what earlier attempts already counted for THIS unit, so the\n // terminal record describes the document rather than the remainder this\n // attempt happened to run. Absent (a first attempt) means zero, which is\n // the truth rather than a default.\n const priorUnit = resumeCursors?.[entityTypeName];\n let unitFound = priorUnit?.found ?? 0;\n let unitPersisted = priorUnit?.emitted ?? 0;\n // What remains unknown at the unit's end: floor-accepted pieces, folded.\n let underReported: { pieces: number; found: number; counted: number } | undefined;\n await extractEntities(\n content, [entityTypeName], inferenceClient, params.includeDescriptiveReferences ?? false, logger,\n params.sourceLanguage,\n // Liveness heartbeat (DETECTION-HEARTBEAT): fires at chunk boundaries and\n // every ~15 s while a call is in flight, so a long single-chunk call is\n // not silent. It repeats the current position rather than inventing an\n // advance — the stall watchdog, janitor and client timeout need a signal,\n // not a monotone.\n () => emitTypeProgress(entityTypeName),\n (verdict) => {\n underReported = {\n pieces: (underReported?.pieces ?? 0) + 1,\n found: (underReported?.found ?? 0) + verdict.found,\n counted: (underReported?.counted ?? 0) + verdict.counted,\n };\n },\n (counted) => {\n totalExpected += counted;\n emitTypeProgress(entityTypeName);\n },\n resumeCursors?.[entityTypeName],\n async (chunkEntities, cursor) => {\n const built: Annotation[] = [];\n for (const entity of chunkEntities) {\n const reconciled = reconcileSelector(content, {\n exact: entity.exact,\n ...(entity.prefix !== undefined ? { prefix: entity.prefix } : {}),\n ...(entity.suffix !== undefined ? { suffix: entity.suffix } : {}),\n });\n if (!reconciled) {\n logger.error('Entity dropped — text not found in source', {\n text: entity.exact,\n entityType: entity.entityType,\n });\n errors++;\n continue;\n }\n noteAnchor('reference', entity.exact, reconciled.anchorMethod, logger);\n built.push(buildAnnotation('linking', toMatch(reconciled), unresolvedBody));\n }\n const fresh = dedupe(built);\n // What this chunk makes true ONCE IT IS DURABLE. Computed before the\n // commit because the checkpoint is written inside it and has to carry\n // the running totals — a checkpoint reporting only this attempt's share\n // would reset the count on every death — but assigned after, so the\n // invariant below still holds.\n const nextFound = unitFound + chunkEntities.length;\n const nextEmitted = unitPersisted + fresh.length;\n // Awaited: a failed commit fails the unit before it can checkpoint;\n // the cursor rides with it so the checkpoint trails the log by\n // construction rather than by the caller remembering to order them.\n await onChunkComplete?.(fresh, {\n unit: entityTypeName,\n cursor: { ...cursor, found: nextFound, emitted: nextEmitted },\n });\n // Tallies move only PAST the awaited commit — a chunk that fails to\n // commit contributes nothing anywhere — and the numerator advances at\n // the same grain as the denominator: per chunk, in the same frame\n // family the viewer's found-of-~expected tally reads.\n unitFound = nextFound;\n unitPersisted = nextEmitted;\n totalFound += chunkEntities.length;\n totalEmitted += fresh.length;\n emitTypeProgress(entityTypeName);\n },\n );\n\n // Every chunk of this unit is durable; only now may it checkpoint.\n await onUnitComplete(entityTypeName);\n // Found vs persisted, per unit — the gap between them is this flow's yield.\n completedItems.push({\n value: entityTypeName,\n foundCount: unitFound,\n persistedCount: unitPersisted,\n ...(underReported ? { underReported } : {}),\n });\n if (underReported) totalUnderReportedPieces += underReported.pieces;\n completed++;\n emitTypeProgress(entityTypeName);\n });\n\n // The terminal frame carries the completed set, and it is the only frame\n // that can: the per-unit entries ride the progress emitted at the START of\n // each unit, so the LAST unit's entry — and on a single-type job, every\n // entry — was never reported anywhere (DETECTION-QUALITY-THROUGHPUT P1).\n onProgress(100, { code: 'complete-created', count: totalEmitted, kind: 'reference' }, {\n ...(totalExpected > 0 ? { entitiesExpected: totalExpected } : {}),\n completedItems: [...completedItems],\n requestParams,\n });\n\n return {\n result: {\n kind: 'reference-annotation', totalFound, totalEmitted, errors,\n ...(totalUnderReportedPieces > 0 ? { underReportedPieces: totalUnderReportedPieces } : {}),\n },\n };\n}\n\nexport async function processTagJob(\n content: string,\n inferenceClient: InferenceClient,\n params: TagDetectionParams,\n buildAnnotation: BuildAnnotation,\n onProgress: OnProgress,\n /** This chunk's novel annotations, awaited: the durability write. */\n onChunkComplete: (annotations: Annotation[], checkpoint: UnitCheckpoint) => Promise<void>,\n /** Where earlier attempts left each CATEGORY (CHUNK-GRAIN-RESUME P3) — a tag\n * job's units are its categories, not its motivation: each walks the whole\n * document, so one shared cursor would skip text for all but one of them. */\n resumeCursors?: Record<string, UnitCursor>,\n): Promise<ProcessorResult<JobTagAnnotationResult>> {\n onProgress(10, { code: 'loading' });\n onProgress(30, { code: 'analyzing-tags' });\n\n const bodyLanguage = params.language ?? 'en';\n // One deduper across every category: they share an emission stream, and\n // the key includes the body, so only true repeats collapse.\n const dedupe = makeSpanDeduper();\n // Resumed tallies (CHUNK-GRAIN-RESUME HD3), and the two are seeded\n // DIFFERENTLY because they accumulate differently. `found` sums each\n // category's own running total at the end of that category, and those totals\n // are already seeded — seeding here too would count the earlier attempt\n // twice. `created` accumulates per chunk from this attempt only, so it must\n // start at what earlier attempts committed.\n let found = 0;\n let created = Object.values(resumeCursors ?? {}).reduce((n, c) => n + c.emitted, 0);\n // byCategory counts the DEDUPED set so the per-category counts match what\n // is actually stored. The category is the first (tagging) TextualBody.\n const byCategory: Record<string, number> = {};\n const completedItems: CompletedItem[] = [];\n\n for (let c = 0; c < params.categories.length; c++) {\n const category = params.categories[c]!;\n // The loop always existed; it just never reported itself, so the tag flow\n // was the one counting flow with no subject line (CLEAN-PROGRESS A5).\n const position = () => ({\n current: { kind: 'category' as const, value: category },\n processed: c,\n total: params.categories.length,\n completedItems: [...completedItems],\n });\n onProgress(\n 30 + Math.round((c / params.categories.length) * 30),\n { code: 'analyzing-tags' },\n position(),\n );\n // This category's own running tallies, seeded from its cursor so the\n // checkpoint it writes stays continuable for a third attempt.\n const priorCategory = resumeCursors?.[category];\n let categoryFound = priorCategory?.found ?? 0;\n let categoryCreated = priorCategory?.emitted ?? 0;\n await AnnotationDetection.detectTags(\n content, inferenceClient, params.schema, category, params.sourceLanguage,\n // Liveness (chunk boundaries + in-flight heartbeat): this category's\n // slice of the 30–60 band.\n (consumedChars, totalChars) => onProgress(\n 30 + Math.round(((c + consumedChars / totalChars) / params.categories.length) * 30),\n { code: 'analyzing-tags' },\n position(),\n ),\n resumeCursors?.[category],\n async (matches, cursor) => {\n categoryFound += matches.length;\n const fresh = dedupe(matches.map((t) => {\n const cat = t.category ?? 'unknown';\n // Two-body shape matches the pre-#651 TagAnnotationWorker and every\n // persisted tag annotation: the category as a tagging TextualBody,\n // plus the tagging-schema id as a classifying TextualBody. The\n // classifying body is the only trace of schema provenance in the\n // event log — do not drop it.\n return buildAnnotation('tagging', t, [\n { type: 'TextualBody', value: cat, purpose: 'tagging', format: 'text/plain' satisfies SupportedMediaType, language: bodyLanguage },\n { type: 'TextualBody', value: params.schema.id, purpose: 'classifying', format: 'text/plain' satisfies SupportedMediaType },\n ]);\n }));\n created += fresh.length;\n for (const ann of fresh) {\n const body = (ann as { body?: Array<{ value?: unknown }> }).body;\n const cat = Array.isArray(body) && typeof body[0]?.value === 'string' ? body[0].value : 'unknown';\n byCategory[cat] = (byCategory[cat] ?? 0) + 1;\n }\n onProgress(60, { code: 'creating-tag-annotations', count: created });\n // The unit is the CATEGORY, not the motivation. `tag-annotation` loops\n // over `params.categories`, each walking the whole document from zero,\n // so a single 'tagging' key would have every category overwriting one\n // cursor — and the monotone merge would keep the furthest, which is the\n // right answer for at most one of them and silently skips text for the\n // rest. Same shape as reference's entity types, for the same reason.\n categoryCreated += fresh.length;\n await onChunkComplete(fresh, {\n unit: category,\n cursor: { ...cursor, found: categoryFound, emitted: categoryCreated },\n });\n },\n );\n found += categoryFound;\n completedItems.push({ value: category, foundCount: categoryFound });\n }\n\n onProgress(100, { code: 'complete-created', count: created, kind: 'tag' });\n\n return {\n result: { kind: 'tag-annotation', tagsFound: found, tagsCreated: created, byCategory },\n };\n}\n\n/**\n * Output bound (PDF-GENERATION P5), symmetric with #1124's extraction budget\n * and deliberately the SAME threshold: an artifact larger than what extraction\n * accepts would be a resource our own Smelter declines as 'too-large'. One\n * judgment, two enforcement points. A runaway generation fails loudly\n * (job:fail); it never uploads.\n */\nexport function assertWithinOutputBudget(byteLength: number): void {\n if (!withinByteBudget(byteLength)) {\n throw new Error(\n `Generated artifact exceeds the output byte budget: ${byteLength} bytes > ${MAX_PDF_BYTES}. Refusing a runaway generation.`,\n );\n }\n}\n\nexport async function processGenerationJob(\n inferenceClient: InferenceClient,\n params: GenerationJobParams,\n onProgress: OnProgress,\n logger: Logger,\n): Promise<{ content: Uint8Array; title: string; format: SupportedMediaType; citations: GenerationCitation[]; truncated: boolean }> {\n // Refuse any requested media type the registry doesn't mark `generatable` —\n // loudly (the throw propagates as job:fail), never a silent markdown fallback\n // under a mislabeled format. The gate reads the registry capability\n // (PDF-GENERATION P1), not a local table. Validate before the LLM call.\n const outputMediaType: SupportedMediaType = params.outputMediaType ?? 'text/markdown';\n if (!GENERATABLE_MEDIA_TYPES.includes(outputMediaType)) {\n throw new Error(\n `Unsupported outputMediaType for generation: ${outputMediaType}. Generation produces ${GENERATABLE_MEDIA_TYPES.join(' or ')}.`,\n );\n }\n\n const title = params.title ?? 'Untitled';\n const entityTypes = (params.entityTypes ?? []).map(String);\n\n // PDF path (PDF-GENERATION P3): the model authors Typst; the worker's pinned\n // binary compiles it, with the legible compile errors fed back for a bounded\n // number of repairs. Citations on PDFs need page geometry, not text offsets —\n // until the citation branch (P4) provides it, `cite` fails fast and loudly\n // rather than minting selectors that would render nothing.\n if (outputMediaType === 'application/pdf') {\n onProgress(5, { code: 'generating-resource' });\n\n // Under `cite`, [[<id>]] tokens are stripped from the SOURCE before every\n // compile — they must never render into the artifact. The citations carry\n // the claim text; the worker re-anchors it by page geometry after\n // extraction (P4). Offsets in these citations index the Typst source and\n // are NOT used for PDF anchoring.\n const validIds = params.cite === true ? collectContextResourceIds(params.context) : null;\n\n let generated = await generateResourceFromTopic(\n title, entityTypes, inferenceClient, logger,\n params.prompt, params.language, params.context, params.temperature,\n params.maxTokens, params.sourceLanguage, outputMediaType,\n params.task, params.structure, params.cite,\n );\n let source = generated.content;\n let citations: GenerationCitation[] = [];\n if (validIds) {\n const resolved = resolveCitationTokens(generated.content, validIds, logger);\n source = resolved.content;\n citations = resolved.citations;\n }\n let compiled = compileTypst(source);\n let repairs = 0;\n while ('error' in compiled) {\n // A truncated source that fails to compile is cut off, not wrong —\n // every repair regenerates under the same ceiling and cannot restore\n // content that was never generated. Fail immediately with the actual\n // cause instead of burning the repair budget and blaming the compiler\n // (GENERATE-FROM-RESOURCE P3a).\n if (generated.truncated) {\n throw new Error(\n `Generation stopped at the maxTokens ceiling (${params.maxTokens ?? DEFAULT_MAX_TOKENS} tokens) and the cut-off Typst source does not compile — repair cannot help; raise maxTokens. Compile error: ${compiled.error}`,\n );\n }\n if (repairs >= MAX_COMPILE_REPAIRS) {\n throw new Error(\n `Typst compilation failed after ${MAX_COMPILE_REPAIRS} repair attempts: ${compiled.error}`,\n );\n }\n repairs++;\n logger.warn('Typst compile failed — feeding the error back for repair', {\n attempt: repairs,\n error: compiled.error.slice(0, 500),\n });\n generated = await generateResourceFromTopic(\n title, entityTypes, inferenceClient, logger,\n params.prompt, params.language, params.context, params.temperature,\n params.maxTokens, params.sourceLanguage, outputMediaType,\n params.task, params.structure, params.cite,\n { source, error: compiled.error },\n );\n if (validIds) {\n const resolved = resolveCitationTokens(generated.content, validIds, logger);\n source = resolved.content;\n citations = resolved.citations;\n } else {\n source = generated.content;\n }\n compiled = compileTypst(source);\n }\n\n assertWithinOutputBudget(compiled.pdf.byteLength);\n onProgress(95, { code: 'creating-resource' });\n // The producer owns terminality (GENERATE-FROM-RESOURCE P1/D1): without\n // this, the client's last frame is forever the 95% payload. Generic by\n // design — the outcome (name + link) travels on job:complete (D8).\n // `truncated` rides both surfaces (P3a/D6): truncation that lands at a\n // syntactic boundary still compiles, and the artifact is still cut off.\n onProgress(100, { code: 'complete-generated', truncated: generated.truncated });\n\n return {\n content: compiled.pdf,\n title,\n format: outputMediaType,\n citations,\n truncated: generated.truncated,\n };\n }\n\n // Generation has exactly two observable transitions: the LLM call starting\n // ('generating') and content finalized / creation beginning ('creating').\n // There is no fetch — context arrives pre-gathered in params. Percentages\n // approximate the share of expected wall-clock complete at each transition\n // (a single atomic LLM call has no measurable progress, and inference\n // dominates the job): its start is ~5, its end ~95.\n onProgress(5, { code: 'generating-resource' });\n\n const generated = await generateResourceFromTopic(\n title,\n entityTypes,\n inferenceClient,\n logger,\n params.prompt,\n params.language,\n params.context,\n params.temperature,\n params.maxTokens,\n params.sourceLanguage,\n outputMediaType,\n params.task,\n params.structure,\n params.cite,\n );\n\n // Under `cite`, the model emitted [[<id>]] transport tokens — resolve them:\n // validate against the ids the context actually contained, strip from the\n // stored content, and carry claim-span citations for the worker to mint.\n // When cite is off, bracketed text is legitimate content — leave it alone.\n let content = generated.content;\n let citations: GenerationCitation[] = [];\n if (params.cite === true) {\n const resolved = resolveCitationTokens(content, collectContextResourceIds(params.context), logger);\n content = resolved.content;\n citations = resolved.citations;\n }\n\n onProgress(95, { code: 'creating-resource' });\n\n // The artifact is bytes; text is an encoding of them. One shape for every\n // output media type, so a string can never travel mislabeled as a binary\n // format (PDF-GENERATION P1). Citation offsets index the decoded text.\n const artifact = new TextEncoder().encode(content);\n assertWithinOutputBudget(artifact.byteLength);\n\n // The producer owns terminality (GENERATE-FROM-RESOURCE P1/D1): without\n // this, the client's last frame is forever the 95% payload. Generic by\n // design — the outcome (name + link) travels on job:complete (D8).\n // `truncated` rides both surfaces (P3a/D6): the event is the frame the\n // client renders, and the worker states it in the job's result once the\n // resource exists.\n onProgress(100, { code: 'complete-generated', truncated: generated.truncated });\n\n return {\n content: artifact,\n title,\n format: outputMediaType,\n citations,\n truncated: generated.truncated,\n };\n}\n","/**\n * Job Claim Adapter — worker-side job lifecycle glue on top of a\n * shared bus.\n *\n * Replaces the old `WorkerStateUnit`, which owned its own actor and\n * duplicated the SSE connection that `SemiontClient` already held.\n * Workers construct a `SemiontSession` normally (one actor, one\n * SSE connection) and use this adapter to attach job-claim behaviour\n * on top of the session's bus. It does **not** own the bus, has no HTTP\n * concerns, and has no modal state.\n *\n * THE MODEL — a worker asks the queue at every moment it becomes idle,\n * and never otherwise. `job:claim` carries this worker's types; the\n * dispatcher answers with the next pending job of those types, atomically\n * claimed, or declines. Queue state is the truth; no message carries\n * correctness. The idle moments:\n *\n * - start, once the transport is open;\n * - settle — `completeJob` / `failJob` — immediately, with no timer;\n * - a matching `job:queued` while parked;\n * - reconnect — every `state$` edge into `open` after the first.\n *\n * `job:queued` is a WAKE-UP with no memory. While parked it triggers a\n * pull; while a claim is in flight it sets a dirty bit that earns exactly\n * one more pull before parking, so a wake-up cannot be lost in that window;\n * while a job is held it is ignored, because the settle pulls. One claim\n * in flight at a time — under one-job-at-a-time processing \"drain\" is one\n * claim per idle moment and one at settle, never a loop of claims while a\n * job is held. The type filter on the wake-up is a PRE-FILTER on\n * information the announcement already carries, so a worker that cannot\n * run the announced type does not spend a round trip to be declined; the\n * claim's `types` argument is the rule.\n *\n * What the dispatcher's decline codes mean here (`BusRequestError.code`,\n * promoted from the reply's `CommandError.code`): `bus.none-pending` is\n * the quiet park — nothing to do until a wake-up, nothing emitted. Every\n * other refusal goes out on `refused$` for the runtime to judge;\n * `bus.unauthorized` is the one it exits on, because a credential that\n * can never claim has nothing to do here and the launcher's preflight\n * names the repair.\n *\n * The queue drivers' 30 s re-announce tick survives as INSURANCE against a\n * lost wake-up on an idle worker — never as dispatch. A healthy stack never\n * sees it act.\n *\n * The `bus` parameter is typed against the small `BusRequestPrimitive`\n * interface (from `@semiont/core`) so the adapter is transport-neutral.\n * HTTP workers pass `(session.client.transport as HttpTransport).actor`;\n * an in-process worker could pass a shim wrapping `client.bus`.\n */\n\nimport { BehaviorSubject, Observable, Subject, type Subscription } from 'rxjs';\nimport { BusRequestError, busRequest } from '@semiont/core';\nimport type { BusRequestErrorCode, EventMap, JobId, JobType, ResourceId, UnitCursor } from '@semiont/core';\nimport type { BusRequestPrimitive } from '@semiont/core';\n\n/**\n * The bus operation the claim path AWAITS (census declaration — see\n * `WORKER_AWAITED_OPERATIONS` in worker-runtime.ts). The `satisfies` at the\n * call site keeps this alias and the actual operation from drifting.\n */\nexport type JobClaimAwaits = 'job:claim';\n\n/** The job a `job:claimed` reply carries, running under this worker: the spec's `JobRunning`. */\ntype ClaimedJob = EventMap['job:claimed']['response'];\n\n/**\n * The claimed job as the worker holds it: the fields of the claimed record the\n * worker reads, each with the type the spec gives it there.\n */\nexport interface ActiveJob {\n jobId: JobId;\n type: JobType;\n resourceId: ResourceId;\n params: ClaimedJob['params'];\n /**\n * Entity-type units earlier failed attempts fully emitted\n * (ABANDONED-INFERENCE P2 checkpointed resume) — carried on the claimed\n * record's metadata by `failJob`. The worker skips them, so a retry\n * neither redoes nor duplicates completed work. Empty on first attempts.\n */\n completedUnits: string[];\n /**\n * How far each UNFINISHED unit got on an earlier attempt\n * (CHUNK-GRAIN-RESUME P2) — the grain `completedUnits` cannot express, and\n * the only checkpoint a one-unit job can produce before it finishes. Empty\n * on first attempts, and never overlapping `completedUnits`: a unit is\n * either finished or partway, never both.\n */\n unitCursors: Record<string, UnitCursor>;\n /**\n * The claimed record's retry budget, carried so the worker can report\n * `willRetry` on `job:fail` (JOB-RESTART-SAFETY P5). It is the same budget\n * the queue re-reads at `failJob`, and only `failJob` changes it, so the\n * two evaluations of `willRetryAfter` agree.\n */\n retryCount: number;\n maxRetries: number;\n}\n\nexport interface JobClaimAdapterOptions {\n /** Shared bus (typically the session's HTTP actor or an in-process bus shim). */\n bus: BusRequestPrimitive;\n /**\n * Job types this worker can process — the claim's `types` argument, and\n * the pre-filter on `job:queued` wake-ups. Empty array = accept any.\n */\n jobTypes: string[];\n}\n\n/**\n * A claim the dispatcher refused for a reason other than \"nothing pending\".\n *\n * `code` is the `BusRequestError` code the reply was promoted to, or `null`\n * when the failure was local — a thrown non-bus error — never a manufactured\n * bus code. `bus.none-pending` never appears here: it is the quiet park, and\n * emitting it would make an empty queue look like a fault.\n */\nexport interface ClaimRefusal {\n code: BusRequestErrorCode | null;\n message: string;\n}\n\n/**\n * Point-in-time liveness snapshot (WORKER-LIVENESS.md P1). The adapter\n * is the only component that sees every wake-up, claim, and finish,\n * so its snapshot is what `/health` reports and the stall watchdog reads.\n *\n * `lastQueuedEventAt` is any `job:queued` received, matching or not. It\n * proves the transport delivered a broadcast, but on an idle stack with an\n * empty queue it stands still by design — no announcement is owed — so a\n * still stamp alone is not a transport fault; transport liveness proper is\n * the actor's SSE heartbeat. `lastActivityAt` (claim, progress emission, or\n * finish) is processing liveness; a job stuck mid-inference stops advancing\n * it, and that is what the watchdog reads.\n */\nexport interface WorkerVitals {\n lastQueuedEventAt: string | null;\n lastClaimAt: string | null;\n /** Last completion or failure — a failing-but-moving worker is alive. */\n lastFinishedAt: string | null;\n lastActivityAt: string | null;\n activeJob: { jobId: string; type: string; since: string } | null;\n jobsCompleted: number;\n}\n\nexport interface JobClaimAdapter {\n /** Currently-claimed job, or null when idle. */\n readonly activeJob$: Observable<ActiveJob | null>;\n /** True while a claim is in flight or a job is being processed. */\n readonly isProcessing$: Observable<boolean>;\n /** Monotonically-incrementing count of successfully-completed jobs. */\n readonly jobsCompleted$: Observable<number>;\n /** Stream of job failures reported through `failJob`. */\n readonly errors$: Observable<{ jobId: string; error: string }>;\n /**\n * Claims the dispatcher refused for a reason the runtime must judge.\n * `bus.unauthorized` means this credential can never claim; the runtime\n * exits on it. Anything else is logged and the worker stays parked until\n * the next wake-up. See `ClaimRefusal`.\n */\n readonly refused$: Observable<ClaimRefusal>;\n\n /**\n * Begin pulling: one claim now (once the transport is open), then on every\n * settle, matching wake-up, and reconnect. Idempotent — calling `start()`\n * twice is a no-op.\n */\n start(): void;\n\n /** Stop pulling. Does not cancel an in-flight job. */\n stop(): void;\n\n /** Signal successful completion of `activeJob$`. Pulls the next job. */\n completeJob(): void;\n\n /** Signal failure of `activeJob$`. Emits on `errors$`, then pulls the next job. */\n failJob(jobId: string, error: string): void;\n\n /** Liveness snapshot for `/health` and the stall watchdog. */\n vitals(): WorkerVitals;\n\n /**\n * Record processing activity. The worker process calls this on every\n * progress emission so a long multi-call job keeps proving liveness\n * between inference calls.\n */\n touchActivity(): void;\n\n /** Release observables. Does not dispose the shared bus. */\n dispose(): void;\n}\n\ntype ClaimOutcome = { job: ActiveJob } | { declined: true } | { refused: ClaimRefusal };\n\n/**\n * Attach job-claim behaviour to a shared bus.\n */\nexport function createJobClaimAdapter(options: JobClaimAdapterOptions): JobClaimAdapter {\n const { bus, jobTypes } = options;\n\n const activeJob$ = new BehaviorSubject<ActiveJob | null>(null);\n const isProcessing$ = new BehaviorSubject<boolean>(false);\n const jobsCompleted$ = new BehaviorSubject<number>(0);\n const errors$ = new Subject<{ jobId: string; error: string }>();\n const refused$ = new Subject<ClaimRefusal>();\n\n let subscriptions: Subscription[] = [];\n let started = false;\n // The loop's two bits: one claim in flight at a time, and a wake-up that\n // arrived during it — honoured with exactly one more claim before parking.\n let claimInFlight = false;\n let wakePending = false;\n\n // Vitals clock (epoch ms internally; rendered as ISO in snapshots).\n let lastQueuedEventAt: number | null = null;\n let lastClaimAt: number | null = null;\n let lastFinishedAt: number | null = null;\n let lastActivityAt: number | null = null;\n let activeSince: number | null = null;\n const iso = (t: number | null): string | null => (t === null ? null : new Date(t).toISOString());\n\n const claimNext = async (): Promise<ClaimOutcome> => {\n // Ask for the next pending job of this worker's types (JOB-QUEUE-DRIVER\n // P2). Same request/reply path as the SDK: busRequest mints the\n // correlationId, matches the job:claimed / job:claim-failed reply by it,\n // and returns the reply's `response` — the claimed job, as the spec types\n // it. A reply is not checked on receipt: the dispatcher states it, and its\n // conformance suite holds every frame it sends to the channel's schema.\n let claimed: ClaimedJob;\n try {\n claimed = await busRequest(bus, 'job:claim' satisfies JobClaimAwaits, { types: jobTypes }, 10_000);\n } catch (error) {\n // The reply's verdict, promoted to the client vocabulary by core. A\n // decline is the expected quiet outcome; everything else is the\n // runtime's to judge. A non-bus throw is local and says so (`null`).\n if (error instanceof BusRequestError) {\n if (error.code === 'bus.none-pending') return { declined: true };\n return { refused: { code: error.code, message: error.message } };\n }\n return { refused: { code: null, message: error instanceof Error ? error.message : String(error) } };\n }\n\n const { metadata, params } = claimed;\n return {\n job: {\n jobId: metadata.id,\n type: metadata.type,\n resourceId: params.resourceId,\n params,\n // Both appear on the record once an attempt has checkpointed, and a\n // finished unit has no cursor: the dispatcher drops it at the merge.\n completedUnits: metadata.completedUnits ?? [],\n unitCursors: metadata.unitCursors ?? {},\n retryCount: metadata.retryCount,\n maxRetries: metadata.maxRetries,\n },\n };\n };\n\n /** One idle moment: ask once, or remember that we were asked to. */\n const pull = (): void => {\n if (!started) return;\n // Holding a job: the settle pulls. Nothing to remember — the queue's\n // state, not this wake-up, is what the settle pull reads.\n if (activeJob$.getValue() !== null) return;\n if (claimInFlight) {\n wakePending = true;\n return;\n }\n claimInFlight = true;\n wakePending = false;\n isProcessing$.next(true);\n void claimNext().then((outcome) => {\n claimInFlight = false;\n if ('job' in outcome) {\n const now = Date.now();\n lastClaimAt = now;\n lastActivityAt = now;\n activeSince = now;\n // A wake-up that arrived mid-claim is moot: the settle pulls.\n wakePending = false;\n activeJob$.next(outcome.job);\n return;\n }\n if ('refused' in outcome) refused$.next(outcome.refused);\n isProcessing$.next(false);\n if (wakePending) {\n wakePending = false;\n pull();\n }\n });\n };\n\n return {\n activeJob$: activeJob$.asObservable(),\n isProcessing$: isProcessing$.asObservable(),\n jobsCompleted$: jobsCompleted$.asObservable(),\n errors$: errors$.asObservable(),\n refused$: refused$.asObservable(),\n\n start: () => {\n if (started) return;\n started = true;\n\n // `job:queued` is declared twice over, and both halves are load-bearing:\n // as a bridged broadcast so the frame exists on the wire at all, and in\n // `WORKER_CONSUMED_BROADCASTS` so this process's transport carries it.\n // The worker subscribes its manifest, not `BRIDGED_CHANNELS`.\n subscriptions.push(\n bus.stream('job:queued').subscribe((event) => {\n // Every announcement received — matching or not — is stamped before\n // any filtering.\n lastQueuedEventAt = Date.now();\n // The pre-filter: the claim's `types` is the rule; this saves the\n // round trip when the announced type is one this worker cannot run.\n if (jobTypes.length > 0 && !jobTypes.includes(event.jobType)) return;\n pull();\n }),\n );\n\n // Reconnect is an edge into `open` after the first observation. The\n // first observation decides whether start pulls now or waits for the\n // transport to open — a claim on a closed transport would only be\n // refused locally.\n let observed = false;\n let wasOpen = false;\n subscriptions.push(\n bus.state$.subscribe((state) => {\n const open = state === 'open';\n if (observed && open && !wasOpen) pull();\n observed = true;\n wasOpen = open;\n }),\n );\n if (wasOpen) pull();\n },\n\n stop: () => {\n for (const s of subscriptions) s.unsubscribe();\n subscriptions = [];\n started = false;\n },\n\n completeJob: () => {\n const now = Date.now();\n lastFinishedAt = now;\n lastActivityAt = now;\n activeSince = null;\n activeJob$.next(null);\n isProcessing$.next(false);\n jobsCompleted$.next(jobsCompleted$.getValue() + 1);\n pull();\n },\n\n failJob: (jid: string, error: string) => {\n const now = Date.now();\n lastFinishedAt = now;\n lastActivityAt = now;\n activeSince = null;\n activeJob$.next(null);\n isProcessing$.next(false);\n errors$.next({ jobId: jid, error });\n pull();\n },\n\n vitals: () => {\n const active = activeJob$.getValue();\n return {\n lastQueuedEventAt: iso(lastQueuedEventAt),\n lastClaimAt: iso(lastClaimAt),\n lastFinishedAt: iso(lastFinishedAt),\n lastActivityAt: iso(lastActivityAt),\n activeJob: active && activeSince !== null\n ? { jobId: active.jobId, type: active.type, since: iso(activeSince)! }\n : null,\n jobsCompleted: jobsCompleted$.getValue(),\n };\n },\n\n touchActivity: () => {\n lastActivityAt = Date.now();\n },\n\n dispose: () => {\n for (const s of subscriptions) s.unsubscribe();\n subscriptions = [];\n started = false;\n activeJob$.complete();\n isProcessing$.complete();\n jobsCompleted$.complete();\n errors$.complete();\n refused$.complete();\n },\n };\n}\n","/**\n * Worker Runtime — the importable half of the worker host.\n *\n * `worker-main.ts` is a process entrypoint (config at module scope,\n * `main()` at import) and therefore untestable by construction; everything\n * a unit test needs to reach lives here instead, fully parameterized — no\n * module-scope env reads, no side effects at import.\n *\n * The load-bearing contract this module owns (and the reason it was\n * extracted): a worker's stamped identity is the DID the\n * `/api/tokens/agent` exchange MINTED for it, carried verbatim — never\n * re-derived from the URL the worker happens to dial. One logical agent\n * previously got two DIDs that way (.plans/bugs/agent-did-host-skew.md).\n */\n\nimport type { EventMap } from '@semiont/core';\nimport { startWorkerProcess } from './worker-process';\nimport type { MarkCommitAwaits, DescriptorReadAwaits, DurabilityProbeAwaits } from './worker-process';\nimport type { WorkerVitals, JobClaimAwaits } from './job-claim-adapter';\nimport type { ConsultAnchoredTextAwaits } from './workers/detection/prepare-detection';\nimport { answerLimitsRequests, type InferenceClient, type LimitsSource } from '@semiont/inference';\nimport { hostname } from 'os';\nimport {\n replyChannelsFor,\n didToAgent,\n baseUrl,\n retryWithBackoff,\n isTransientFetchError,\n STARTUP_FETCH_RETRY,\n type BusOperationKey,\n type RetryPolicy,\n type components,\n type Logger,\n type AccessToken,\n} from '@semiont/core';\nimport {\n InMemorySessionStorage,\n SemiontClient,\n SemiontSession,\n kbGatewayUrl,\n setStoredSession,\n type HttpEndpoint,\n type KbTarget,\n} from '@semiont/sdk';\nimport { HttpContentTransport, HttpTransport } from '@semiont/http-transport';\nimport type { ContentReads } from '@semiont/content';\nimport { BehaviorSubject } from 'rxjs';\nimport { serviceAccountToken } from '@semiont/core';\nimport type { ServiceAccountCredential } from '@semiont/core';\n\ntype Agent = components['schemas']['Agent'];\n\n/** Shape of each resolved worker inference entry under `_metadata.workers`. */\nexport type ResolvedInference = {\n type: 'anthropic' | 'ollama';\n model: string;\n apiKey?: string;\n endpoint?: string;\n baseURL?: string;\n};\n\n/** One agent identity: an inference engine and the job types it serves. */\nexport interface AgentGroup {\n inference: ResolvedInference;\n jobTypes: string[];\n client: InferenceClient;\n}\n\nexport interface WorkerRuntimeOptions {\n group: AgentGroup;\n /** The gateway URL this worker dials — connection topology ONLY, never identity. */\n gatewayBaseUrl: string;\n /** This process's own account at the issuer, and the bearer the byte reads\n * below show the Archivist. */\n credential: ServiceAccountCredential;\n /**\n * The resource's bytes, for detection's extraction seam. Built by the\n * entrypoint (`worker-main`) rather than here, so a worker with no\n * Archivist configured refuses at boot instead of failing every job\n * (SINGLE-KB-MOUNT P4).\n */\n contentReads: ContentReads;\n logger: Logger;\n /**\n * The clients whose limits this agent reports on `job:limits-requested`:\n * every group's, for the one agent that answers for its pool, and none for\n * the rest. The gateway delivers only the first reply to a request.\n */\n reportsLimitsOf: readonly LimitsSource[];\n}\n\n/** Per-agent liveness: the adapter's snapshot plus this agent's identity. */\nexport interface AgentVitals extends WorkerVitals {\n provider: string;\n model: string;\n did: string;\n jobTypes: string[];\n}\n\nexport interface AgentWorkerHandle {\n session: SemiontSession;\n vitals(): AgentVitals;\n dispose(): Promise<void>;\n}\n\nexport interface WorkerHealthPayload {\n status: 'ok';\n agents: number;\n workers: AgentVitals[];\n}\n\n/**\n * The `/health` body (WORKER-LIVENESS.md P1). Additive: existing\n * consumers (image HEALTHCHECK, compose `service_healthy`, `semiont start`)\n * keep reading `status`/`agents`; the per-agent vitals expose\n * claim-loop progress so a stalled worker is *visible*, not just alive.\n */\nexport function buildHealthPayload(workers: ReadonlyArray<{ vitals(): AgentVitals }>): WorkerHealthPayload {\n return {\n status: 'ok',\n agents: workers.length,\n workers: workers.map((w) => w.vitals()),\n };\n}\n\n/**\n * Stall watchdog (WORKER-LIVENESS.md P3) — the fail-fast line behind the\n * inference timeout. There is no poll timer to heartbeat — the worker pulls\n * when idle, and a parked idle worker is not a stall; the honest stall\n * signal is *processing without activity*: an agent holding a claimed job\n * whose `lastActivityAt` (claim / progress / finish) has stopped advancing\n * is wedged — the adapter defers every wake-up while a job is held and\n * pulls at settle, so a wedged agent never settles and never recovers on\n * its own. Silent hang → loud crash → whatever\n * restart policy the deployment chose.\n *\n * Thresholds are fixed by design (no env knobs) and deliberately\n * layered: inference timeout (10 min, P2) fires first; this watchdog\n * (15 min) catches wedges where the loop still turns but activity has\n * stopped; the gateway's dead-worker janitor (30 min) re-queues the job\n * regardless.\n *\n * The layering matters because this watchdog has a hard limit: it is an\n * IN-PROCESS timer, so it cannot fire while the event loop itself is\n * blocked — the exact condition a blocked loop creates\n * (JOB-RESTART-SAFETY P7, the 2026-09-03 finalization hang: 18 min silent,\n * this watchdog never fired, an empty /health confirming the loop was\n * wedged). The unbounded emit that caused that specific hang is now bounded\n * at the transport (`EMIT_TIMEOUT_MS`), so the loop errors instead of\n * blocking; but for any future blocked-loop bug the ONLY backstop is the\n * out-of-process one — the dispatcher's sweep, which fails a running job\n * whose worker has gone silent (docs/protocol/JOBS.md). A liveness guarantee a\n * blocked loop defeats is not one; the sweep is the guarantee.\n */\nexport const STALL_THRESHOLD_MS = 15 * 60_000;\nexport const STALL_CHECK_INTERVAL_MS = 60_000;\n\nexport interface StallWatchdogOptions {\n workers: ReadonlyArray<{ vitals(): AgentVitals }>;\n logger: Logger;\n /** Test seam; defaults to process.exit. */\n exit?: (code: number) => void;\n}\n\nexport function startStallWatchdog(opts: StallWatchdogOptions): { dispose(): void } {\n const { workers, logger, exit = (code: number) => process.exit(code) } = opts;\n\n const timer = setInterval(() => {\n const now = Date.now();\n for (const worker of workers) {\n const v = worker.vitals();\n if (!v.activeJob || !v.lastActivityAt) continue;\n\n const silentForMs = now - Date.parse(v.lastActivityAt);\n if (silentForMs <= STALL_THRESHOLD_MS) continue;\n\n logger.error('Worker stalled — exiting for restart', {\n provider: v.provider,\n model: v.model,\n did: v.did,\n jobId: v.activeJob.jobId,\n jobType: v.activeJob.type,\n processingSince: v.activeJob.since,\n lastActivityAt: v.lastActivityAt,\n silentForMs,\n thresholdMs: STALL_THRESHOLD_MS,\n });\n clearInterval(timer);\n exit(1);\n return;\n }\n }, STALL_CHECK_INTERVAL_MS);\n timer.unref?.();\n\n return { dispose: () => clearInterval(timer) };\n}\n\n/**\n * The bus operations a worker process ever AWAITS a reply to. Reply channels\n * are global fan-out on the gateway, so a full `BRIDGED_CHANNELS`\n * subscription made every worker receive every other client's reply traffic\n * — measured at ~85 multi-MB `browse:annotations-result` frames/min during\n * the 2026-09-03 worker OOM, all parsed and dropped by cid filtering. The\n * worker subscribes exactly its own operations' reply channels instead.\n *\n * This list restates a fact the code owns (which operations worker code\n * paths call `busRequest` on); its gate is the build-time census below\n * (`workerAwaitCensus`): every awaiting site declares its operation next to\n * the call, and an operation awaited but missing here fails COMPILATION with\n * the operation named. `busRequest`'s `isSubscribed` probe remains the\n * runtime backstop for an await nobody declared — a loud `bus.unsubscribed`\n * at first use, never a silent 30 s timeout.\n * (`job:queued` is not here: it is a broadcast, not an awaited reply. The\n * broadcasts a worker consumes are declared in `WORKER_CONSUMED_BROADCASTS`\n * below, and `WORKER_CHANNELS` is the union.)\n */\nexport const WORKER_AWAITED_OPERATIONS = [\n 'job:claim',\n 'browse:resource-requested',\n // Canonical geometry for a geometry-bearing detection: the consult behind\n // `ConsultAnchoredText` (SMELTER-OWNS-OCR P2). Its omission broke every\n // PDF detection job at the transport probe\n // (.plans/WORKER-ANCHORED-TEXT-CHANNEL.md); the census below now fails the\n // BUILD when this list and the declared awaits drift.\n 'browse:anchored-text-requested',\n // Durability acknowledgement for a unit's annotations (JOB-RESTART-SAFETY\n // P6). The worker AWAITS this one — a unit may not advance until its\n // annotations are in the event log — so its replies must be in the narrow\n // channel set or every commit fails fast with `bus.unsubscribed`.\n 'mark:commit',\n // The durability probe for a commit whose acknowledgement never routed\n // (COMMIT-ACK-FALSE-FAILURE F1). SINGULAR by design: the annotation LIST\n // channel is the multi-MB fan-out this narrowing exists to keep out, and a\n // rare error path is no reason to let it back in.\n 'browse:annotation-requested',\n] as const satisfies readonly BusOperationKey[];\n\n/**\n * The broadcasts a worker CONSUMES — announcements nobody replies to, which\n * therefore derive from no operation.\n *\n * One home, because the alternative was proven: these lived as `addChannels`\n * calls beside their consumers, so the worker's complete set existed nowhere\n * and a widening could be deleted without any list getting shorter. That is\n * the 2026-09-16 outage — every worker idle on a `job:queued` its transport\n * would never carry, `lastQueuedEventAt: null`, nothing thrown and nothing\n * logged.\n *\n * An entry here must have a consumer and a consumer must have an entry; the\n * census beside this file asserts both directions.\n */\nexport const WORKER_CONSUMED_BROADCASTS = [\n // The queue announcement the claim adapter races for.\n 'job:queued',\n // Cooperative cancellation of the ACTIVE job (JOB-RESTART-SAFETY P4).\n 'job:cancel-requested',\n] as const satisfies readonly (keyof EventMap)[];\n\n/**\n * The requests a worker ANSWERS. It holds the inference credentials, so it is\n * the one service that can discover its models' limits from their providers.\n * One agent in a pool answers for all of them (`reportsLimitsOf`): only its\n * transport subscribes these, so no other agent receives a request it would\n * drop.\n */\nexport const WORKER_ANSWERED_OPERATIONS = [\n 'job:limits-requested',\n] as const satisfies readonly BusOperationKey[];\n\n/**\n * The global SSE channel set for a worker's transport: the whole manifest,\n * stated once and passed at construction. Nothing widens it afterwards.\n */\n// `replyChannelsFor` already returns `EventName[]`; annotating this\n// `readonly string[]` threw that proof away and was the only reason a\n// transport's channel roster was ever wider than the registry.\nexport const WORKER_CHANNELS: readonly (keyof EventMap)[] = [\n ...replyChannelsFor(WORKER_AWAITED_OPERATIONS),\n ...WORKER_CONSUMED_BROADCASTS,\n];\n\n/**\n * The build-time census gate (WORKER-ANCHORED-TEXT-CHANNEL F2).\n *\n * `WORKER_AWAITED_OPERATIONS` restates a fact the code owns — which\n * operations worker paths call `busRequest` on — and one of those calls\n * hides behind an injected seam (`ConsultAnchoredText` → the SDK), where no\n * grep and no runtime probe-before-shipping can see it. So every awaiting\n * site DECLARES its operation next to the call (the `*Awaits` aliases), the\n * declarations are assembled here, and this constant compiles ONLY when the\n * list and the declarations agree in BOTH directions. Drift fails the build\n * with the drifted operation named in the type error — at build time, not at\n * the first live job. `busRequest`'s `bus.unsubscribed` probe remains the\n * runtime backstop for an await nobody declared.\n */\ntype DeclaredWorkerAwaits =\n | JobClaimAwaits // job-claim-adapter.ts — claiming an announced job\n | DescriptorReadAwaits // worker-process.ts — the resource descriptor read\n | MarkCommitAwaits // worker-process.ts — the durability ack (JOB-RESTART-SAFETY P6)\n | DurabilityProbeAwaits // worker-process.ts — did the batch land? (COMMIT-ACK-FALSE-FAILURE F1)\n | ConsultAnchoredTextAwaits; // prepare-detection.ts — canonical geometry (SMELTER-OWNS-OCR P2)\n\ntype WorkerAwaitCensusDrift =\n | Exclude<DeclaredWorkerAwaits, (typeof WORKER_AWAITED_OPERATIONS)[number]>\n | Exclude<(typeof WORKER_AWAITED_OPERATIONS)[number], DeclaredWorkerAwaits>;\n\nexport const workerAwaitCensus: [WorkerAwaitCensusDrift] extends [never]\n ? 'in-census'\n : WorkerAwaitCensusDrift = 'in-census';\n\nexport function parseGatewayUrl(url: string): { protocol: 'http' | 'https'; host: string; port: number } {\n const parsed = new URL(url);\n const protocol = (parsed.protocol.replace(':', '') === 'https' ? 'https' : 'http') as 'http' | 'https';\n const host = parsed.hostname;\n const port = parsed.port\n ? Number(parsed.port)\n : protocol === 'https' ? 443 : 80;\n return { protocol, host, port };\n}\n\n/**\n * Exchange this process's issuer token for an agent JWT and its canonical DID.\n * The DID is minted by the gateway (under the KB's own domain) — the caller\n * carries it verbatim.\n *\n * Connection-level failures (`TypeError: fetch failed`) are retried with\n * exponential backoff: the gateway may be mid-restart or the container\n * network still warming up when this process starts, and orchestration\n * runs workers with `--rm` and no restart policy — exiting on the first\n * failed fetch is permanent death. HTTP-level rejections (401 on a bad\n * secret) are NOT retried; the gateway is up and said no.\n */\nexport async function authenticateAgent(opts: {\n gatewayBaseUrl: string;\n credential: ServiceAccountCredential;\n provider: string;\n model: string;\n logger?: Logger;\n retry?: RetryPolicy;\n}): Promise<{ token: string; did: string }> {\n const { gatewayBaseUrl, credential, provider, model, logger, retry = STARTUP_FETCH_RETRY } = opts;\n\n return retryWithBackoff(\n async () => {\n // The process proves who IT is, then asks for the agent identity it wants.\n // One worker holds several of the latter when job types are configured\n // with different models, which is why they are separate exchanges.\n const caller = await serviceAccountToken(credential);\n\n const response = await fetch(`${gatewayBaseUrl}/api/tokens/agent`, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n Authorization: `Bearer ${caller}`,\n },\n body: JSON.stringify({ provider, model }),\n });\n\n if (!response.ok) {\n throw new Error(`Agent authentication failed for ${provider}:${model}: ${response.status} ${response.statusText}`);\n }\n\n return await response.json() as { token: string; did: string };\n },\n isTransientFetchError,\n retry,\n ({ attempt, attempts, delayMs, error }) => {\n logger?.warn('Gateway unreachable, retrying agent authentication', {\n agent: `${provider}:${model}`,\n attempt,\n attempts,\n retryInMs: delayMs,\n error: error instanceof Error ? error.message : String(error),\n });\n },\n );\n}\n\nexport async function startAgentWorker(\n opts: WorkerRuntimeOptions,\n): Promise<AgentWorkerHandle> {\n const { group, gatewayBaseUrl, credential, contentReads, reportsLimitsOf, logger } = opts;\n const { inference } = group;\n\n const { protocol, host, port } = parseGatewayUrl(gatewayBaseUrl);\n const { token: initialToken, did } = await authenticateAgent({\n gatewayBaseUrl,\n credential,\n provider: inference.type,\n model: inference.model,\n logger,\n });\n\n // The exchange minted this worker's canonical DID (under the KB's own\n // domain) and we carry it VERBATIM — never re-derive identity from\n // the URL we happen to dial (`host` is connection topology only). One\n // logical agent previously got two DIDs this way:\n // .plans/bugs/agent-did-host-skew.md.\n const generator: Agent = didToAgent(did);\n\n const kbId = `agent-${inference.type}-${inference.model}-${hostname()}`;\n const endpoint: HttpEndpoint = { kind: 'http', host, port, protocol };\n const kb: KbTarget = {\n id: kbId,\n label: `${inference.type} / ${inference.model} @ ${host}`,\n endpoint,\n };\n const storage = new InMemorySessionStorage();\n // No refresh token: a worker renews by re-authenticating as its service\n // account, not by presenting a refresh grant. The client id and token\n // endpoint are its own, so the stored session names the credential that\n // actually backs it rather than leaving them blank.\n setStoredSession(storage, kbId, {\n access: initialToken,\n refresh: '',\n clientId: credential.clientId,\n tokenEndpoint: credential.issuer,\n });\n\n const token$ = new BehaviorSubject<AccessToken | null>(null);\n let session!: SemiontSession;\n const transport = new HttpTransport({\n baseUrl: baseUrl(kbGatewayUrl(endpoint)),\n token$,\n tokenRefresher: () => session.refresh().then((t) => t ?? null),\n // Only the reply channels this process awaits — not the full bridged\n // set. See WORKER_AWAITED_OPERATIONS. The agent that reports its pool's\n // limits also subscribes the requests it answers.\n channels: reportsLimitsOf.length > 0 ? [...WORKER_CHANNELS, ...WORKER_ANSWERED_OPERATIONS] : WORKER_CHANNELS,\n });\n const content = new HttpContentTransport(transport);\n const client = new SemiontClient(transport, content, transport);\n session = new SemiontSession({\n kb,\n storage,\n client,\n token$,\n refresh: async () => {\n try {\n const { token } = await authenticateAgent({\n gatewayBaseUrl,\n credential,\n provider: inference.type,\n model: inference.model,\n logger,\n });\n return token;\n } catch (err) {\n logger.error('Agent token refresh failed', {\n error: err instanceof Error ? err.message : String(err),\n agent: did,\n });\n return null;\n }\n },\n onError: (err) => {\n logger.error('Session error', { code: err.code, message: err.message, agent: did });\n },\n });\n await session.ready;\n\n const adapter = startWorkerProcess({\n session,\n jobTypes: group.jobTypes,\n inferenceClient: group.client,\n generator,\n // Byte reads for decode-path media only. A geometry-bearing type's text\n // never comes from bytes here — it is CONSULTED from the Smelter's\n // canonical anchored text over the bus (SMELTER-OWNS-OCR P2), and this\n // worker cannot derive even by mistake (READ-VS-EXTRACT P2).\n contentReads,\n logger,\n });\n\n const limitsResponder = reportsLimitsOf.length > 0\n ? answerLimitsRequests(transport, 'job:limits-requested', reportsLimitsOf, logger)\n : undefined;\n\n logger.info('Agent ready', {\n did,\n provider: inference.type,\n model: inference.model,\n jobTypes: group.jobTypes,\n });\n\n return {\n session,\n vitals: () => ({\n provider: inference.type,\n model: inference.model,\n did,\n jobTypes: group.jobTypes,\n ...adapter.vitals(),\n }),\n dispose: async () => {\n limitsResponder?.unsubscribe();\n adapter.dispose();\n await session.dispose();\n },\n };\n}\n"]}