luxray-agent 0.1.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/bin/luxray-agent.ts","../../src/vault/credential-vault.ts","../../src/client/agent-client.ts","../../../streaming/src/errors.ts","../../../streaming/src/config.ts","../../../streaming/src/envelope.ts","../../../streaming/src/kafka.ts","../../../streaming/src/topics.ts","../../src/client/task-stream.ts","../../src/execution/test-job.ts","../../src/execution/task-executor.ts","../../src/execution/exploration-job.ts","../../../../apps/exploration-worker/src/exploration-worker.ts","../../../../apps/exploration-worker/src/artifacts/run-artifacts.ts","../../../../apps/exploration-worker/src/browser/task-browser.ts","../../../../apps/exploration-worker/src/errors.ts","../../../../apps/exploration-worker/src/auth/login.ts","../../../../apps/exploration-worker/src/browser/page-snapshot.ts","../../../../apps/capture-worker/src/index.ts","../../../../apps/capture-worker/src/browser/browser-manager.ts","../../../../apps/capture-worker/src/interceptor/network-interceptor.ts","../../../../apps/capture-worker/src/interceptor/body-resolver.ts","../../../../apps/capture-worker/src/transaction/transaction-correlator.ts","../../../../apps/capture-worker/src/storage/memory-storage.ts","../../../../apps/capture-worker/src/capture-engine.ts","../../../../apps/capture-worker/src/lifecycle/process-lifecycle.ts","../../../../apps/exploration-worker/src/browser/task-capture.ts","../../../../apps/exploration-worker/src/crawl/frontier.ts","../../../../apps/exploration-worker/src/crawl/url-canonicalizer.ts","../../../../apps/exploration-worker/src/crawl/url-policy.ts","../../../../apps/exploration-worker/src/crawl/crawler.ts","../../../../apps/exploration-worker/src/crawl/types.ts","../../src/execution/openapi-spec.ts","../../../normalization/src/url/url-parser.ts","../../../normalization/src/heuristics/patterns.ts","../../../normalization/src/heuristics/static-words.ts","../../../normalization/src/heuristics/segment-classifier.ts","../../../normalization/src/naming/singularize.ts","../../../normalization/src/naming/parameter-namer.ts","../../../normalization/src/query/query-analyzer.ts","../../../normalization/src/engine/endpoint-normalizer.ts","../../../normalization/src/engine/endpoint-aggregator.ts","../../../relationship-discovery/src/resources/resource-identifier.ts","../../../relationship-discovery/src/resources/endpoint-classifier.ts","../../../relationship-discovery/src/identifiers/identifier-extractor.ts","../../../relationship-discovery/src/identifiers/identifier-matcher.ts","../../../relationship-discovery/src/scoring/relationship-scorer.ts","../../../relationship-discovery/src/discovery/relationship-discovery-engine.ts","../../../openapi-generator/src/converters/path-converter.ts","../../../openapi-generator/src/converters/parameter-converter.ts","../../../openapi-generator/src/converters/schema-converter.ts","../../../openapi-generator/src/converters/request-converter.ts","../../../openapi-generator/src/converters/response-converter.ts","../../../openapi-generator/src/converters/link-converter.ts","../../../openapi-generator/src/components/component-registry.ts","../../../openapi-generator/src/serializers/serializer.ts","../../../openapi-generator/src/generator/openapi-generator.ts","../../../schema-inference/src/parser/content-detector.ts","../../../schema-inference/src/parser/media-type-normalizer.ts","../../../schema-inference/src/inferencer/primitive-inferencer.ts","../../../schema-inference/src/merger/schema-merger.ts","../../../schema-inference/src/redactor/sample-redactor.ts","../../../schema-inference/src/inferencer/value-inferencer.ts","../../../schema-inference/src/provenance/confidence-evaluator.ts","../../../schema-inference/src/engine/schema-inference-engine.ts","../../src/client/luxray-api-client.ts"],"sourcesContent":["#!/usr/bin/env node\nimport * as os from 'node:os';\nimport * as readline from 'node:readline/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { CredentialVault, type StoredAgentCredentials } from '../vault/credential-vault.js';\nimport { AgentClient } from '../client/agent-client.js';\nimport { TaskStream } from '../client/task-stream.js';\nimport { streamConfigFromEnv } from '@luxray/streaming';\nimport { TaskExecutor, type JobFinishedInfo } from '../execution/task-executor.js';\nimport {\n createExplorationRunner,\n type ExploreAuthOptions,\n} from '../execution/exploration-job.js';\nimport {\n DEFAULT_EXPLORATION_LIMITS,\n ExplorationWorker,\n type ExplorationOutcome,\n} from '@luxray/exploration-worker';\nimport {\n LuxrayApiError,\n createAgentExplorationTask,\n login,\n registerAgent,\n type FetchLike,\n} from '../client/luxray-api-client.js';\nimport type { LoginResponse, AgentPlatform, AgentArchitecture } from '@luxray/shared';\n\nconst DEFAULT_API_URL = 'http://localhost:4000';\nconst DEFAULT_WS_URL = 'ws://127.0.0.1:4001/v1/agent/socket';\nconst DEFAULT_EXPLORE_MAX_PAGES = DEFAULT_EXPLORATION_LIMITS.maxPages;\nconst DEFAULT_EXPLORE_MAX_DEPTH = DEFAULT_EXPLORATION_LIMITS.maxDepth;\nconst DEFAULT_EXPLORE_JOB_MS = 10 * 60_000;\n/** How long to wait for the server to hand over a task we just created. */\nconst OFFER_WAIT_MS = 90_000;\n\nconst httpFetch: FetchLike = (url, init) => fetch(url, init);\n\nfunction parseArgs(args: string[]): {\n command: string;\n flags: Record<string, string>;\n positionals: string[];\n} {\n const flags: Record<string, string> = {};\n const positionals: string[] = [];\n let command = 'help';\n let commandSet = false;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!arg) continue;\n\n if (!arg.startsWith('-')) {\n if (!commandSet) {\n command = arg;\n commandSet = true;\n } else {\n positionals.push(arg);\n }\n continue;\n }\n\n if (arg.startsWith('--')) {\n const key = arg.slice(2);\n const nextArg = args[i + 1];\n if (nextArg && !nextArg.startsWith('-')) {\n flags[key] = nextArg;\n i++;\n } else {\n flags[key] = 'true';\n }\n } else {\n const key = arg.slice(1);\n const nextArg = args[i + 1];\n if (nextArg && !nextArg.startsWith('-')) {\n flags[key] = nextArg;\n i++;\n } else {\n flags[key] = 'true';\n }\n }\n }\n\n return { command, flags, positionals };\n}\n\nfunction parsePositiveIntFlag(raw: string | undefined, fallback: number, max: number): number {\n if (raw === undefined || raw === '') return fallback;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > max) {\n throw new Error(`Invalid numeric flag value \"${raw}\"; expected an integer between 1 and ${max}.`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeIntFlag(\n raw: string | undefined,\n fallback: number,\n max: number,\n): number {\n if (raw === undefined || raw === '') return fallback;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > max) {\n throw new Error(`Invalid numeric flag value \"${raw}\"; expected an integer between 0 and ${max}.`);\n }\n return parsed;\n}\n\nasync function readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n let content = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => {\n content += chunk;\n });\n process.stdin.on('end', () => {\n resolve(content.trim());\n });\n process.stdin.on('error', reject);\n });\n}\n\n/**\n * Reads a secret from an interactive terminal with echo disabled.\n * Used for passwords and agent tokens so they never land in scrollback.\n */\nfunction readSecret(promptText: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const stdin = process.stdin;\n const stdout = process.stdout;\n\n if (!stdin.isTTY) {\n reject(new Error('Cannot read a secret without a TTY. Use --password-stdin or --token-stdin.'));\n return;\n }\n\n stdout.write(promptText);\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let value = '';\n let settled = false;\n\n const finish = (action: () => void): void => {\n if (settled) return;\n settled = true;\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n stdout.write('\\n');\n action();\n };\n\n const onData = (chunk: string): void => {\n for (const ch of chunk) {\n if (ch === '\\r' || ch === '\\n') {\n finish(() => resolve(value));\n return;\n }\n if (ch === '\\u0003') {\n finish(() => reject(new Error('Cancelled.')));\n return;\n }\n if (ch === '\\u007f' || ch === '\\b') {\n value = value.slice(0, -1);\n continue;\n }\n if (ch >= ' ') {\n value += ch;\n }\n }\n };\n\n stdin.on('data', onData);\n });\n}\n\nfunction printHelp(): void {\n console.log(`\nLuxray Local Exploration Agent CLI\n\nUsage:\n luxray-agent <command> [options]\n\nCommands:\n register Authenticate and register this machine with Luxray\n login Store agent credentials issued elsewhere (dashboard or admin)\n explore Crawl a URL now from the terminal (also records it in Luxray)\n start Start the agent worker and connect to Luxray Cloud\n status Inspect local registration and connectivity status\n logout Clear stored credentials from this machine\n help Show this help message\n\nOptions for 'explore':\n <url> Absolute http(s) URL to crawl (required)\n --max-pages <n> Page limit for this run (default ${DEFAULT_EXPLORE_MAX_PAGES}, max 1000)\n --max-depth <n> Link depth limit (default ${DEFAULT_EXPLORE_MAX_DEPTH}, max 10)\n --allowed-domains <a,b> In-scope hostnames (default: the start URL host)\n --include-subdomains Allow subdomains of the allowed domains\n --out <dir> Artifact root (default ~/.luxray/runs)\n --headed Show the browser window\n --include-secrets Keep auth/cookie headers in artifacts (off by default)\n --max-job-ms <ms> Hard run limit (default ${DEFAULT_EXPLORE_JOB_MS})\n --login-url <url> Sign-in page (default: the start URL)\n --username <name> Site username/email (prompts if omitted)\n --password-stdin Read the site password from stdin\n --auth-timeout-ms <ms> Time allowed for the site to accept the form (default 30000)\n --auth-header <h> Send one request header, e.g. \"Authorization: Bearer ...\"\n --auth-headers-json <json> Add several headers as a JSON object (or @path to a file)\n --auth-cookie <c> Install cookies, e.g. \"session=abc; csrftoken=xyz\"\n --auth-state <file> Reuse a saved session instead of signing in\n --save-auth-state <file> Write the session to a file after signing in\n --no-auth Never send auth; crawl public pages and skip sign-in walls\n --api <url> API base URL (defaults to the stored one)\n --name <name> Task name shown in the dashboard\n --config <path> Path to credentials file\n\nOptions for 'register':\n --workspace <id> Target Workspace ID (defaults to your only workspace)\n --name <name> Agent device name (defaults to hostname)\n --url <url> API base URL (defaults to ${DEFAULT_API_URL})\n --ws <url> WebSocket URL (defaults to ${DEFAULT_WS_URL})\n --email <email> Account email (prompts if omitted)\n --password-stdin Read the account password from stdin\n --token <jwt> Use an existing access token instead of logging in\n (exposes the token in shell history; prefer prompting)\n\nOptions for 'login' (agent credentials issued by the dashboard):\n --agent-id <id> Agent ID (prompts if omitted)\n --workspace <id> Workspace ID (prompts if omitted)\n --token-stdin Read the agent token securely from stdin\n (e.g. echo $TOKEN | luxray-agent login --token-stdin)\n --allow-insecure Allow saving credentials if OS ACLs cannot be applied\n\nOptions for 'start':\n --ws <url> Override WebSocket URL\n --config <path> Path to credentials file\n --max-jobs <n> Concurrent jobs this agent runs (default 1, max 16)\n --max-job-ms <ms> Local execution limit per TEST job (default 120000)\n --max-exploration-ms <ms> Local execution limit per exploration (default ${DEFAULT_EXPLORE_JOB_MS})\n --progress-interval-ms <ms> Minimum gap between progress frames (default 1000)\n --lease-renew-ms <ms> Lease renewal interval (default: one third of the lease)\n --out <dir> Artifact root for dashboard-assigned crawls\n --headed Show the browser window while crawling\n --test-steps <n> Steps in the M3 TEST job (default 5)\n --test-step-delay-ms <ms> Delay per TEST step (default 200)\n\nEnvironment Variables:\n LUXRAY_AGENT_TOKEN Agent authentication token\n LUXRAY_AGENT_ID Agent unique ID\n LUXRAY_WORKSPACE_ID Workspace ID\n LUXRAY_WS_URL WebSocket gateway URL\n LUXRAY_API_URL API base URL\n LUXRAY_EMAIL Account email (non-interactive registration)\n LUXRAY_PASSWORD Account password (discouraged; prefer --password-stdin)\n LUXRAY_SITE_USERNAME Target-site username for --login-url crawls\n LUXRAY_SITE_PASSWORD Target-site password (discouraged; prefer --password-stdin)\n LUXRAY_AUTH_HEADER Request header for protected pages (\"Name: value\")\n LUXRAY_AUTH_COOKIE Cookie header for protected pages (\"name=value; ...\")\n LUXRAY_CREDENTIALS_PATH Custom credentials file location\n`);\n}\n\nasync function resolveLoginCredentials(\n flags: Record<string, string>,\n): Promise<{ email: string; password: string }> {\n let email = flags.email || process.env.LUXRAY_EMAIL || '';\n let password = '';\n\n if (flags['password-stdin'] === 'true' || flags['password-stdin'] === '') {\n password = await readStdin();\n } else if (process.env.LUXRAY_PASSWORD) {\n password = process.env.LUXRAY_PASSWORD;\n }\n\n if ((!email || !password) && process.stdin.isTTY) {\n if (!email) {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n email = (await rl.question('Email: ')).trim();\n rl.close();\n }\n if (!password) {\n password = await readSecret('Password: ');\n }\n }\n\n if (!email || !password) {\n throw new Error(\n 'Email and password are required. Use --email/--password-stdin or LUXRAY_EMAIL/LUXRAY_PASSWORD.',\n );\n }\n\n return { email, password };\n}\n\n/** Reads one line from the terminal; used for usernames and confirmations. */\nasync function askLine(question: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question(question)).trim();\n } finally {\n rl.close();\n }\n}\n\n/** `--flag value` omits the value, so `--flag` alone must not read as a path. */\nfunction flagValue(flags: Record<string, string>, name: string): string | undefined {\n const value = flags[name];\n if (value === undefined || value === '' || value === 'true') return undefined;\n return value;\n}\n\n/** Parses one `Name: value` header. The value is never echoed back in errors. */\nfunction parseAuthHeader(raw: string): { name: string; value: string } {\n const index = raw.indexOf(':');\n if (index <= 0) {\n throw new Error('Auth headers must look like \"Name: value\".');\n }\n const name = raw.slice(0, index).trim();\n const value = raw.slice(index + 1).trim();\n\n if (!/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid HTTP header name.`);\n }\n if (value.length === 0) {\n throw new Error(`Header \"${name}\" has an empty value.`);\n }\n return { name, value };\n}\n\n/** Parses a `name=value; name2=value2` cookie header into context cookies. */\nfunction parseAuthCookies(raw: string): Array<{ name: string; value: string }> {\n const cookies: Array<{ name: string; value: string }> = [];\n for (const part of raw.split(';')) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n const index = trimmed.indexOf('=');\n if (index <= 0) {\n throw new Error('Auth cookies must look like \"name=value; name2=value2\".');\n }\n const name = trimmed.slice(0, index).trim();\n const value = trimmed.slice(index + 1).trim();\n if (name.length === 0 || value.length === 0) {\n throw new Error(`Cookie \"${name || '(unnamed)'}\" has an empty name or value.`);\n }\n cookies.push({ name, value });\n }\n return cookies;\n}\n\n/** `--auth-headers-json` accepts an inline object or `@path` to a JSON file. */\nfunction parseAuthHeadersJson(raw: string): Record<string, string> {\n let text = raw;\n if (raw.startsWith('@')) {\n const path = raw.slice(1);\n if (!existsSync(path)) throw new Error(`Auth headers file not found: ${path}`);\n text = readFileSync(path, 'utf8');\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new Error(`--auth-headers-json is not valid JSON: ${(error as Error).message}`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('--auth-headers-json must be a JSON object of header names to values.');\n }\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Header \"${name}\" must have a non-empty string value.`);\n }\n // Round-trip through the single-header parser so validation is identical.\n const validated = parseAuthHeader(`${name}: ${value}`);\n headers[validated.name] = validated.value;\n }\n return headers;\n}\n\n/**\n * Collects the auth material for a terminal-initiated crawl.\n *\n * Nothing here reaches Postgres: a password is typed into the page, a header or\n * cookie is sent with each request, and every value is scrubbed from the\n * artifacts. The only durable trace is the fact that the run was authenticated.\n *\n * An empty answer means an anonymous crawl: public pages only, with sign-in\n * walls marked instead of recorded as content.\n */\nasync function resolveExploreAuth(\n flags: Record<string, string>,\n startUrl: URL,\n options: { readonly headless: boolean },\n): Promise<ExploreAuthOptions | null> {\n const saveStorageStatePath = flagValue(flags, 'save-auth-state');\n const authStatePath = flagValue(flags, 'auth-state');\n\n if (authStatePath) {\n if (!existsSync(authStatePath)) {\n throw new Error(`--auth-state file not found: ${authStatePath}`);\n }\n return {\n storageStatePath: authStatePath,\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n };\n }\n\n const loginUrlFlag = flagValue(flags, 'login-url');\n let username = flagValue(flags, 'username') ?? process.env.LUXRAY_SITE_USERNAME ?? '';\n const passwordFromStdin = flags['password-stdin'] === 'true' || flags['password-stdin'] === '';\n const noAuth = flags['no-auth'] === 'true';\n const explicitForm = Boolean(loginUrlFlag || username || passwordFromStdin);\n\n const headerFlag = flagValue(flags, 'auth-header') ?? process.env.LUXRAY_AUTH_HEADER;\n const headersJsonFlag = flagValue(flags, 'auth-headers-json');\n const cookieFlag = flagValue(flags, 'auth-cookie') ?? process.env.LUXRAY_AUTH_COOKIE;\n const explicitKeys = Boolean(headerFlag || headersJsonFlag || cookieFlag);\n\n if (explicitForm && explicitKeys) {\n throw new Error(\n 'Pass either a form sign-in (--login-url/--username/--password-stdin) or auth keys ' +\n '(--auth-header/--auth-headers-json/--auth-cookie), not both.',\n );\n }\n\n if (explicitKeys) {\n return buildKeyAuth(headerFlag, headersJsonFlag, cookieFlag, saveStorageStatePath);\n }\n\n if (!explicitForm) {\n if (noAuth || !process.stdin.isTTY) {\n // Non-interactive with no keys is an anonymous crawl by definition. It is\n // not an error: crawling a public site is the common case.\n return saveStorageStatePath ? { saveStorageStatePath } : null;\n }\n\n console.log(`\nAuthentication for ${startUrl.hostname}\n Press Enter to crawl public pages only; pages behind a sign-in wall are skipped.\n Credentials are held by this agent process and never reach the control plane.`);\n const headerLine = await readSecret('Auth header (Name: value, blank = anonymous): ');\n const cookieLine = await readSecret('Auth cookie (name=value; ..., blank = none): ');\n\n if (headerLine.trim().length === 0 && cookieLine.trim().length === 0) {\n return saveStorageStatePath ? { saveStorageStatePath } : null;\n }\n return buildKeyAuth(\n headerLine.trim() || undefined,\n undefined,\n cookieLine.trim() || undefined,\n saveStorageStatePath,\n );\n }\n\n let password = '';\n if (passwordFromStdin) {\n password = await readStdin();\n } else if (process.env.LUXRAY_SITE_PASSWORD) {\n password = process.env.LUXRAY_SITE_PASSWORD;\n }\n\n if (!username) {\n if (!process.stdin.isTTY) {\n throw new Error(\n 'A sign-in was requested without a username. Pass --username (or LUXRAY_SITE_USERNAME).',\n );\n }\n username = await askLine('Username or email: ');\n }\n\n if (!password) {\n if (!process.stdin.isTTY) {\n throw new Error(\n 'A sign-in was requested without a password. Use --password-stdin or LUXRAY_SITE_PASSWORD.',\n );\n }\n password = await readSecret('Site password: ');\n }\n\n if (!username || !password) {\n throw new Error('A username and password are required to sign in.');\n }\n\n const loginUrl = loginUrlFlag ?? startUrl.toString();\n let parsedLoginUrl: URL;\n try {\n parsedLoginUrl = new URL(loginUrl);\n } catch {\n throw new Error(`--login-url \"${loginUrl}\" is not an absolute URL.`);\n }\n if (parsedLoginUrl.protocol !== 'http:' && parsedLoginUrl.protocol !== 'https:') {\n throw new Error(`--login-url must be http(s) (got ${parsedLoginUrl.protocol}).`);\n }\n\n if (saveStorageStatePath) {\n await mkdir(dirname(saveStorageStatePath), { recursive: true });\n }\n\n return {\n credentials: { username, password },\n loginUrl: parsedLoginUrl.toString(),\n submitTimeoutMs: parsePositiveIntFlag(flags['auth-timeout-ms'], 30_000, 600_000),\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n // A captcha or 2FA prompt cannot be solved by a form fill. When the window\n // is visible the operator finishes it; otherwise the run fails with a clear\n // message instead of crawling the login wall.\n ...(options.headless\n ? {}\n : {\n manualAssist: async (): Promise<void> => {\n console.log(\n '\\nFinish the sign-in in the browser window (captcha, two-factor, device approval).',\n );\n await askLine('Press Enter once you are signed in: ');\n },\n }),\n };\n}\n\n/**\n * Builds the auth-key answer from flags or prompt lines.\n *\n * A key that was supplied but cannot be parsed is an error, never silently\n * dropped: crawling anonymously after an operator handed over a token would\n * look like the token simply did not work.\n */\nfunction buildKeyAuth(\n header: string | undefined,\n headersJson: string | undefined,\n cookies: string | undefined,\n saveStorageStatePath: string | undefined,\n): ExploreAuthOptions {\n const headers: Record<string, string> = {};\n\n if (headersJson) Object.assign(headers, parseAuthHeadersJson(headersJson));\n if (header) {\n const parsed = parseAuthHeader(header);\n headers[parsed.name] = parsed.value;\n }\n\n const parsedCookies = cookies ? parseAuthCookies(cookies) : [];\n if (Object.keys(headers).length === 0 && parsedCookies.length === 0) {\n throw new Error('Auth keys were requested but no header or cookie was supplied.');\n }\n\n return {\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n ...(parsedCookies.length > 0 ? { cookies: parsedCookies } : {}),\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n };\n}\n\nasync function resolveWorkspaceId(\n flags: Record<string, string>,\n session: LoginResponse,\n): Promise<string> {\n const requested = flags.workspace || process.env.LUXRAY_WORKSPACE_ID;\n const available = session.workspaces;\n\n if (requested) {\n if (available.length > 0 && !available.some((workspace) => workspace.id === requested)) {\n throw new Error(`You are not a member of workspace \"${requested}\".`);\n }\n return requested;\n }\n\n if (available.length === 0) {\n throw new Error(\n 'Your account does not belong to any workspace. Create one in the dashboard first.',\n );\n }\n\n const only = available[0];\n if (available.length === 1 && only) {\n return only.id;\n }\n\n if (!process.stdin.isTTY) {\n throw new Error(\n `Multiple workspaces available; pass --workspace. Options: ${available\n .map((workspace) => `${workspace.id} (${workspace.name})`)\n .join(', ')}`,\n );\n }\n\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n console.log('Available workspaces:');\n for (const workspace of available) {\n console.log(` ${workspace.id} ${workspace.name} [${workspace.role}]`);\n }\n const answer = (await rl.question('Enter Workspace ID: ')).trim();\n rl.close();\n\n if (!available.some((workspace) => workspace.id === answer)) {\n throw new Error(`You are not a member of workspace \"${answer}\".`);\n }\n return answer;\n}\n\nasync function handleRegister(flags: Record<string, string>): Promise<void> {\n const apiUrl = (flags.url || process.env.LUXRAY_API_URL || DEFAULT_API_URL).replace(/\\/$/, '');\n const wsUrl = flags.ws || process.env.LUXRAY_WS_URL || DEFAULT_WS_URL;\n const name = flags.name || process.env.LUXRAY_AGENT_NAME || os.hostname();\n const platform = os.platform() as AgentPlatform;\n const arch = os.arch() as AgentArchitecture;\n const version = '0.1.0';\n\n let session: LoginResponse | null = null;\n let accessToken: string;\n\n try {\n if (flags.token) {\n console.warn(\n '[SECURITY WARNING] Passing an access token via --token exposes it in your shell history and process list.',\n );\n accessToken = flags.token;\n } else {\n const { email, password } = await resolveLoginCredentials(flags);\n console.log(`Authenticating as ${email}...`);\n session = await login(httpFetch, apiUrl, email, password);\n accessToken = session.accessToken;\n console.log(`Authenticated as ${session.user.email}.`);\n }\n\n let workspaceId = flags.workspace || process.env.LUXRAY_WORKSPACE_ID;\n if (session) {\n workspaceId = await resolveWorkspaceId(flags, session);\n }\n if (!workspaceId) {\n throw new Error('Workspace ID is required. Use --workspace or LUXRAY_WORKSPACE_ID.');\n }\n\n console.log(`Registering agent \"${name}\" with workspace ${workspaceId} at ${apiUrl}...`);\n\n const data = await registerAgent(httpFetch, apiUrl, workspaceId, accessToken, {\n name,\n platform,\n arch,\n version,\n });\n\n const creds: StoredAgentCredentials = {\n apiUrl,\n wsUrl,\n workspaceId,\n agentId: data.agent.id,\n token: data.token,\n name,\n savedAt: new Date().toISOString(),\n };\n\n const savedPath = await CredentialVault.saveCredentials(\n creds,\n flags.config,\n flags['allow-insecure'] === 'true',\n );\n\n console.log(`\nAgent successfully registered!\n Agent ID: ${data.agent.id}\n Device Name: ${data.agent.name}\n Workspace: ${workspaceId}\n Credentials: ${savedPath}\n\nTo start your agent, run:\n npx luxray-agent start\n`);\n } catch (err) {\n if (err instanceof LuxrayApiError) {\n console.error(`Registration failed: ${err.message}`);\n } else {\n console.error(`Registration failed: ${(err as Error).message}`);\n }\n process.exit(1);\n }\n}\n\nasync function handleLogin(flags: Record<string, string>): Promise<void> {\n let agentId = flags['agent-id'] || flags.agentId;\n let workspaceId = flags.workspace;\n let token = flags.token;\n\n if (flags['token-stdin'] === 'true' || flags['token-stdin'] === '') {\n token = await readStdin();\n }\n\n // If token is provided in command line arguments, warn user about shell history leakage\n if (flags.token && !flags['token-stdin']) {\n console.warn(`\n[SECURITY WARNING] Passing credentials via '--token' exposes secrets in your shell history and process list.\nPrefer the interactive prompt or '--token-stdin' in automation scripts.\n`);\n }\n\n // Interactive prompts if fields are missing and stdin is a TTY\n if (process.stdin.isTTY && (!agentId || !workspaceId || !token)) {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n if (!workspaceId) {\n workspaceId = (await rl.question('Enter Workspace ID: ')).trim();\n }\n if (!agentId) {\n agentId = (await rl.question('Enter Agent ID: ')).trim();\n }\n rl.close();\n if (!token) {\n // Masked: the agent token must never be echoed to the terminal.\n token = await readSecret('Enter Agent Token (hidden): ');\n }\n }\n\n if (!agentId || !token || !workspaceId) {\n console.error('Error: Agent ID, Workspace ID, and Token are required.');\n process.exit(1);\n }\n\n const wsUrl = flags.ws || process.env.LUXRAY_WS_URL || DEFAULT_WS_URL;\n const apiUrl = (flags.url || process.env.LUXRAY_API_URL || DEFAULT_API_URL).replace(/\\/$/, '');\n const name = flags.name || os.hostname();\n\n const creds: StoredAgentCredentials = {\n apiUrl,\n wsUrl,\n workspaceId,\n agentId,\n token,\n name,\n savedAt: new Date().toISOString(),\n };\n\n const savedPath = await CredentialVault.saveCredentials(\n creds,\n flags.config,\n flags['allow-insecure'] === 'true',\n );\n console.log(`Credentials saved securely to ${savedPath}`);\n}\n\nasync function handleStart(flags: Record<string, string>): Promise<void> {\n const creds = await CredentialVault.loadCredentials(flags.config);\n if (!creds) {\n console.error(`\nNo valid agent credentials found.\nPlease register this agent first:\n npx luxray-agent register\nOr login interactively:\n npx luxray-agent login\nOr configure environment variables (LUXRAY_AGENT_ID, LUXRAY_AGENT_TOKEN, LUXRAY_WORKSPACE_ID).\n`);\n process.exit(1);\n }\n\n const wsUrl = flags.ws || creds.wsUrl;\n const headless = flags.headed !== 'true';\n const artifactRoot = flags.out ? flags.out : join(os.homedir(), '.luxray', 'runs');\n\n console.log(`\nStarting Luxray Agent:\n Agent ID: ${creds.agentId}\n Name: ${creds.name}\n Workspace: ${creds.workspaceId}\n Gateway: ${wsUrl}\n Artifacts: ${artifactRoot}\n`);\n\n const streamConfig = streamConfigFromEnv(process.env, {\n clientId: `luxray-agent-${creds.agentId}`,\n });\n console.log(` Kafka: ${streamConfig.brokers.join(', ')}`);\n\n const worker = new ExplorationWorker({ headless });\n const explorationLogger = {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n\n let client: AgentClient;\n let stream: TaskStream | null = null;\n const executor = new TaskExecutor({\n agentId: creds.agentId,\n // Reports leave over Kafka. The socket cannot carry them any more: the\n // server nacks task frames with WRONG_TRANSPORT.\n send: (message) => stream?.report(message) ?? false,\n maxConcurrentJobs: parsePositiveIntFlag(flags['max-jobs'], 1, 16),\n maxJobDurationMs: parsePositiveIntFlag(flags['max-job-ms'], 120_000, 86_400_000),\n explorationMaxDurationMs: parsePositiveIntFlag(\n flags['max-exploration-ms'],\n DEFAULT_EXPLORE_JOB_MS,\n 86_400_000,\n ),\n progressIntervalMs: parsePositiveIntFlag(flags['progress-interval-ms'], 1_000, 60_000),\n leaseRenewIntervalMs: flags['lease-renew-ms']\n ? parsePositiveIntFlag(flags['lease-renew-ms'], 30_000, 86_400_000)\n : undefined,\n // Dashboard-assigned EXPLORATION tasks run in the same isolated browser\n // worker the terminal `explore` command uses.\n explorationRunner: createExplorationRunner(worker, {\n artifactRoot,\n headless,\n logger: explorationLogger,\n onPage: (page) => {\n // A dashboard sees the crawl while it runs instead of after it ends.\n stream?.publishPage(page);\n },\n }),\n // The TEST job exists so dispatch, cancellation and timeouts can be\n // exercised without a browser.\n testSteps: flags['test-steps']\n ? parsePositiveIntFlag(flags['test-steps'], 5, 10_000)\n : undefined,\n testStepDelayMs: flags['test-step-delay-ms']\n ? parseNonNegativeIntFlag(flags['test-step-delay-ms'], 200, 60_000)\n : undefined,\n });\n\n stream = new TaskStream({\n config: streamConfig,\n agentId: creds.agentId,\n workspaceId: creds.workspaceId,\n handlers: {\n onOffer: (msg) => executor.handleOffer(msg),\n onCancel: (msg) => executor.handleCancel(msg),\n onPause: (msg) => executor.handlePause(msg),\n onRenewed: (msg) => executor.handleRenewed(msg),\n onNack: (msg) => executor.handleNack(msg),\n },\n logger: explorationLogger,\n });\n\n client = new AgentClient({\n wsUrl,\n agentId: creds.agentId,\n token: creds.token,\n onRevoked: (msg) => {\n console.error(`\\nAgent credentials revoked: ${msg.reason}. Exiting.`);\n void executor.shutdown().finally(() => process.exit(1));\n },\n onDisconnect: (code, reason) => {\n if (code === 4401) {\n console.error('\\nAuthentication failed: credentials invalid or revoked. Exiting.');\n void executor.shutdown().finally(() => process.exit(1));\n }\n },\n });\n\n let stopping = false;\n const shutdown = (): void => {\n if (stopping) return;\n stopping = true;\n console.log('\\nShutting down agent gracefully...');\n void (async () => {\n // Abort in-flight jobs first so the server sees the lease abandoned\n // rather than a completion that races the disconnect.\n await executor.shutdown().catch(() => {});\n // Flush the terminal report before the process disappears; the socket\n // only needs to close after that.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n process.exit(0);\n })();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n await stream.connect();\n } catch (err) {\n // No silent fallback to the socket: the socket no longer carries tasks, so\n // an agent that \"connected\" without Kafka would accept work and be unable\n // to report a byte of it.\n console.error(`Cannot start execution: ${(err as Error).message}`);\n await worker.dispose().catch(() => {});\n process.exitCode = 1;\n return;\n }\n\n try {\n await client.connect();\n console.log('Agent is online and waiting for exploration tasks.\\nPress Ctrl+C to stop.');\n } catch (err: any) {\n console.error(`Failed to connect to gateway: ${err.message}`);\n await stream.close().catch(() => {});\n await executor.shutdown();\n await worker.dispose().catch(() => {});\n process.exitCode = 1;\n }\n}\n\nasync function handleExplore(\n positionals: readonly string[],\n flags: Record<string, string>,\n): Promise<void> {\n const rawUrl = positionals[0];\n if (!rawUrl) {\n console.error('Usage: luxray-agent explore <url> [options]');\n console.error('Example: luxray-agent explore https://example.com --max-pages 20');\n process.exit(1);\n }\n\n let startUrl: URL;\n try {\n startUrl = new URL(rawUrl);\n } catch {\n console.error(`Error: \"${rawUrl}\" is not an absolute URL.`);\n process.exit(1);\n }\n if (startUrl.protocol !== 'http:' && startUrl.protocol !== 'https:') {\n console.error(`Error: only http(s) URLs can be explored (got ${startUrl.protocol}).`);\n process.exit(1);\n }\n\n const creds = await CredentialVault.loadCredentials(flags.config);\n if (!creds) {\n console.error(`\nNo valid agent credentials found.\nRegister or import this agent first:\n npx luxray-agent register\n npx luxray-agent login\n`);\n process.exit(1);\n }\n\n const hostname = startUrl.hostname.toLowerCase();\n const allowedDomains = flags['allowed-domains']\n ? flags['allowed-domains']\n .split(',')\n .map((domain) => domain.trim().toLowerCase())\n .filter((domain) => domain.length > 0)\n : [hostname];\n if (allowedDomains.length === 0) {\n console.error('Error: --allowed-domains did not contain a single hostname.');\n process.exit(1);\n }\n\n const maxPages = parsePositiveIntFlag(flags['max-pages'], DEFAULT_EXPLORE_MAX_PAGES, 1_000);\n const maxDepth = parsePositiveIntFlag(flags['max-depth'], DEFAULT_EXPLORE_MAX_DEPTH, 10);\n const maxJobMs = parsePositiveIntFlag(flags['max-job-ms'], DEFAULT_EXPLORE_JOB_MS, 3_600_000);\n const includeSubdomains = flags['include-subdomains'] === 'true';\n const includeSecrets = flags['include-secrets'] === 'true';\n const headless = flags.headed !== 'true';\n const artifactRoot = flags.out\n ? flags.out\n : join(os.homedir(), '.luxray', 'runs');\n const apiUrl = (flags.api || flags.url || creds.apiUrl).replace(/\\/$/, '');\n const wsUrl = flags.ws || creds.wsUrl;\n const streamConfig = streamConfigFromEnv(process.env, {\n clientId: `luxray-agent-${creds.agentId}`,\n });\n\n // Ask before touching the network or the control plane: a crawl that needs a\n // session should fail here, at the prompt, not 13 pages into a login wall.\n const auth = await resolveExploreAuth(flags, startUrl, { headless });\n\n // Warn before touching credentials: this changes what lands on disk.\n if (includeSecrets) {\n console.warn(\n '[SECURITY WARNING] --include-secrets keeps Authorization/Cookie headers in the run artifacts.',\n );\n }\n if (auth?.saveStorageStatePath) {\n console.warn(\n `[SECURITY WARNING] --save-auth-state writes live session cookies to ${auth.saveStorageStatePath}.`,\n );\n }\n\n const signInLine = auth?.credentials\n ? `${auth.loginUrl} (credentials used once, not stored)`\n : auth?.headers || auth?.cookies\n ? [\n auth.headers ? `${Object.keys(auth.headers).length} header(s)` : null,\n auth.cookies ? `${auth.cookies.length} cookie(s)` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(' + ') + ' (used for this run, not stored)'\n : auth?.storageStatePath\n ? `saved session from ${auth.storageStatePath}`\n : 'none (public crawl)';\n\n console.log(`\nLuxray exploration\n Start URL: ${startUrl.toString()}\n Scope: ${allowedDomains.join(', ')}${includeSubdomains ? ' (including subdomains)' : ''}\n Limits: ${maxPages} pages, depth ${maxDepth}, ${Math.round(maxJobMs / 1000)}s\n Artifacts: ${artifactRoot}\n Browser: ${headless ? 'headless' : 'visible'}\n Sign-in: ${signInLine}\n Kafka: ${streamConfig.brokers.join(', ')}\n Agent: ${creds.agentId}\n`);\n\n const worker = new ExplorationWorker({ headless });\n const logger = {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n\n let targetTaskId: string | null = null;\n let settleTargetTask: (taskId: string | null) => void = () => {};\n // The offer can beat the HTTP response that carries the task id. The sign-in\n // binding waits on this instead of reading a variable that may still be null.\n const targetTask = new Promise<string | null>((resolve) => {\n settleTargetTask = resolve;\n });\n let lastOutcome: ExplorationOutcome | null = null;\n let jobSettled = false;\n let resolveFinished: (info: JobFinishedInfo) => void = () => {};\n const finished = new Promise<JobFinishedInfo>((resolve) => {\n resolveFinished = resolve;\n });\n\n let client: AgentClient;\n let stream: TaskStream | null = null;\n const executor = new TaskExecutor({\n agentId: creds.agentId,\n send: (message) => stream?.report(message) ?? false,\n maxConcurrentJobs: 1,\n maxJobDurationMs: maxJobMs,\n explorationMaxDurationMs: maxJobMs,\n explorationRunner: createExplorationRunner(worker, {\n artifactRoot,\n headless,\n includeSecrets,\n // Only the task this command created may use the operator's session; a\n // stale queued task assigned to this agent must not inherit it.\n auth: auth\n ? {\n ...auth,\n appliesTo: async (taskId) => taskId === (await targetTask),\n }\n : undefined,\n logger,\n onPage: (page) => {\n stream?.publishPage(page);\n },\n onFinished: (result) => {\n lastOutcome = result.outcome;\n },\n }),\n onJobFinished: (info) => {\n // Unrelated tasks assigned to this agent may also come through; only the\n // one this command created decides when the command ends.\n if (targetTaskId !== null && info.taskId === targetTaskId) {\n jobSettled = true;\n resolveFinished(info);\n }\n },\n logger: {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n },\n });\n\n stream = new TaskStream({\n config: streamConfig,\n agentId: creds.agentId,\n workspaceId: creds.workspaceId,\n handlers: {\n onOffer: (msg) => executor.handleOffer(msg),\n onCancel: (msg) => executor.handleCancel(msg),\n onPause: (msg) => executor.handlePause(msg),\n onRenewed: (msg) => executor.handleRenewed(msg),\n onNack: (msg) => executor.handleNack(msg),\n },\n logger,\n });\n\n client = new AgentClient({\n wsUrl,\n agentId: creds.agentId,\n token: creds.token,\n onRevoked: (msg) => {\n console.error(`\\nAgent credentials revoked: ${msg.reason}. Exiting.`);\n executor.failActiveJobs('Agent credentials were revoked during the run.');\n void executor.shutdown().finally(() => process.exit(1));\n },\n onDisconnect: (code) => {\n if (code === 4401) {\n console.error('\\nAuthentication failed: credentials invalid or revoked. Exiting.');\n void executor.shutdown().finally(() => process.exit(1));\n }\n },\n });\n\n let stopping = false;\n const interrupt = (): void => {\n if (stopping) return;\n stopping = true;\n console.error('\\nStopped by the operator; reporting the failure to the control plane...');\n void (async () => {\n executor.failActiveJobs('Stopped by the operator (Ctrl+C).');\n await executor.shutdown().catch(() => {});\n // Flush the failure frame before the process disappears.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n process.exit(130);\n })();\n };\n process.on('SIGINT', interrupt);\n process.on('SIGTERM', interrupt);\n\n let exitCode = 0;\n try {\n await stream.connect();\n } catch (err) {\n console.error(`Cannot start the Kafka transport: ${(err as Error).message}`);\n await worker.dispose().catch(() => {});\n process.exit(1);\n }\n\n try {\n await client.connect();\n console.log(`Connected as agent ${creds.agentId}. Creating the exploration task...`);\n\n const { task } = await createAgentExplorationTask(httpFetch, apiUrl, creds.token, {\n startUrl: startUrl.toString(),\n jobType: 'EXPLORATION',\n name: flags.name,\n scope: {\n allowedDomains,\n includeSubdomains,\n maxPages,\n maxDepth,\n },\n });\n targetTaskId = task.id;\n settleTargetTask(task.id);\n console.log(`Task ${task.id} created and assigned. Watching the crawl:\\n`);\n\n // Only the handoff is time-boxed. A crawl's duration is bounded by\n // --max-job-ms, so a slow site is allowed to finish instead of being\n // killed by a watchdog that was only meant to catch a missing offer.\n const start = await executor.waitForJobStarted(task.id, OFFER_WAIT_MS);\n if (start === 'timeout') {\n console.error(\n `The API did not hand task ${task.id} to this agent within ` +\n `${Math.round(OFFER_WAIT_MS / 1000)}s. It keeps its lease, which will expire and ` +\n 'return the task to the queue; check that the gateway is reachable.',\n );\n exitCode = 1;\n } else {\n const result = await finished;\n\n if (result.outcome === 'completed') {\n printExplorationSummary(lastOutcome);\n exitCode = 0;\n } else if (result.outcome === 'stopped') {\n console.error(`\\nExploration stopped (${result.stopReason ?? 'unknown reason'}).`);\n exitCode = 130;\n } else {\n console.error(`\\nExploration failed: ${result.error ?? 'unknown error'}`);\n exitCode = 1;\n }\n }\n } catch (err) {\n if (err instanceof LuxrayApiError) {\n console.error(`Could not create the exploration task: ${err.message}`);\n } else {\n console.error(`Exploration aborted: ${(err as Error).message}`);\n }\n exitCode = 1;\n } finally {\n process.removeListener('SIGINT', interrupt);\n process.removeListener('SIGTERM', interrupt);\n // A job that started before the task was created must not wait forever.\n settleTargetTask(targetTaskId);\n\n // Walking away from a task the server still believes is running must be\n // reported: otherwise the dashboard shows a phantom RUNNING job until the\n // lease expires and the queue silently retries it.\n if (targetTaskId !== null && !jobSettled && executor.getRunningJobCount() > 0) {\n executor.failActiveJobs('The agent stopped before the crawl finished.');\n }\n\n await executor.shutdown().catch(() => {});\n // Flushes the terminal frame; without this the DB can keep saying RUNNING\n // while the command exits successfully.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n }\n\n process.exit(exitCode);\n}\n\nfunction printExplorationSummary(outcome: ExplorationOutcome | null): void {\n if (!outcome) {\n console.log('\\nExploration completed.');\n return;\n }\n\n const summary = outcome.run.summary;\n console.log(`\nExploration completed.\n Pages visited: ${summary.pagesVisited}\n Pages failed: ${summary.pagesFailed}\n Duplicate templates: ${summary.duplicatePages}\n Requests captured: ${outcome.transactionsCaptured}\n Links discovered: ${summary.linksDiscovered}\n Frontier remaining: ${summary.frontierRemaining}\n Duration: ${(summary.durationMs / 1000).toFixed(1)}s\n Artifacts: ${outcome.paths.dir}\n`);\n if (summary.truncatedByLimit) {\n console.log(\n ` Note: stopped by a limit with ${summary.frontierRemaining} URL(s) still queued. ` +\n 'Raise --max-pages/--max-depth or --max-job-ms to go further.',\n );\n }\n\n const authentication = summary.authentication;\n if (authentication) {\n const parts: string[] = [authentication.strategy];\n if (authentication.loginUrl) parts.push(`at ${authentication.loginUrl}`);\n if (authentication.headers > 0) parts.push(`${authentication.headers} header(s)`);\n if (authentication.cookies !== null) parts.push(`${authentication.cookies} cookie(s)`);\n console.log(` Auth: ${parts.join(', ')}`);\n }\n}\n\nasync function handleStatus(flags: Record<string, string>): Promise<void> {\n const creds = await CredentialVault.loadCredentials(flags.config);\n const defaultPath = CredentialVault.getDefaultPath();\n\n console.log('Luxray Local Agent Status:');\n console.log(` Credentials path: ${defaultPath}`);\n\n if (!creds) {\n console.log(' Status: NOT CONFIGURED (No credentials found)');\n return;\n }\n\n console.log(' Status: CONFIGURED');\n console.log(` Agent ID: ${creds.agentId}`);\n console.log(` Device Name: ${creds.name}`);\n console.log(` Workspace ID: ${creds.workspaceId}`);\n console.log(` Gateway WS: ${creds.wsUrl}`);\n console.log(` Registered: ${creds.savedAt}`);\n}\n\nasync function handleLogout(flags: Record<string, string>): Promise<void> {\n const cleared = await CredentialVault.clearCredentials(flags.config);\n if (cleared) {\n console.log('Credentials cleared successfully.');\n } else {\n console.log('No credentials found to clear.');\n }\n}\n\nasync function main(): Promise<void> {\n const { command, flags, positionals } = parseArgs(process.argv.slice(2));\n\n switch (command) {\n case 'register':\n await handleRegister(flags);\n break;\n case 'login':\n await handleLogin(flags);\n break;\n case 'start':\n await handleStart(flags);\n break;\n case 'explore':\n await handleExplore(positionals, flags);\n break;\n case 'status':\n await handleStatus(flags);\n break;\n case 'logout':\n await handleLogout(flags);\n break;\n case 'help':\n case '--help':\n case '-h':\n printHelp();\n break;\n default:\n printHelp();\n // An unknown command is an operator mistake, so it is not a success.\n process.exitCode = 1;\n break;\n }\n}\n\nmain().catch((err) => {\n console.error('Fatal agent error:', err);\n process.exit(1);\n});\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface StoredAgentCredentials {\n apiUrl: string;\n wsUrl: string;\n workspaceId: string;\n agentId: string;\n token: string;\n name: string;\n savedAt: string;\n}\n\nexport class CredentialVault {\n public static getDefaultPath(): string {\n const override = process.env.LUXRAY_CREDENTIALS_PATH;\n if (override && override.trim().length > 0) {\n return path.resolve(override);\n }\n const homeDir = os.homedir();\n return path.join(homeDir, '.luxray', 'credentials.json');\n }\n\n /**\n * Securely saves credentials to the file system with platform-specific ACL/permission restrictions.\n * - POSIX: Mode 0600 on file, 0700 on directory (readable/writable only by UID).\n * - Windows: Applies icacls to restrict file ACL to the active %USERNAME%.\n */\n public static async saveCredentials(\n credentials: StoredAgentCredentials,\n filePath?: string,\n allowInsecureFallback = false,\n ): Promise<string> {\n const targetPath = filePath ?? this.getDefaultPath();\n const targetDir = path.dirname(targetPath);\n\n // Ensure parent directory exists with 0700 mode permissions\n await fs.mkdir(targetDir, { recursive: true, mode: 0o700 });\n\n const content = JSON.stringify(credentials, null, 2);\n\n // Write file directly with 0600 permissions\n await fs.writeFile(targetPath, content, { encoding: 'utf8', mode: 0o600 });\n\n // Apply platform-specific ACL enforcement\n if (os.platform() === 'win32') {\n try {\n const username = process.env.USERNAME;\n if (username) {\n // Remove inherited ACLs and grant exclusive read/write to current user\n await execFileAsync('icacls', [\n targetPath,\n '/inheritance:r',\n '/grant:r',\n `${username}:(R,W)`,\n ]);\n }\n } catch (err: any) {\n if (!allowInsecureFallback && process.env.LUXRAY_ALLOW_INSECURE_STORAGE !== 'true') {\n console.warn(\n `[CredentialVault:WARN] Could not apply strict Windows NTFS ACLs to credentials file: ${err.message}.`,\n );\n }\n }\n } else {\n try {\n await fs.chmod(targetPath, 0o600);\n } catch (err: any) {\n if (!allowInsecureFallback && process.env.LUXRAY_ALLOW_INSECURE_STORAGE !== 'true') {\n console.warn(\n `[CredentialVault:WARN] Could not apply chmod 0600 to credentials file: ${err.message}.`,\n );\n }\n }\n }\n\n return targetPath;\n }\n\n /**\n * Loads credentials from the file system or environment variables.\n * Environment variables take precedence if LUXRAY_AGENT_TOKEN and LUXRAY_AGENT_ID are provided.\n */\n public static async loadCredentials(filePath?: string): Promise<StoredAgentCredentials | null> {\n // Check environment variable overrides first\n const envToken = process.env.LUXRAY_AGENT_TOKEN;\n const envAgentId = process.env.LUXRAY_AGENT_ID;\n const envWorkspaceId = process.env.LUXRAY_WORKSPACE_ID;\n const envApiUrl = process.env.LUXRAY_API_URL || 'http://localhost:4000';\n const envWsUrl = process.env.LUXRAY_WS_URL || 'ws://127.0.0.1:4001/v1/agent/socket';\n\n if (envToken && envAgentId && envWorkspaceId) {\n return {\n apiUrl: envApiUrl,\n wsUrl: envWsUrl,\n workspaceId: envWorkspaceId,\n agentId: envAgentId,\n token: envToken,\n name: process.env.LUXRAY_AGENT_NAME || os.hostname(),\n savedAt: new Date().toISOString(),\n };\n }\n\n const targetPath = filePath ?? this.getDefaultPath();\n\n try {\n const data = await fs.readFile(targetPath, 'utf8');\n const parsed = JSON.parse(data) as Partial<StoredAgentCredentials>;\n\n if (\n !parsed.agentId ||\n !parsed.token ||\n !parsed.workspaceId ||\n !parsed.wsUrl\n ) {\n return null;\n }\n\n return {\n apiUrl: parsed.apiUrl || 'http://localhost:4000',\n wsUrl: parsed.wsUrl,\n workspaceId: parsed.workspaceId,\n agentId: parsed.agentId,\n token: parsed.token,\n name: parsed.name || 'Unnamed Agent',\n savedAt: parsed.savedAt || new Date().toISOString(),\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Deletes the stored credentials file.\n */\n public static async clearCredentials(filePath?: string): Promise<boolean> {\n const targetPath = filePath ?? this.getDefaultPath();\n try {\n await fs.unlink(targetPath);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { WebSocket } from 'ws';\nimport * as os from 'node:os';\nimport type {\n AgentPlatform,\n AgentArchitecture,\n AgentProtocolMessage,\n AgentConnectedMessage,\n AgentHeartbeatAckMessage,\n AgentErrorMessage,\n AgentRevokedMessage,\n AgentStatusMessage,\n} from '@luxray/shared';\n\nexport type AgentClientState =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'stopped'\n | 'revoked';\n\nexport interface AgentClientOptions {\n wsUrl: string;\n agentId: string;\n token: string;\n version?: string;\n platform?: AgentPlatform;\n arch?: AgentArchitecture;\n heartbeatIntervalMs?: number;\n autoReconnect?: boolean;\n initialBackoffMs?: number;\n maxBackoffMs?: number;\n onConnected?: (msg: AgentConnectedMessage) => void;\n onHeartbeatAck?: (msg: AgentHeartbeatAckMessage) => void;\n onRevoked?: (msg: AgentRevokedMessage) => void;\n onError?: (err: Error) => void;\n onDisconnect?: (code: number, reason: string) => void;\n logger?: {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n };\n}\n\nexport class AgentClient {\n private ws: WebSocket | null = null;\n private state: AgentClientState = 'idle';\n private heartbeatTimer: NodeJS.Timeout | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private reconnectAttempt = 0;\n private isIntentionallyClosed = false;\n private activeHeartbeatIntervalMs = 10000;\n private connectionId: string | null = null;\n\n private readonly wsUrl: string;\n private readonly agentId: string;\n private readonly token: string;\n private readonly version: string;\n private readonly platform: AgentPlatform;\n private readonly arch: AgentArchitecture;\n private readonly autoReconnect: boolean;\n private readonly initialBackoffMs: number;\n private readonly maxBackoffMs: number;\n private readonly logger: NonNullable<AgentClientOptions['logger']>;\n\n constructor(private readonly options: AgentClientOptions) {\n this.wsUrl = options.wsUrl;\n this.agentId = options.agentId;\n this.token = options.token;\n this.version = options.version || '0.1.0';\n this.platform = options.platform || (os.platform() as AgentPlatform);\n this.arch = options.arch || (os.arch() as AgentArchitecture);\n this.autoReconnect = options.autoReconnect ?? true;\n this.initialBackoffMs = options.initialBackoffMs ?? 1000;\n this.maxBackoffMs = options.maxBackoffMs ?? 30000;\n this.activeHeartbeatIntervalMs = options.heartbeatIntervalMs ?? 10000;\n this.logger = options.logger ?? {\n info: (...args) => console.log('[LuxrayAgent]', ...args),\n warn: (...args) => console.warn('[LuxrayAgent:WARN]', ...args),\n error: (...args) => console.error('[LuxrayAgent:ERROR]', ...args),\n debug: (...args) => {},\n };\n }\n\n public getState(): AgentClientState {\n return this.state;\n }\n\n public getConnectionId(): string | null {\n return this.connectionId;\n }\n\n public isConnected(): boolean {\n return this.state === 'connected' && this.ws?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Connects to the Luxray Cloud WebSocket server and completes the hello handshake.\n */\n public connect(): Promise<AgentConnectedMessage> {\n if (this.state === 'revoked') {\n return Promise.reject(new Error('Agent credentials have been revoked. Cannot connect.'));\n }\n\n this.isIntentionallyClosed = false;\n this.state = 'connecting';\n\n return new Promise((resolve, reject) => {\n let isResolved = false;\n\n try {\n this.ws = new WebSocket(this.wsUrl);\n } catch (err: any) {\n this.state = 'idle';\n return reject(err);\n }\n\n const connectionTimeout = setTimeout(() => {\n if (!isResolved) {\n isResolved = true;\n this.logger.error('Connection timed out waiting for server response.');\n this.ws?.terminate();\n reject(new Error('Connection timed out.'));\n }\n }, 15000);\n\n this.ws.on('open', () => {\n this.logger.info(`WebSocket transport opened to ${this.wsUrl}. Sending agent.hello...`);\n this.sendHello();\n });\n\n this.ws.on('message', (raw: Buffer | string) => {\n try {\n const msg = JSON.parse(raw.toString()) as AgentProtocolMessage;\n this.handleIncomingMessage(msg, (connected) => {\n if (!isResolved) {\n isResolved = true;\n clearTimeout(connectionTimeout);\n resolve(connected);\n }\n });\n } catch (err: any) {\n this.logger.error('Failed to parse incoming WebSocket message:', err.message);\n }\n });\n\n this.ws.on('close', (code, reasonBuf) => {\n clearTimeout(connectionTimeout);\n const reason = reasonBuf.toString();\n this.handleClose(code, reason);\n if (!isResolved) {\n isResolved = true;\n reject(new Error(`WebSocket closed during handshake (code: ${code}, reason: ${reason})`));\n }\n });\n\n this.ws.on('error', (err) => {\n this.logger.error('WebSocket transport error:', err.message);\n if (this.options.onError) {\n this.options.onError(err);\n }\n });\n });\n }\n\n /**\n * Sends the agent.hello greeting to identify and authenticate this agent.\n */\n private sendHello(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const helloPayload = {\n type: 'agent.hello' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n token: this.token,\n agentVersion: this.version,\n platform: this.platform,\n arch: this.arch,\n timestamp: Date.now(),\n };\n\n this.ws.send(JSON.stringify(helloPayload));\n }\n\n /**\n * Handles incoming protocol messages.\n */\n private handleIncomingMessage(\n msg: AgentProtocolMessage,\n onConnectedFirstTime: (connected: AgentConnectedMessage) => void,\n ): void {\n switch (msg.type) {\n case 'agent.connected': {\n const connectedMsg = msg as AgentConnectedMessage;\n this.state = 'connected';\n this.reconnectAttempt = 0;\n this.connectionId = connectedMsg.connectionId;\n this.activeHeartbeatIntervalMs = connectedMsg.heartbeatIntervalMs || 10000;\n this.logger.info(\n `Successfully connected & authenticated with Luxray Cloud! Connection ID: ${connectedMsg.connectionId}`,\n );\n\n this.startHeartbeatLoop();\n onConnectedFirstTime(connectedMsg);\n\n if (this.options.onConnected) {\n this.options.onConnected(connectedMsg);\n }\n break;\n }\n\n case 'agent.heartbeat.ack': {\n const ackMsg = msg as AgentHeartbeatAckMessage;\n this.logger.debug(`Heartbeat acknowledged by server (ack: ${ackMsg.timestamp})`);\n if (this.options.onHeartbeatAck) {\n this.options.onHeartbeatAck(ackMsg);\n }\n break;\n }\n\n case 'agent.revoked': {\n const revokedMsg = msg as AgentRevokedMessage;\n this.state = 'revoked';\n this.isIntentionallyClosed = true;\n this.logger.error(`CRITICAL: Agent credentials have been revoked. Reason: ${revokedMsg.reason}`);\n this.stopHeartbeatLoop();\n if (this.options.onRevoked) {\n this.options.onRevoked(revokedMsg);\n }\n this.ws?.close(4401, 'Agent Revoked');\n break;\n }\n\n case 'agent.error': {\n const errMsg = msg as AgentErrorMessage;\n this.logger.error(`Server error [${errMsg.code}]: ${errMsg.message}`);\n if (errMsg.fatal) {\n this.logger.error('Fatal server error encountered. Closing connection.');\n this.ws?.close(4000, errMsg.message);\n }\n break;\n }\n\n default:\n // Task frames do not travel over this socket any more. One arriving\n // here is either a stale server or a bug worth noticing.\n this.logger.debug('Unhandled message type:', (msg as any).type);\n }\n }\n\n /**\n * Starts periodic heartbeat transmission.\n */\n private startHeartbeatLoop(): void {\n this.stopHeartbeatLoop();\n this.heartbeatTimer = setInterval(() => {\n this.sendHeartbeat();\n }, this.activeHeartbeatIntervalMs);\n }\n\n private stopHeartbeatLoop(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n /**\n * Transmits heartbeat metrics to the cloud.\n */\n private sendHeartbeat(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const memoryMb = Math.round(process.memoryUsage().rss / (1024 * 1024));\n const uptime = Math.round(process.uptime());\n\n const heartbeatPayload = {\n type: 'agent.heartbeat' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n memoryUsageMb: memoryMb,\n uptimeSeconds: uptime,\n timestamp: Date.now(),\n };\n\n try {\n this.ws.send(JSON.stringify(heartbeatPayload));\n this.logger.debug(`Heartbeat sent: memory=${memoryMb}MB, uptime=${uptime}s`);\n } catch (err: any) {\n this.logger.warn('Failed to transmit heartbeat:', err.message);\n }\n }\n\n /**\n * Handles WebSocket closure and schedules reconnection if appropriate.\n */\n private handleClose(code: number, reason: string): void {\n this.stopHeartbeatLoop();\n this.connectionId = null;\n\n if (this.options.onDisconnect) {\n this.options.onDisconnect(code, reason);\n }\n\n if (code === 4401 || this.state === 'revoked') {\n this.state = 'revoked';\n this.logger.error('Connection closed: Agent credentials revoked. Will NOT reconnect.');\n return;\n }\n\n if (this.isIntentionallyClosed) {\n this.state = 'stopped';\n this.logger.info('Agent stopped gracefully.');\n return;\n }\n\n if (code === 4009) {\n this.logger.warn('Another instance of this agent connected elsewhere. Backing off.');\n }\n\n if (!this.autoReconnect) {\n this.state = 'idle';\n this.logger.info(`Connection closed (code: ${code}, reason: ${reason}). Auto-reconnect is disabled.`);\n return;\n }\n\n this.scheduleReconnect();\n }\n\n /**\n * Exponential backoff with random jitter for reconnects.\n */\n private scheduleReconnect(): void {\n this.state = 'reconnecting';\n this.reconnectAttempt++;\n\n // Backoff formula: initialBackoffMs * 1.5^(attempt - 1) + jitter (0 - 1000ms)\n const exponential = this.initialBackoffMs * Math.pow(1.5, Math.min(this.reconnectAttempt, 10));\n const jitter = Math.floor(Math.random() * 1000);\n const delay = Math.min(exponential + jitter, this.maxBackoffMs);\n\n this.logger.warn(\n `Connection lost. Reconnecting in ${(delay / 1000).toFixed(1)}s (attempt ${this.reconnectAttempt})...`,\n );\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n }\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.connect();\n } catch (err: any) {\n this.logger.warn('Reconnect attempt failed:', err.message);\n // The close event will trigger the next reconnect attempt\n }\n }, delay);\n }\n\n /**\n * Gracefully stops the agent connection and notifies cloud.\n *\n * Resolves once the socket has actually closed, not when closing was\n * requested. A job's terminal frame (a completion or a failure) may still be\n * in the send buffer, and the peer processes frames in order: waiting for the\n * close handshake means the report was delivered before this process exits\n * and claims the run ended.\n */\n public async disconnect(timeoutMs = 1_000): Promise<void> {\n this.isIntentionallyClosed = true;\n this.state = 'stopped';\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n this.stopHeartbeatLoop();\n\n const ws = this.ws;\n this.ws = null;\n if (!ws) return;\n\n // Send a graceful goodbye status before closing if socket is open\n if (ws.readyState === WebSocket.OPEN) {\n const goodbyePayload: AgentStatusMessage = {\n type: 'agent.status',\n version: '1.0',\n agentId: this.agentId,\n status: 'DISCONNECTED',\n timestamp: Date.now(),\n };\n try {\n ws.send(JSON.stringify(goodbyePayload));\n } catch {}\n }\n\n if (ws.readyState === WebSocket.CLOSED) return;\n\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n timer.unref?.();\n\n ws.once('close', () => {\n clearTimeout(timer);\n resolve();\n });\n\n try {\n ws.close(1000, 'Agent Stopped Manually');\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n }\n}\n","/** Raised when the broker cannot be reached or refuses the connection. */\nexport class StreamUnavailableError extends Error {\n public override readonly name = 'StreamUnavailableError';\n\n constructor(\n message: string,\n public readonly brokers: readonly string[],\n public override readonly cause?: unknown,\n ) {\n super(message);\n }\n}\n\n/** Raised when a record is not a valid envelope. Never inferred as meaning. */\nexport class StreamProtocolError extends Error {\n public override readonly name = 'StreamProtocolError';\n}\n","import { StreamUnavailableError } from './errors.js';\n\nexport interface StreamSaslConfig {\n readonly mechanism: 'plain' | 'scram-sha-256' | 'scram-sha-512';\n readonly username: string;\n readonly password: string;\n}\n\nexport interface StreamConfig {\n readonly brokers: readonly string[];\n readonly clientId: string;\n readonly ssl: boolean;\n readonly sasl: StreamSaslConfig | null;\n /** How long a broker connection may take before it counts as unavailable. */\n readonly connectionTimeoutMs: number;\n /** Retries per connect attempt; kept small so a missing broker fails fast. */\n readonly retryCount: number;\n /** Partitions used when a stream topic has to be created. Default 3. */\n readonly topicPartitions?: number;\n /** Replication factor used when a stream topic has to be created. Default 1. */\n readonly replicationFactor?: number;\n}\n\nconst DEFAULT_BROKERS = '127.0.0.1:9092';\n\nexport function streamConfigFromEnv(\n env: NodeJS.ProcessEnv = process.env,\n overrides: Partial<StreamConfig> = {},\n): StreamConfig {\n const brokers = (env['KAFKA_BROKERS'] ?? DEFAULT_BROKERS)\n .split(',')\n .map((broker) => broker.trim())\n .filter((broker) => broker.length > 0);\n\n if (brokers.length === 0) {\n throw new Error('KAFKA_BROKERS is set but lists no broker address.');\n }\n\n const merged: StreamConfig = {\n brokers,\n clientId: env['KAFKA_CLIENT_ID'] ?? 'luxray',\n ssl: (env['KAFKA_SSL'] ?? '').toLowerCase() === 'true',\n sasl: saslFromEnv(env),\n connectionTimeoutMs: 5_000,\n retryCount: 2,\n topicPartitions: positiveInt(env['KAFKA_TOPIC_PARTITIONS'], 3, 'KAFKA_TOPIC_PARTITIONS'),\n replicationFactor: positiveInt(\n env['KAFKA_REPLICATION_FACTOR'],\n 1,\n 'KAFKA_REPLICATION_FACTOR',\n ),\n ...overrides,\n };\n\n // A retry count of zero is rejected by kafkajs whenever the producer is\n // idempotent, which it always is here.\n return { ...merged, retryCount: Math.max(1, merged.retryCount) };\n}\n\nfunction saslFromEnv(env: NodeJS.ProcessEnv): StreamSaslConfig | null {\n const username = env['KAFKA_SASL_USERNAME'];\n const password = env['KAFKA_SASL_PASSWORD'];\n if (!username || !password) return null;\n\n const raw = (env['KAFKA_SASL_MECHANISM'] ?? 'plain').toLowerCase();\n if (raw !== 'plain' && raw !== 'scram-sha-256' && raw !== 'scram-sha-512') {\n throw new Error(\n `KAFKA_SASL_MECHANISM must be plain, scram-sha-256 or scram-sha-512 (got ${raw}).`,\n );\n }\n return { mechanism: raw, username, password };\n}\n\n/** Parses a positive integer setting, naming the variable in the error. */\nfunction positiveInt(raw: string | undefined, fallback: number, name: string): number {\n if (raw === undefined || raw.trim() === '') return fallback;\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer (got \"${raw}\").`);\n }\n return value;\n}\n\n/** One error message for both processes, naming the thing to fix. */\nexport function unavailableError(config: StreamConfig, cause: unknown): StreamUnavailableError {\n const detail = cause instanceof Error ? cause.message : String(cause);\n return new StreamUnavailableError(\n `Kafka is not reachable at ${config.brokers.join(', ')} (${detail}). ` +\n 'Start it with `docker compose up -d kafka`, or point KAFKA_BROKERS at a broker.',\n config.brokers,\n cause,\n );\n}\n","import type { StreamEnvelope, StreamKind } from '@luxray/shared';\nimport { StreamProtocolError } from './errors.js';\n\nconst KINDS: readonly StreamKind[] = ['task', 'report', 'event', 'result'];\n\nexport function encodeEnvelope<T>(envelope: StreamEnvelope<T>): string {\n return JSON.stringify(envelope);\n}\n\n/**\n * Parses one record.\n *\n * A malformed record is a protocol error, never a partially usable message:\n * acting on half an offer would be worse than dropping it, because the durable\n * offer stays in the task row and is replayed on the next connection.\n *\n * `expected` may name several kinds when a topic deliberately carries more than\n * one. Page results share the report topic so a task's pages and its completion\n * stay in one partition order; the caller dispatches on the returned kind.\n */\nexport function decodeEnvelope<T>(\n raw: string,\n expected?: StreamKind | readonly StreamKind[],\n): StreamEnvelope<T> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new StreamProtocolError(`Record is not JSON: ${(error as Error).message}`);\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new StreamProtocolError('Record is not an object.');\n }\n\n const record = parsed as Record<string, unknown>;\n if (record['envelope'] !== 1) {\n throw new StreamProtocolError(`Unsupported envelope version: ${String(record['envelope'])}.`);\n }\n\n const kind = record['kind'];\n if (typeof kind !== 'string' || !KINDS.includes(kind as StreamKind)) {\n throw new StreamProtocolError(`Unknown stream kind: ${String(kind)}.`);\n }\n if (expected !== undefined) {\n const allowed = typeof expected === 'string' ? [expected] : expected;\n if (!allowed.includes(kind as StreamKind)) {\n throw new StreamProtocolError(\n `Expected a ${allowed.join(' or ')} record, got ${kind}.`,\n );\n }\n }\n\n const agentId = record['agentId'];\n // Results and lifecycle events may concern an unassigned task, so only the\n // two directional streams require a producer identity.\n if (typeof agentId !== 'string') {\n throw new StreamProtocolError('Envelope has no agentId.');\n }\n if ((kind === 'task' || kind === 'report') && agentId.length === 0) {\n throw new StreamProtocolError('Envelope has no agentId.');\n }\n\n const workspaceId = record['workspaceId'];\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new StreamProtocolError('Envelope has no workspaceId.');\n }\n\n const sentAt = record['sentAt'];\n if (typeof sentAt !== 'number' || !Number.isFinite(sentAt)) {\n throw new StreamProtocolError('Envelope has no sentAt.');\n }\n\n const payload = record['payload'];\n if (payload === null || typeof payload !== 'object') {\n throw new StreamProtocolError('Envelope has no payload.');\n }\n\n return {\n envelope: 1,\n kind: kind as StreamKind,\n agentId,\n workspaceId,\n sentAt,\n payload: payload as T,\n };\n}\n","import { Kafka, logLevel, type Consumer, type Producer, type SASLOptions } from 'kafkajs';\nimport type { StreamConfig } from './config.js';\nimport { unavailableError } from './config.js';\nimport { StreamProtocolError, StreamUnavailableError } from './errors.js';\nexport interface StreamLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/** One record as consumers receive it. */\nexport interface StreamMessage {\n readonly key: string | null;\n readonly value: string;\n}\n\nexport interface StreamPublisher {\n connect(): Promise<void>;\n publish(topic: string, key: string, value: string): Promise<void>;\n /** Resolves once every accepted record has been acknowledged by the broker. */\n flush(): Promise<void>;\n disconnect(): Promise<void>;\n readonly publishedCount: number;\n readonly failedCount: number;\n}\n\nexport interface StreamSubscriber {\n connect(): Promise<void>;\n /**\n * Subscribes to `topics` and starts consuming. The handler is awaited, so a\n * throw leaves the offset uncommitted and the record is redelivered: every\n * handler must therefore be idempotent (the task service already is).\n */\n subscribe(\n topics: readonly string[],\n handler: (message: StreamMessage) => Promise<void>,\n ): Promise<void>;\n disconnect(): Promise<void>;\n readonly handledCount: number;\n readonly skippedCount: number;\n}\n\nfunction saslOptions(config: StreamConfig): SASLOptions | undefined {\n if (!config.sasl) return undefined;\n return {\n mechanism: config.sasl.mechanism,\n username: config.sasl.username,\n password: config.sasl.password,\n };\n}\n\nfunction createKafka(config: StreamConfig): Kafka {\n return new Kafka({\n clientId: config.clientId,\n brokers: [...config.brokers],\n ssl: config.ssl || undefined,\n sasl: saslOptions(config),\n connectionTimeout: config.connectionTimeoutMs,\n retry: { retries: config.retryCount, initialRetryTime: 300 },\n logLevel: logLevel.ERROR,\n });\n}\n\n/**\n * Creates the stream topics if the broker does not have them yet.\n *\n * Subscribing to a missing topic would make metadata refresh race the broker's\n * auto-creation, which surfaces as a transient `REPLICA_NOT_AVAILABLE` and\n * aborts startup. Creating the topics first, and waiting for their leaders, makes\n * the first subscribe deterministic on a fresh broker. Existing topics are left\n * untouched, including their partition count.\n *\n * Existing topics are filtered out before the create call: asking the broker to\n * create a topic that already exists is answered with a per-topic error, which\n * kafkajs reports at ERROR level. That noise on every restart trains operators\n * to ignore the stream logs, so the check is done here instead.\n */\nexport async function ensureTopics(\n config: StreamConfig,\n topics: readonly string[],\n logger?: StreamLogger,\n): Promise<void> {\n const admin = createKafka(config).admin();\n try {\n await admin.connect();\n } catch (error) {\n await admin.disconnect().catch(() => {});\n throw unavailableError(config, error);\n }\n\n try {\n const existing = new Set(await admin.listTopics());\n const missing = topics.filter((topic) => !existing.has(topic));\n if (missing.length === 0) return;\n\n const partitions = config.topicPartitions ?? 3;\n const replicationFactor = config.replicationFactor ?? 1;\n await admin.createTopics({\n topics: missing.map((topic) => ({\n topic,\n numPartitions: partitions,\n replicationFactor,\n })),\n waitForLeaders: true,\n });\n logger?.info(\n `Created stream topics: ${missing.join(', ')} ` +\n `(${partitions} partition(s), replication ${replicationFactor}).`,\n );\n } catch (error) {\n throw new StreamUnavailableError(\n `Could not create the stream topics (${topics.join(', ')}): ${(error as Error).message}`,\n config.brokers,\n error,\n );\n } finally {\n await admin.disconnect().catch(() => {});\n }\n}\n\n/**\n * Ordered, at-least-once producer.\n *\n * Sends are chained rather than fired in parallel so the broker sees one\n * agent's frames in the order they were produced. `acks: -1` means the promise\n * resolves only after every in-sync replica has the record, which is what makes\n * `flush()` a real guarantee before the process exits.\n */\nexport class KafkaPublisher implements StreamPublisher {\n private producer: Producer | null = null;\n private tail: Promise<void> = Promise.resolve();\n private sent = 0;\n private failed = 0;\n\n constructor(\n private readonly config: StreamConfig,\n private readonly logger?: StreamLogger,\n ) {}\n\n public get publishedCount(): number {\n return this.sent;\n }\n\n public get failedCount(): number {\n return this.failed;\n }\n\n public async connect(): Promise<void> {\n if (this.producer) return;\n const kafka = createKafka(this.config);\n try {\n const producer = kafka.producer({ allowAutoTopicCreation: true, idempotent: true });\n await producer.connect();\n this.producer = producer;\n } catch (error) {\n throw unavailableError(this.config, error);\n }\n this.logger?.debug(`Kafka producer connected to ${this.config.brokers.join(', ')}.`);\n }\n\n public publish(topic: string, key: string, value: string): Promise<void> {\n const producer = this.producer;\n if (!producer) {\n return Promise.reject(\n new StreamUnavailableError(\n 'The Kafka producer is not connected.',\n this.config.brokers,\n ),\n );\n }\n\n const send = this.tail.then(() =>\n producer.send({ topic, acks: -1, messages: [{ key, value }] }),\n );\n const settled = send.then(\n () => {\n this.sent += 1;\n },\n (error: unknown) => {\n this.failed += 1;\n this.logger?.error(\n `Could not publish to ${topic}: ${(error as Error).message}`,\n );\n throw error;\n },\n );\n // The chain must survive a failed send, or one broker hiccup would stall\n // every later record.\n this.tail = settled.catch(() => {});\n return settled;\n }\n\n public async flush(): Promise<void> {\n await this.tail;\n }\n\n public async disconnect(): Promise<void> {\n const producer = this.producer;\n this.producer = null;\n if (!producer) return;\n await this.tail.catch(() => {});\n await producer.disconnect().catch(() => {});\n }\n}\n\n/**\n * Consumer for one group.\n *\n * A poison record (bad envelope) is logged and skipped; anything else throws, so\n * the offset stays put and the record is retried. That is the only split where\n * at-least-once is safe: malformed input can never become authority, and valid\n * input is idempotent downstream.\n */\nexport class KafkaSubscriber implements StreamSubscriber {\n private consumer: Consumer | null = null;\n private started = false;\n private handled = 0;\n private skipped = 0;\n\n constructor(\n private readonly config: StreamConfig,\n private readonly groupId: string,\n private readonly options?: {\n readonly fromBeginning?: boolean;\n readonly logger?: StreamLogger;\n },\n ) {}\n\n public get handledCount(): number {\n return this.handled;\n }\n\n public get skippedCount(): number {\n return this.skipped;\n }\n\n public async connect(): Promise<void> {\n if (this.consumer) return;\n const kafka = createKafka(this.config);\n const consumer = kafka.consumer({\n groupId: this.groupId,\n sessionTimeout: 30_000,\n heartbeatInterval: 3_000,\n });\n try {\n await consumer.connect();\n } catch (error) {\n await consumer.disconnect().catch(() => {});\n throw unavailableError(this.config, error);\n }\n this.consumer = consumer;\n this.options?.logger?.debug(\n `Kafka consumer ${this.groupId} connected to ${this.config.brokers.join(', ')}.`,\n );\n }\n\n public async subscribe(\n topics: readonly string[],\n handler: (message: StreamMessage) => Promise<void>,\n ): Promise<void> {\n const consumer = this.consumer;\n if (!consumer) {\n throw new StreamUnavailableError(\n `Kafka consumer ${this.groupId} is not connected.`,\n this.config.brokers,\n );\n }\n if (this.started) {\n throw new Error(`Kafka consumer ${this.groupId} is already running.`);\n }\n\n const fromBeginning = this.options?.fromBeginning ?? false;\n for (const topic of topics) {\n await consumer.subscribe({ topic, fromBeginning });\n }\n\n await consumer.run({\n autoCommit: true,\n partitionsConsumedConcurrently: 1,\n eachMessage: async ({ topic, message }) => {\n if (!message.value) return;\n try {\n await handler({\n key: message.key ? message.key.toString() : null,\n value: message.value.toString(),\n });\n this.handled += 1;\n } catch (error) {\n if (error instanceof StreamProtocolError) {\n this.skipped += 1;\n this.options?.logger?.warn(\n `Skipping a malformed record on ${topic}: ${error.message}`,\n );\n return;\n }\n throw error;\n }\n },\n });\n this.started = true;\n }\n\n public async disconnect(): Promise<void> {\n const consumer = this.consumer;\n this.consumer = null;\n this.started = false;\n if (!consumer) return;\n await consumer.disconnect().catch(() => {});\n }\n}\n","/**\n * Topic names and partition keys.\n *\n * One topic per direction rather than one per agent: a topic per agent is\n * unbounded topic creation on a broker that is supposed to be boring. Ordering\n * is preserved per key instead, which is all the protocol needs:\n *\n * - commands are keyed by agent, so one agent's offers arrive in order;\n * - reports are keyed by task, so one task's pages, ack, progress and completion\n * arrive in order even when several agents report concurrently;\n * - results are keyed by task, for the same reason.\n */\nexport const STREAM_TOPICS = {\n /** Server to agent: offers, control frames, lease renewals, nacks. */\n commands: 'luxray.agent.commands',\n /**\n * Agent to server: page observations and acks/progress/checkpoints/completion.\n *\n * Pages share this topic with commands on purpose. Keyed by task, they land in\n * one partition, so the control plane applies every page before the report\n * that closes the same attempt. A `report` record always follows this order.\n */\n reports: 'luxray.agent.reports',\n /** Server to subscribers: durable lifecycle events, mirrored for consumers. */\n events: 'luxray.tasks.events',\n /** Server to subscribers: page observations, mirrored after they persist. */\n results: 'luxray.crawl.results',\n} as const;\n\nexport type StreamTopic = (typeof STREAM_TOPICS)[keyof typeof STREAM_TOPICS];\n\n/**\n * Every stream topic, in the order a fresh broker should be given them.\n *\n * Consumers create topics explicitly before subscribing: subscribing to a topic\n * that does not exist yet makes metadata refresh race topic creation, and a\n * control plane must not fail to start on that transient.\n */\nexport const STREAM_TOPIC_LIST: readonly StreamTopic[] = [\n STREAM_TOPICS.commands,\n STREAM_TOPICS.reports,\n STREAM_TOPICS.results,\n STREAM_TOPICS.events,\n];\n\n/** Each agent is its own consumer group, so it sees only its own commands. */\nexport function agentConsumerGroup(agentId: string): string {\n return `luxray-agent-${agentId}`;\n}\n\n/** All API instances share a group: a report is applied exactly once. */\nexport const API_REPORTS_GROUP = 'luxray-api-reports';\nexport const API_RESULTS_GROUP = 'luxray-api-results';\n","import type {\n AgentTaskCancelMessage,\n AgentTaskClientMessage,\n AgentTaskNackMessage,\n AgentTaskOfferMessage,\n AgentTaskPauseMessage,\n AgentTaskRenewedMessage,\n AgentTaskServerMessage,\n CrawlPageResult,\n StreamEnvelope,\n} from '@luxray/shared';\nimport {\n KafkaPublisher,\n KafkaSubscriber,\n STREAM_TOPICS,\n agentConsumerGroup,\n decodeEnvelope,\n encodeEnvelope,\n ensureTopics,\n type StreamConfig,\n type StreamMessage,\n type StreamPublisher,\n type StreamSubscriber,\n} from '@luxray/streaming';\n\nexport interface TaskStreamLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/**\n * Receives the commands addressed to this agent.\n *\n * Handlers are synchronous by design: the executor's decisions (ack, run, stop)\n * are decisions about local state, and a Kafka handler that awaits a long job\n * would stall the partition behind it.\n */\nexport interface TaskStreamHandlers {\n readonly onOffer: (message: AgentTaskOfferMessage) => void;\n readonly onCancel: (message: AgentTaskCancelMessage) => void;\n readonly onPause: (message: AgentTaskPauseMessage) => void;\n readonly onRenewed: (message: AgentTaskRenewedMessage) => void;\n readonly onNack: (message: AgentTaskNackMessage) => void;\n}\n\nexport interface TaskStreamOptions {\n readonly config: StreamConfig;\n readonly agentId: string;\n readonly workspaceId: string;\n readonly handlers: TaskStreamHandlers;\n readonly logger?: TaskStreamLogger;\n /** Injected in tests so the stream can be exercised without a broker. */\n readonly publisher?: StreamPublisher;\n readonly subscriber?: StreamSubscriber;\n /** Injected in tests; the default creates the topics on the real broker. */\n readonly ensureTopics?: (config: StreamConfig) => Promise<void>;\n}\n\n/**\n * The agent's side of the Kafka transport.\n *\n * Reports and page results leave through the publisher; commands arrive on a\n * consumer group private to this agent. The group is what makes an offer\n * durable: a command produced while the agent is offline is still there when it\n * reconnects, whereas the old socket could only replay what the control plane\n * remembered to resend.\n */\nexport class TaskStream {\n private readonly publisher: StreamPublisher;\n private readonly subscriber: StreamSubscriber;\n private readonly handlers: TaskStreamHandlers;\n private readonly logger: TaskStreamLogger;\n private readonly prepareTopics: (config: StreamConfig) => Promise<void>;\n private connected = false;\n\n constructor(private readonly options: TaskStreamOptions) {\n this.publisher =\n options.publisher ?? new KafkaPublisher(options.config, options.logger);\n this.subscriber =\n options.subscriber ??\n new KafkaSubscriber(options.config, agentConsumerGroup(options.agentId), {\n fromBeginning: true,\n logger: options.logger,\n });\n this.handlers = options.handlers;\n this.prepareTopics =\n options.ensureTopics ??\n ((config) =>\n ensureTopics(config, [\n STREAM_TOPICS.commands,\n STREAM_TOPICS.reports,\n STREAM_TOPICS.results,\n ]));\n this.logger = options.logger ?? {\n info: () => {},\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public get publishedCount(): number {\n return this.publisher.publishedCount;\n }\n\n /**\n * Connects both sides before anything is produced.\n *\n * The subscriber connects first in spirit as well as in order: a command\n * published between \"agent is online\" and \"agent is consuming\" would still be\n * delivered later, but a producer that is not connected silently rejects\n * every report it is handed.\n */\n public async connect(): Promise<void> {\n if (this.connected) return;\n await this.subscriber.connect();\n try {\n await this.publisher.connect();\n // A fresh broker has no topics; creating them before subscribing avoids\n // the metadata race that would otherwise look like an unavailable broker.\n await this.prepareTopics(this.options.config);\n await this.subscriber.subscribe([STREAM_TOPICS.commands], (message) =>\n this.receive(message),\n );\n } catch (error) {\n await this.subscriber.disconnect().catch(() => {});\n await this.publisher.disconnect().catch(() => {});\n throw error;\n }\n this.connected = true;\n }\n\n /**\n * Publishes one execution report.\n *\n * Returns false when the stream is not connected, which the executor already\n * treats as a transient gap. A publish failure after acceptance is logged,\n * not thrown: the lease will expire and the control plane will reclaim the\n * task, which is the same outcome as a socket write that never arrived.\n */\n public report(message: AgentTaskClientMessage): boolean {\n if (!this.connected) return false;\n\n const envelope: StreamEnvelope<AgentTaskClientMessage> = {\n envelope: 1,\n kind: 'report',\n agentId: this.options.agentId,\n workspaceId: this.options.workspaceId,\n sentAt: Date.now(),\n payload: message,\n };\n\n // Keyed by task: one task's ack/progress/complete stay in order even when\n // several jobs on this agent publish at once.\n void this.publisher\n .publish(STREAM_TOPICS.reports, message.taskId, encodeEnvelope(envelope))\n .catch((error: unknown) => {\n this.logger.error(\n `Could not publish ${message.type} for task ${message.taskId}: ${(error as Error).message}`,\n );\n });\n return true;\n }\n\n /**\n * Streams one observed page while the crawl is still running.\n *\n * Pages share the topic with reports and are keyed by task, so the completion\n * that follows them lands in the same partition and can never overtake them.\n */\n public publishPage(page: CrawlPageResult): boolean {\n if (!this.connected) return false;\n\n const envelope: StreamEnvelope<CrawlPageResult> = {\n envelope: 1,\n kind: 'result',\n agentId: this.options.agentId,\n workspaceId: this.options.workspaceId,\n sentAt: Date.now(),\n payload: page,\n };\n\n void this.publisher\n .publish(STREAM_TOPICS.reports, page.taskId, encodeEnvelope(envelope))\n .catch((error: unknown) => {\n this.logger.warn(\n `Could not publish page ${page.sequence} of task ${page.taskId}: ${(error as Error).message}`,\n );\n });\n return true;\n }\n\n /** Waits until every accepted record was acknowledged by the broker. */\n public async flush(): Promise<void> {\n await this.publisher.flush();\n }\n\n public async close(): Promise<void> {\n if (!this.connected) {\n await this.publisher.disconnect().catch(() => {});\n await this.subscriber.disconnect().catch(() => {});\n return;\n }\n this.connected = false;\n // Flush before disconnecting, or a completion queued during shutdown is\n // dropped and the task sits RUNNING until its lease expires.\n await this.flush().catch((error: unknown) => {\n this.logger.error(`Could not flush the task stream: ${(error as Error).message}`);\n });\n await this.subscriber.disconnect();\n await this.publisher.disconnect();\n }\n\n private async receive(message: StreamMessage): Promise<void> {\n const envelope = decodeEnvelope<AgentTaskServerMessage>(message.value, 'task');\n\n // The group is private to this agent, so a foreign envelope means a\n // misconfigured producer, not a message for us. Ignoring it is safer than\n // executing a task this agent was never assigned.\n if (envelope.agentId !== this.options.agentId) {\n this.logger.warn(\n `Ignoring a ${envelope.payload.type} record addressed to agent ${envelope.agentId}.`,\n );\n return;\n }\n\n const payload = envelope.payload;\n switch (payload.type) {\n case 'task.offer':\n this.handlers.onOffer(payload);\n return;\n case 'task.cancel':\n this.handlers.onCancel(payload);\n return;\n case 'task.pause':\n this.handlers.onPause(payload);\n return;\n case 'task.renewed':\n this.handlers.onRenewed(payload);\n return;\n case 'task.nack':\n this.handlers.onNack(payload);\n return;\n default: {\n // A newer server may send a command this build does not know. Retrying\n // it would block every later command on this agent's partition, and it\n // can never succeed, so it is logged and dropped. The durable task row\n // is unaffected; the lease sweep is the backstop.\n const unknown = payload as { type?: unknown };\n this.logger.warn(`Ignoring an unknown task command: ${String(unknown.type)}.`);\n return;\n }\n }\n }\n}\n","/**\n * Deterministic test job executed by the M3 agent.\n *\n * It intentionally touches no network and no browser. Its purpose is to prove\n * the execution pipeline end-to-end: lease acknowledgement, progress, durable\n * checkpoints, cancellation, timeout and completion reporting. Real browser\n * exploration arrives with the isolated worker in M4.\n */\n\nexport interface TestJobContext {\n readonly signal: AbortSignal;\n readonly reportProgress: (percent: number, message: string) => void;\n readonly checkpoint: (label: string, state: Record<string, unknown>) => void;\n readonly sleep: (ms: number) => Promise<void>;\n}\n\nexport interface TestJobResult {\n readonly steps: number;\n readonly completedSteps: number;\n readonly durationMs: number;\n}\n\nexport interface TestJobOptions {\n readonly steps?: number;\n readonly stepDelayMs?: number;\n}\n\nexport const DEFAULT_TEST_JOB_STEPS = 5;\nexport const DEFAULT_TEST_STEP_DELAY_MS = 200;\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n const error = new Error('Job aborted.');\n error.name = 'AbortError';\n throw error;\n}\n\n/**\n * Runs a fixed number of steps with deterministic progress. The checkpoint is\n * written once, in the middle, so recovery has a meaningful recovery point\n * without pretending the job has real state to restore.\n */\nexport async function runTestJob(\n context: TestJobContext,\n options: TestJobOptions = {},\n): Promise<TestJobResult> {\n const steps = Math.max(1, options.steps ?? DEFAULT_TEST_JOB_STEPS);\n const stepDelayMs = Math.max(0, options.stepDelayMs ?? DEFAULT_TEST_STEP_DELAY_MS);\n const startedAt = Date.now();\n let completedSteps = 0;\n\n for (let step = 1; step <= steps; step++) {\n throwIfAborted(context.signal);\n\n await context.sleep(stepDelayMs);\n throwIfAborted(context.signal);\n\n completedSteps = step;\n const percent = Math.min(95, Math.round((step / steps) * 90));\n context.reportProgress(percent, `step ${step}/${steps}`);\n\n if (step === Math.ceil(steps / 2)) {\n context.checkpoint('test-job-halfway', {\n step,\n totalSteps: steps,\n completedSteps,\n });\n }\n }\n\n context.reportProgress(99, 'finalizing');\n return {\n steps,\n completedSteps,\n durationMs: Date.now() - startedAt,\n };\n}\n","import type {\n AgentTaskCancelMessage,\n AgentTaskCheckpointMessage,\n AgentTaskClientMessage,\n AgentTaskCompleteMessage,\n AgentTaskFailMessage,\n AgentTaskNackMessage,\n AgentTaskOfferMessage,\n AgentTaskPauseMessage,\n AgentTaskProgressMessage,\n AgentTaskRenewMessage,\n AgentTaskRenewedMessage,\n ExplorationOpenApiSpec,\n ExplorationReport,\n ExplorationTask,\n} from '@luxray/shared';\nimport { runTestJob } from './test-job.js';\n\nexport interface TaskExecutorLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/** What a job implementation may use while it runs. */\nexport interface JobExecutionContext {\n readonly signal: AbortSignal;\n readonly reportProgress: (percent: number, message: string) => void;\n readonly checkpoint: (label: string, state: Record<string, unknown>) => void;\n readonly sleep: (ms: number) => Promise<void>;\n}\n\n/**\n * What an exploration run hands back.\n *\n * The summary is free-form and lands in the task history; the report is the\n * typed outcome and rides in the completion frame, so the control plane stores\n * it atomically with the COMPLETED status.\n */\nexport interface ExplorationJobResult {\n readonly summary: Record<string, unknown>;\n readonly report: ExplorationReport;\n /**\n * Specifications generated from captured traffic, omitted when the crawl saw\n * no API traffic or the documents exceeded the transport budget.\n */\n readonly openApi?: ExplorationOpenApiSpec;\n}\n\n/**\n * Executes one `EXPLORATION` job. Injected rather than imported so the executor\n * keeps no browser dependency: the CLI supplies the isolated browser worker.\n */\nexport type ExplorationJobRunner = (\n execution: JobExecutionContext,\n task: ExplorationTask,\n) => Promise<ExplorationJobResult>;\n\nexport type JobOutcome = 'completed' | 'failed' | 'stopped';\n\n/** Result of waiting for a specific task to start executing locally. */\nexport type JobStartOutcome = 'started' | 'timeout';\n\n/** How a job ended, for callers that drive one task at a time. */\nexport interface JobFinishedInfo {\n readonly taskId: string;\n readonly leaseId: string;\n readonly jobType: string;\n readonly outcome: JobOutcome;\n readonly stopReason: StopReason | null;\n readonly error: string | null;\n}\n\nexport interface TaskExecutorOptions {\n readonly agentId: string;\n /** Transport sink. Returns false when the socket is not currently usable. */\n readonly send: (message: AgentTaskClientMessage) => boolean;\n /** Jobs this process will run at once. M3 defaults to a single job. */\n readonly maxConcurrentJobs?: number;\n /** Hard limit for one job; exceeding it fails the task. */\n readonly maxJobDurationMs?: number;\n /** Hard limit for one exploration job; browsers are slower than test jobs. */\n readonly explorationMaxDurationMs?: number;\n /** Minimum gap between progress frames. */\n readonly progressIntervalMs?: number;\n /** Overrides lease-based renewal interval. */\n readonly leaseRenewIntervalMs?: number;\n /** Largest checkpoint payload the transport will carry. */\n readonly checkpointMaxBytes?: number;\n /** Runs `EXPLORATION` offers. Without it, exploration fails honestly. */\n readonly explorationRunner?: ExplorationJobRunner;\n /** Fires exactly once per job, whatever the ending was. */\n readonly onJobFinished?: (info: JobFinishedInfo) => void;\n readonly testSteps?: number;\n readonly testStepDelayMs?: number;\n readonly now?: () => number;\n readonly logger?: TaskExecutorLogger;\n}\n\ntype StopReason = 'cancel' | 'pause' | 'superseded' | 'fenced' | 'timeout' | 'shutdown';\n\ninterface StartWaiter {\n readonly resolve: (outcome: JobStartOutcome) => void;\n timer: NodeJS.Timeout | null;\n}\n\ninterface ActiveJob {\n readonly key: string;\n readonly leaseId: string;\n readonly taskId: string;\n readonly offer: AgentTaskOfferMessage;\n readonly controller: AbortController;\n leaseExpiresAt: number;\n stopReason: StopReason | null;\n settled: boolean;\n outcome: JobOutcome | null;\n outcomeError: string | null;\n lastProgressAt: number;\n lastPercentSent: number;\n pendingProgress: { percent: number; message: string } | null;\n progressTimer: NodeJS.Timeout | null;\n renewTimer: NodeJS.Timeout | null;\n timeoutTimer: NodeJS.Timeout | null;\n}\n\nconst DEFAULT_MAX_CONCURRENT_JOBS = 1;\nconst DEFAULT_MAX_JOB_DURATION_MS = 120_000;\nconst DEFAULT_EXPLORATION_MAX_DURATION_MS = 10 * 60_000;\nconst DEFAULT_PROGRESS_INTERVAL_MS = 1_000;\nconst DEFAULT_CHECKPOINT_MAX_BYTES = 16 * 1024;\nconst MIN_RENEW_INTERVAL_MS = 1_000;\nconst MAX_RENEW_INTERVAL_MS = 60_000;\nconst MAX_ERROR_LENGTH = 2_000;\n\n/**\n * Owns local execution state for assigned jobs.\n *\n * The server is authoritative for leases and lifecycle. This class keeps only\n * what it needs to run work safely: a per-lease dedupe key, an abort signal,\n * throttled progress, and a renewal timer. It deliberately performs no\n * autonomous exploration.\n */\nexport class TaskExecutor {\n private readonly maxConcurrentJobs: number;\n private readonly maxJobDurationMs: number;\n private readonly explorationMaxDurationMs: number;\n private readonly progressIntervalMs: number;\n private readonly leaseRenewIntervalMs: number | null;\n private readonly checkpointMaxBytes: number;\n private readonly explorationRunner: ExplorationJobRunner | null;\n private readonly testSteps: number | undefined;\n private readonly testStepDelayMs: number | undefined;\n private readonly now: () => number;\n private readonly logger: TaskExecutorLogger;\n\n private readonly running = new Map<string, ActiveJob>();\n private readonly runs = new Map<string, Promise<void>>();\n private readonly queued: AgentTaskOfferMessage[] = [];\n /** Tasks this process has accepted a lease for, used by `waitForJobStarted`. */\n private readonly startedTaskIds = new Set<string>();\n private readonly startWaiters = new Map<string, StartWaiter[]>();\n private shuttingDown = false;\n\n constructor(private readonly options: TaskExecutorOptions) {\n this.maxConcurrentJobs = clampInt(options.maxConcurrentJobs ?? DEFAULT_MAX_CONCURRENT_JOBS, 1, 16);\n this.maxJobDurationMs = Math.max(1, options.maxJobDurationMs ?? DEFAULT_MAX_JOB_DURATION_MS);\n this.explorationMaxDurationMs = Math.max(\n 1,\n options.explorationMaxDurationMs ?? DEFAULT_EXPLORATION_MAX_DURATION_MS,\n );\n this.progressIntervalMs = Math.max(0, options.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS);\n this.leaseRenewIntervalMs = options.leaseRenewIntervalMs ?? null;\n this.checkpointMaxBytes = Math.max(\n 256,\n options.checkpointMaxBytes ?? DEFAULT_CHECKPOINT_MAX_BYTES,\n );\n this.explorationRunner = options.explorationRunner ?? null;\n this.testSteps = options.testSteps;\n this.testStepDelayMs = options.testStepDelayMs;\n this.now = options.now ?? Date.now;\n this.logger = options.logger ?? {\n info: (...args) => console.log('[TaskExecutor]', ...args),\n warn: (...args) => console.warn('[TaskExecutor:WARN]', ...args),\n error: (...args) => console.error('[TaskExecutor:ERROR]', ...args),\n debug: () => {},\n };\n }\n\n public getRunningJobCount(): number {\n return this.running.size;\n }\n\n public getQueuedJobCount(): number {\n return this.queued.length;\n }\n\n /**\n * Resolves once this process has begun executing `taskId`, or with\n * `'timeout'` when no offer arrives within `timeoutMs`.\n *\n * This bounds the handoff only, never the work: a crawl of a heavy site\n * legitimately takes minutes, and its own limits decide when to give up. The\n * already-started set is checked first because an offer can be acknowledged\n * before the caller learns the task id, so a bare timer would race.\n */\n public waitForJobStarted(taskId: string, timeoutMs: number): Promise<JobStartOutcome> {\n if (this.startedTaskIds.has(taskId)) return Promise.resolve('started');\n\n return new Promise<JobStartOutcome>((resolve) => {\n const waiter: StartWaiter = { resolve, timer: null };\n waiter.timer = setTimeout(\n () => this.settleStartWaiter(taskId, waiter, 'timeout'),\n Math.max(0, timeoutMs),\n );\n waiter.timer.unref?.();\n\n const waiters = this.startWaiters.get(taskId) ?? [];\n waiters.push(waiter);\n this.startWaiters.set(taskId, waiters);\n });\n }\n\n /** Accepts an offer. Duplicate offers for the same lease are acknowledged twice. */\n public handleOffer(offer: AgentTaskOfferMessage): void {\n if (this.shuttingDown) return;\n\n if (offer.leaseExpiresAt <= this.now()) {\n this.logger.warn(\n `Ignoring expired offer for task ${offer.task.id} (lease ${offer.leaseId}).`,\n );\n return;\n }\n\n const key = this.jobKey(offer.task.id, offer.leaseId);\n const existing = this.running.get(key);\n if (existing) {\n // At-least-once delivery after a reconnect: acknowledge again, never run\n // the same lease twice in this process.\n this.sendAck(offer);\n return;\n }\n\n if (this.queued.some((entry) => this.jobKey(entry.task.id, entry.leaseId) === key)) {\n return;\n }\n\n if (this.running.size >= this.maxConcurrentJobs) {\n this.queued.push(offer);\n this.logger.info(\n `Queued task ${offer.task.id}; ${this.running.size}/${this.maxConcurrentJobs} jobs active.`,\n );\n return;\n }\n\n this.start(offer);\n }\n\n public handleCancel(message: AgentTaskCancelMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId !== message.taskId) continue;\n if (message.leaseId !== null && message.leaseId !== job.leaseId) continue;\n this.stop(job, 'cancel');\n }\n }\n\n public handlePause(message: AgentTaskPauseMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId === message.taskId) this.stop(job, 'pause');\n }\n }\n\n public handleNack(message: AgentTaskNackMessage): void {\n // A retryable rejection is a transient action failure; keep executing and\n // let the next progress frame or renewal retry. Fencing is final.\n if (message.retryable) {\n this.logger.debug(\n `Task ${message.taskId}: ${message.code} — ${message.message} (retryable, still running).`,\n );\n return;\n }\n\n this.logger.warn(\n `Task ${message.taskId} rejected by the control plane: ${message.code} — ${message.message}`,\n );\n\n for (const job of this.running.values()) {\n if (job.taskId !== message.taskId) continue;\n if (message.leaseId !== null && message.leaseId !== job.leaseId) continue;\n this.stop(job, 'fenced');\n }\n }\n\n public handleRenewed(message: AgentTaskRenewedMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId === message.taskId && job.leaseId === message.leaseId) {\n job.leaseExpiresAt = message.leaseExpiresAt;\n }\n }\n }\n\n /**\n * Fails every in-flight job with an operator-supplied reason, then stops it.\n *\n * `shutdown()` alone leaves the server to reclaim the task when the lease\n * expires, which is right for an abrupt exit but wrong for Ctrl+C: the\n * operator deliberately stopped the run, and the task history should say so\n * immediately instead of waiting out the lease.\n */\n public failActiveJobs(reason: string): void {\n for (const job of [...this.running.values()]) {\n if (job.settled) continue;\n this.sendFailure(job, reason);\n this.stop(job, 'shutdown');\n }\n }\n\n /** Stops everything and waits for in-flight jobs to unwind. */\n public async shutdown(): Promise<void> {\n this.shuttingDown = true;\n this.queued.length = 0;\n\n for (const job of [...this.running.values()]) {\n this.stop(job, 'shutdown');\n }\n\n await Promise.allSettled([...this.runs.values()]);\n }\n\n /** Records a start and wakes anyone watching for this task. */\n private noteJobStarted(taskId: string): void {\n this.startedTaskIds.add(taskId);\n\n const waiters = this.startWaiters.get(taskId);\n if (!waiters) return;\n this.startWaiters.delete(taskId);\n\n for (const waiter of waiters) {\n if (waiter.timer) {\n clearTimeout(waiter.timer);\n waiter.timer = null;\n }\n waiter.resolve('started');\n }\n }\n\n private settleStartWaiter(\n taskId: string,\n waiter: StartWaiter,\n outcome: JobStartOutcome,\n ): void {\n if (waiter.timer) {\n clearTimeout(waiter.timer);\n waiter.timer = null;\n }\n\n const waiters = this.startWaiters.get(taskId);\n if (waiters) {\n const index = waiters.indexOf(waiter);\n if (index >= 0) waiters.splice(index, 1);\n if (waiters.length === 0) this.startWaiters.delete(taskId);\n }\n\n waiter.resolve(outcome);\n }\n\n private start(offer: AgentTaskOfferMessage): void {\n const job: ActiveJob = {\n key: this.jobKey(offer.task.id, offer.leaseId),\n leaseId: offer.leaseId,\n taskId: offer.task.id,\n offer,\n controller: new AbortController(),\n leaseExpiresAt: offer.leaseExpiresAt,\n stopReason: null,\n settled: false,\n outcome: null,\n outcomeError: null,\n lastProgressAt: 0,\n lastPercentSent: 0,\n pendingProgress: null,\n progressTimer: null,\n renewTimer: null,\n timeoutTimer: null,\n };\n\n this.running.set(job.key, job);\n this.noteJobStarted(job.taskId);\n this.sendAck(offer);\n this.startRenewal(job);\n\n job.timeoutTimer = setTimeout(() => {\n this.stop(job, 'timeout');\n }, this.jobDurationLimitMs(offer.task.jobType));\n job.timeoutTimer.unref?.();\n\n this.logger.info(\n `Starting ${offer.task.jobType} task ${offer.task.id} (lease ${offer.leaseId}, attempt ${offer.attempt}).`,\n );\n\n const run = this.execute(job).finally(() => {\n this.settle(job);\n });\n this.runs.set(job.key, run);\n }\n\n private async execute(job: ActiveJob): Promise<void> {\n try {\n const jobType = job.offer.task.jobType;\n\n if (jobType === 'TEST') {\n const result = await runTestJob(this.jobContext(job), {\n steps: this.testSteps,\n stepDelayMs: this.testStepDelayMs,\n });\n\n if (job.stopReason !== null) return;\n\n this.sendCompletion(job, {\n jobType,\n steps: result.steps,\n completedSteps: result.completedSteps,\n durationMs: result.durationMs,\n });\n this.logger.info(`Task ${job.taskId} completed in ${result.durationMs}ms.`);\n return;\n }\n\n if (jobType === 'EXPLORATION') {\n if (!this.explorationRunner) {\n this.sendFailure(\n job,\n 'This agent build has no exploration runner installed, so it cannot execute EXPLORATION jobs.',\n );\n return;\n }\n\n const startedAt = this.now();\n const { summary, report, openApi } = await this.explorationRunner(\n this.jobContext(job),\n job.offer.task,\n );\n if (job.stopReason !== null) return;\n\n this.sendCompletion(\n job,\n {\n jobType,\n durationMs: this.now() - startedAt,\n ...summary,\n },\n report,\n openApi,\n );\n this.logger.info(\n `Exploration task ${job.taskId} completed in ${this.now() - startedAt}ms.`,\n );\n return;\n }\n\n this.sendFailure(\n job,\n `Job type ${String(jobType)} is not executable by this agent build.`,\n );\n } catch (err) {\n if (job.stopReason === 'timeout') {\n this.sendFailure(\n job,\n `Job exceeded the local ${this.jobDurationLimitMs(job.offer.task.jobType)}ms execution limit.`,\n );\n return;\n }\n if (job.stopReason !== null || job.controller.signal.aborted) {\n this.logger.debug(`Task ${job.taskId} stopped (${job.stopReason ?? 'aborted'}).`);\n return;\n }\n this.sendFailure(job, this.errorMessage(err));\n }\n }\n\n private sendCompletion(\n job: ActiveJob,\n summary: Record<string, unknown>,\n report?: ExplorationReport,\n openApi?: ExplorationOpenApiSpec,\n ): void {\n const message: AgentTaskCompleteMessage = {\n ...this.base(),\n type: 'task.complete',\n taskId: job.taskId,\n leaseId: job.leaseId,\n summary,\n ...(report ? { report } : {}),\n ...(openApi ? { openApi } : {}),\n };\n if (!this.send(message)) {\n // Silently claiming success while the report never left the process is\n // the worst possible failure mode; make it visible.\n this.logger.warn(\n `Could not report completion for task ${job.taskId}: the transport is closed. ` +\n 'The lease will expire and the queue will decide what happens next.',\n );\n }\n if (job.outcome === null) job.outcome = 'completed';\n }\n\n private jobDurationLimitMs(jobType: string): number {\n return jobType === 'EXPLORATION' ? this.explorationMaxDurationMs : this.maxJobDurationMs;\n }\n\n private jobContext(job: ActiveJob): JobExecutionContext {\n return {\n signal: job.controller.signal,\n reportProgress: (percent, message) => this.reportProgress(job, percent, message),\n checkpoint: (label, state) => this.reportCheckpoint(job, label, state),\n sleep: (ms) => this.sleep(ms, job.controller.signal),\n };\n }\n\n /** Abortable delay so cancellation and timeout do not wait for a step. */\n private sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(abortError());\n return;\n }\n\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(abortError());\n };\n\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n private reportProgress(job: ActiveJob, percent: number, message: string): void {\n if (job.settled || job.stopReason !== null) return;\n\n // Progress is a monotonic contract: consumers assume a percentage never\n // moves backwards. A throttled flush must not resurrect an older value\n // after a newer direct send.\n const value = Math.max(0, Math.min(100, Math.round(percent)));\n if (value < job.lastPercentSent) return;\n\n const now = this.now();\n if (now - job.lastProgressAt < this.progressIntervalMs) {\n if (job.pendingProgress === null || value >= job.pendingProgress.percent) {\n job.pendingProgress = { percent: value, message };\n }\n if (!job.progressTimer) {\n job.progressTimer = setTimeout(() => {\n job.progressTimer = null;\n this.flushProgress(job);\n }, this.progressIntervalMs);\n job.progressTimer.unref?.();\n }\n return;\n }\n\n this.sendProgress(job, value, message);\n }\n\n private flushProgress(job: ActiveJob): void {\n if (job.settled || job.stopReason !== null) return;\n const pending = job.pendingProgress;\n if (!pending) return;\n this.sendProgress(job, pending.percent, pending.message);\n }\n\n private sendProgress(job: ActiveJob, percent: number, message: string): void {\n // A direct send supersedes anything queued for the throttle window.\n if (job.progressTimer) {\n clearTimeout(job.progressTimer);\n job.progressTimer = null;\n }\n job.pendingProgress = null;\n job.lastPercentSent = Math.max(job.lastPercentSent, percent);\n\n const progress: AgentTaskProgressMessage = {\n ...this.base(),\n type: 'task.progress',\n taskId: job.taskId,\n leaseId: job.leaseId,\n percent: job.lastPercentSent,\n message,\n };\n job.lastProgressAt = this.now();\n this.send(progress);\n }\n\n private reportCheckpoint(job: ActiveJob, label: string, state: Record<string, unknown>): void {\n if (job.settled || job.stopReason !== null) return;\n\n const serialized = JSON.stringify(state);\n if (Buffer.byteLength(serialized, 'utf8') > this.checkpointMaxBytes) {\n this.logger.warn(\n `Skipping checkpoint \"${label}\" for task ${job.taskId}: exceeds ${this.checkpointMaxBytes} bytes.`,\n );\n return;\n }\n\n const message: AgentTaskCheckpointMessage = {\n ...this.base(),\n type: 'task.checkpoint',\n taskId: job.taskId,\n leaseId: job.leaseId,\n label,\n state,\n };\n this.send(message);\n }\n\n private sendAck(offer: AgentTaskOfferMessage): void {\n this.send({\n ...this.base(),\n type: 'task.ack',\n taskId: offer.task.id,\n leaseId: offer.leaseId,\n });\n }\n\n private sendFailure(job: ActiveJob, error: string): void {\n const message: AgentTaskFailMessage = {\n ...this.base(),\n type: 'task.fail',\n taskId: job.taskId,\n leaseId: job.leaseId,\n error: error.slice(0, MAX_ERROR_LENGTH),\n };\n if (!this.send(message)) {\n this.logger.warn(\n `Could not report failure for task ${job.taskId}: the transport is closed. ` +\n 'The lease will expire and the queue will decide what happens next.',\n );\n }\n this.logger.warn(`Task ${job.taskId} failed: ${message.error}`);\n if (job.outcome === null) {\n job.outcome = 'failed';\n job.outcomeError = message.error;\n }\n }\n\n private startRenewal(job: ActiveJob): void {\n const interval =\n this.leaseRenewIntervalMs ??\n clampInt(\n Math.floor((job.leaseExpiresAt - this.now()) / 3),\n MIN_RENEW_INTERVAL_MS,\n MAX_RENEW_INTERVAL_MS,\n );\n\n job.renewTimer = setInterval(() => {\n if (job.settled || job.stopReason !== null) return;\n const message: AgentTaskRenewMessage = {\n ...this.base(),\n type: 'task.renew',\n taskId: job.taskId,\n leaseId: job.leaseId,\n };\n this.send(message);\n }, interval);\n job.renewTimer.unref?.();\n }\n\n private stop(job: ActiveJob, reason: StopReason): void {\n if (job.settled) return;\n // Timeout and fencing are terminal; they must not be overwritten by a late\n // cancel frame for the same job.\n if (job.stopReason === null) {\n job.stopReason = reason;\n this.logger.info(`Stopping task ${job.taskId}: ${reason}.`);\n }\n job.controller.abort();\n }\n\n private settle(job: ActiveJob): void {\n if (job.settled) return;\n job.settled = true;\n\n if (job.progressTimer) {\n clearTimeout(job.progressTimer);\n job.progressTimer = null;\n }\n if (job.renewTimer) {\n clearInterval(job.renewTimer);\n job.renewTimer = null;\n }\n if (job.timeoutTimer) {\n clearTimeout(job.timeoutTimer);\n job.timeoutTimer = null;\n }\n\n this.running.delete(job.key);\n this.runs.delete(job.key);\n\n try {\n this.options.onJobFinished?.({\n taskId: job.taskId,\n leaseId: job.leaseId,\n jobType: job.offer.task.jobType,\n outcome: job.outcome ?? 'stopped',\n stopReason: job.stopReason,\n error: job.outcomeError,\n });\n } catch (err) {\n this.logger.warn(`onJobFinished listener failed: ${(err as Error).message}`);\n }\n\n this.pump();\n }\n\n private pump(): void {\n if (this.shuttingDown) return;\n\n while (this.running.size < this.maxConcurrentJobs && this.queued.length > 0) {\n const next = this.queued.shift();\n if (!next) return;\n\n if (next.leaseExpiresAt <= this.now()) {\n this.logger.warn(`Dropping queued offer for task ${next.task.id}: lease expired.`);\n continue;\n }\n if (this.running.has(this.jobKey(next.task.id, next.leaseId))) continue;\n\n this.start(next);\n }\n }\n\n private send(message: AgentTaskClientMessage): boolean {\n try {\n return this.options.send(message);\n } catch (err) {\n this.logger.warn(`Failed to send ${message.type}: ${(err as Error).message}`);\n return false;\n }\n }\n\n private base(): { version: '1.0'; agentId: string; timestamp: number } {\n return {\n version: '1.0',\n agentId: this.options.agentId,\n timestamp: Date.now(),\n };\n }\n\n private jobKey(taskId: string, leaseId: string): string {\n return `${taskId}:${leaseId}`;\n }\n\n private errorMessage(err: unknown): string {\n if (err instanceof Error && err.message.trim().length > 0) return err.message;\n return 'Unknown execution error.';\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min;\n return Math.max(min, Math.min(max, Math.trunc(value)));\n}\n\nfunction abortError(): Error {\n const error = new Error('Job aborted.');\n error.name = 'AbortError';\n return error;\n}\n","import { createHash } from 'node:crypto';\nimport { join } from 'node:path';\nimport type {\n CrawlPageResult,\n ExplorationOpenApiSpec,\n ExplorationReport,\n ExplorationTask,\n} from '@luxray/shared';\nimport type { ExplorationWorker, ExplorationOutcome, PageObservation } from '@luxray/exploration-worker';\nimport { DEFAULT_EXPLORATION_LIMITS } from '@luxray/exploration-worker';\nimport {\n applyOpenApiTransportBudget,\n generateOpenApiSpec,\n writeOpenApiArtifacts,\n} from './openapi-spec.js';\nimport type { ExplorationJobResult, ExplorationJobRunner } from './task-executor.js';\n\n/**\n * Operator-supplied sign-in for crawls started from this terminal.\n *\n * These values are never sent to the control plane: the task row records that a\n * sign-in happened, not how. `appliesTo` exists because this agent can be handed\n * unrelated queued tasks, and those must never inherit the operator's password.\n */\nexport interface ExploreAuthOptions {\n /** Form sign-in: proposed in a dedicated page before the crawl starts. */\n readonly credentials?: {\n readonly username: string;\n readonly password: string;\n };\n /** Arbitrary request headers; the general case for bearer tokens/API keys. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cookies installed on the task context before the first navigation. */\n readonly cookies?: readonly { readonly name: string; readonly value: string }[];\n /** Page that renders the sign-in form; defaults to the task's start URL. */\n readonly loginUrl?: string;\n readonly submitTimeoutMs?: number;\n /** Resolves once the operator finished a captcha/2FA sign-in by hand. */\n readonly manualAssist?: () => Promise<void>;\n /** Restore a saved session instead of signing in. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n /**\n * Only tasks this predicate accepts may use the session. Defaults to all.\n *\n * Async because the offer can reach the agent before the request that created\n * the task returns its id; a caller that has to wait for that id can do so\n * here instead of racing it.\n */\n readonly appliesTo?: (taskId: string) => boolean | Promise<boolean>;\n}\n\nexport interface ExplorationRunnerOptions {\n /** Directory that receives one subdirectory per task. */\n readonly artifactRoot: string;\n readonly headless?: boolean;\n readonly includeSecrets?: boolean;\n /** Sign-in material for tasks that may use it. */\n readonly auth?: ExploreAuthOptions;\n /**\n * Receives each page as the crawl observes it, not at the end.\n *\n * The executor publishes this to the results stream so a long crawl is\n * inspectable while it runs; the run summary is still the terminal report.\n */\n readonly onPage?: (page: CrawlPageResult) => void;\n readonly onFinished?: (result: {\n readonly taskId: string;\n readonly startUrl: string;\n readonly outcome: ExplorationOutcome;\n }) => void;\n readonly logger?: {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n };\n}\n\n/**\n * Adapts the isolated browser worker to the task executor.\n *\n * The task's stored scope is the authority for what may be crawled; the local\n * defaults only fill in operational limits the control plane does not store\n * (timeouts, checkpoint cadence).\n */\nexport function createExplorationRunner(\n worker: ExplorationWorker,\n options: ExplorationRunnerOptions,\n): ExplorationJobRunner {\n return async (execution, task: ExplorationTask): Promise<ExplorationJobResult> => {\n const scope = task.scope ?? {};\n const allowedDomains =\n scope.allowedDomains && scope.allowedDomains.length > 0\n ? scope.allowedDomains\n : [new URL(task.startUrl).hostname];\n\n const maySignIn = options.auth ? await (options.auth.appliesTo?.(task.id) ?? true) : false;\n const auth = maySignIn ? options.auth ?? null : null;\n\n // The digest must describe the page set the control plane stores, which is\n // keyed by URL. A URL re-observed later supersedes the earlier row, so the\n // collector keeps the last observation and the report is built from that.\n const emitted = new Map<string, CrawlPageResult>();\n\n const outcome = await worker.explore({\n startUrl: task.startUrl,\n scope: {\n allowedDomains,\n includeSubdomains: scope.includeSubdomains ?? false,\n },\n limits: {\n maxPages: scope.maxPages ?? DEFAULT_EXPLORATION_LIMITS.maxPages,\n maxDepth: scope.maxDepth ?? DEFAULT_EXPLORATION_LIMITS.maxDepth,\n },\n artifactDir: join(options.artifactRoot, task.id),\n headless: options.headless ?? true,\n includeSecrets: options.includeSecrets,\n ...(auth?.storageStatePath ? { storageStatePath: auth.storageStatePath } : {}),\n ...(auth?.saveStorageStatePath ? { saveStorageStatePath: auth.saveStorageStatePath } : {}),\n ...(auth && (auth.credentials || auth.headers || auth.cookies)\n ? {\n auth: {\n ...(auth.credentials ? { credentials: auth.credentials } : {}),\n ...(auth.headers ? { headers: auth.headers } : {}),\n ...(auth.cookies ? { cookies: auth.cookies } : {}),\n loginUrl: auth.loginUrl,\n submitTimeoutMs: auth.submitTimeoutMs,\n manualAssist: auth.manualAssist,\n },\n }\n : {}),\n signal: execution.signal,\n onProgress: execution.reportProgress,\n onCheckpoint: execution.checkpoint,\n // Always collect, even when nobody subscribed: the report's digest and\n // page count have to describe what the run emitted, not what a caller\n // happened to forward.\n onPage: (observed: PageObservation, sequence: number) => {\n const page = toPageResult(task, observed, sequence);\n emitted.set(page.url, page);\n options.onPage?.(page);\n },\n logger: options.logger,\n });\n\n options.onFinished?.({ taskId: task.id, startUrl: task.startUrl, outcome });\n\n const pages = [...emitted.values()].sort((a, b) => a.sequence - b.sequence);\n const summary = outcome.run.summary;\n\n // Specification generation is best effort: a crawl that observed API\n // traffic should not fail because the document could not be synthesized or\n // written. The report and the pages are the execution of record.\n const { openApi, openApiSummary } = await buildOpenApi(task, outcome, options.logger);\n\n const report: ExplorationReport = {\n version: 1,\n taskId: task.id,\n attempt: task.attempts,\n outcome: 'completed',\n startUrl: summary.startUrl,\n startedAt: summary.startedAt,\n finishedAt: summary.finishedAt,\n durationMs: summary.durationMs,\n truncatedByLimit: summary.truncatedByLimit,\n limits: summary.limits,\n totals: {\n pagesVisited: summary.pagesVisited,\n pagesFailed: summary.pagesFailed,\n duplicatePages: summary.duplicatePages,\n authRequiredPages: pages.filter((page) => page.authRequired).length,\n transactionsCaptured: summary.transactionsCaptured,\n linksDiscovered: summary.linksDiscovered,\n frontierRemaining: summary.frontierRemaining,\n },\n authentication: summary.authentication ?? null,\n pageCount: pages.length,\n pageDigest: digestPages(pages),\n artifactDir: outcome.paths.dir,\n };\n\n return {\n summary: {\n ...summary,\n artifactDir: outcome.paths.dir,\n transactionsCaptured: outcome.transactionsCaptured,\n openApi: openApiSummary,\n },\n report,\n ...(openApi ? { openApi } : {}),\n };\n };\n}\n\n/**\n * Generates the specification and its artifacts without letting a failure in\n * this optional stage turn a completed crawl into a failed task.\n */\nasync function buildOpenApi(\n task: ExplorationTask,\n outcome: ExplorationOutcome,\n logger: ExplorationRunnerOptions['logger'],\n): Promise<{\n readonly openApi?: ExplorationOpenApiSpec;\n readonly openApiSummary: Record<string, unknown>;\n}> {\n try {\n const generated = generateOpenApiSpec({\n taskId: task.id,\n attempt: task.attempts,\n startUrl: task.startUrl,\n title: task.name,\n transactions: outcome.transactions ?? [],\n });\n\n if (!generated) {\n return {\n openApiSummary: { generated: false, reason: 'no-api-traffic' },\n };\n }\n\n try {\n await writeOpenApiArtifacts(outcome.paths.dir, generated);\n } catch (error) {\n logger?.warn(\n `Could not write OpenAPI artifacts for task ${task.id}: ${(error as Error).message}`,\n );\n }\n\n const payload = applyOpenApiTransportBudget(generated);\n return {\n openApi: payload,\n openApiSummary: {\n generated: true,\n endpointCount: payload.summary.endpointCount,\n schemaCount: payload.summary.schemaCount,\n relationshipCount: payload.summary.relationshipCount,\n jsonBytes: payload.summary.jsonBytes,\n yamlBytes: payload.summary.yamlBytes,\n omitted: payload.summary.omission !== null,\n },\n };\n } catch (error) {\n logger?.warn(\n `Could not generate an OpenAPI specification for task ${task.id}: ${(error as Error).message}`,\n );\n return {\n openApiSummary: { generated: false, reason: 'generation-failed' },\n };\n }\n}\n\n/**\n * Identity of a streamed page set: `sha256:<hex>` over `sequence:url` lines in\n * visit order.\n *\n * The digest lets the control plane tell a redelivered report from a second,\n * different execution of the same attempt without shipping the page manifest in\n * the completion frame.\n */\nexport function digestPages(\n pages: readonly { readonly sequence: number; readonly url: string }[],\n): string {\n const hash = createHash('sha256');\n for (const page of pages) hash.update(`${page.sequence}:${page.url}\\n`);\n return `sha256:${hash.digest('hex')}`;\n}\n\n/**\n * Narrows a worker observation to the stream record.\n *\n * The worker knows more than the control plane needs (`requestedUrl`,\n * `linksQueued`); the stream carries only what the dashboard displays, and the\n * task id comes from the execution rather than the page.\n */\nfunction toPageResult(\n task: ExplorationTask,\n page: PageObservation,\n sequence: number,\n): CrawlPageResult {\n return {\n taskId: task.id,\n // The agent's current attempt fences this observation on the server: a page\n // from an execution that was already requeued is stored nowhere.\n attempt: task.attempts,\n sequence,\n url: page.url,\n depth: page.depth,\n httpStatus: page.httpStatus,\n title: page.title,\n fingerprint: page.fingerprint,\n duplicateOf: page.duplicateOf,\n linksFound: page.linksFound,\n transactions: page.transactions,\n durationMs: page.durationMs,\n observedAt: page.observedAt,\n error: page.error,\n authRequired: page.authRequired,\n };\n}\n","import { join } from 'node:path';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport { writeRunArtifacts, type ArtifactPaths } from './artifacts/run-artifacts.js';\nimport { TaskBrowser } from './browser/task-browser.js';\nimport { DeterministicCrawler, type CrawlAuthOptions, type CrawlLogger } from './crawl/crawler.js';\nimport { ExplorationAbortedError } from './errors.js';\nimport {\n DEFAULT_EXPLORATION_LIMITS,\n type ExplorationLimits,\n type ExplorationRun,\n type PageObservation,\n} from './crawl/types.js';\nimport type { CrawlScope } from './crawl/url-policy.js';\n\nexport interface ExplorationRequest {\n readonly startUrl: string;\n readonly scope: CrawlScope;\n /** Overrides for the local limits; task scope still bounds page count/depth. */\n readonly limits?: Partial<ExplorationLimits>;\n /** Where `run.json`, `pages.json` and `transactions.json` are written. */\n readonly artifactDir: string;\n readonly headless?: boolean;\n /** Keep credential headers in the artifacts. Off by default. */\n readonly includeSecrets?: boolean;\n /** Session material to restore before the first page. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n /**\n * Sign in before crawling. Credentials stay in this process: the task row\n * records only that a sign-in happened, and the password is scrubbed from\n * anything written to disk.\n */\n readonly auth?: CrawlAuthOptions;\n readonly signal?: AbortSignal;\n readonly onProgress?: (percent: number, message: string) => void;\n readonly onCheckpoint?: (label: string, state: Record<string, unknown>) => void;\n /** Streams each observation out while the crawl is still running. */\n readonly onPage?: (page: PageObservation, sequence: number) => void;\n readonly logger?: CrawlLogger;\n}\n\nexport interface ExplorationOutcome {\n readonly run: ExplorationRun;\n readonly paths: ArtifactPaths;\n readonly transactionsCaptured: number;\n /**\n * Every transaction the run captured, for downstream intelligence.\n *\n * Kept on the outcome rather than only in `transactions.json` so the agent\n * can build the OpenAPI specification without re-reading an artifact it did\n * not write.\n */\n readonly transactions: readonly CapturedTransaction[];\n}\n\nconst HARD_PAGE_CAP = 1_000;\nconst HARD_DEPTH_CAP = 10;\n\n/**\n * Public entry point for isolated browser exploration.\n *\n * One instance owns the Chromium process and is meant to live for the whole\n * agent process; every `explore` call gets a fresh, isolated browser context and\n * a fresh artifact directory.\n */\nexport class ExplorationWorker {\n private readonly browser: TaskBrowser;\n private readonly defaultHeadless: boolean;\n private disposed = false;\n\n public constructor(options?: { headless?: boolean }) {\n this.defaultHeadless = options?.headless ?? true;\n this.browser = new TaskBrowser({ headless: this.defaultHeadless });\n }\n\n public async explore(request: ExplorationRequest): Promise<ExplorationOutcome> {\n if (this.disposed) {\n throw new Error('ExplorationWorker has been disposed.');\n }\n\n const limits = this.resolveLimits(request.limits);\n const crawler = new DeterministicCrawler(this.browser, {\n limits,\n scope: request.scope,\n signal: request.signal,\n onProgress: request.onProgress,\n onCheckpoint: request.onCheckpoint,\n onPage: request.onPage,\n logger: request.logger,\n auth: request.auth,\n storageStatePath: request.storageStatePath,\n saveStorageStatePath: request.saveStorageStatePath,\n });\n\n let outcome: { run: ExplorationRun; transactions: readonly CapturedTransaction[] };\n try {\n outcome = await crawler.run(request.startUrl);\n } catch (error) {\n if (error instanceof ExplorationAbortedError) throw error;\n if (request.signal?.aborted) throw new ExplorationAbortedError();\n\n // A Chromium crash loses the rendered state but not the task: relaunch and\n // run the deterministic crawl once more. Any other failure is reported.\n if (!this.browser.isConnected()) {\n request.logger?.warn('Browser process is gone; relaunching and retrying the run once.');\n await this.browser.ensureStarted();\n outcome = await crawler.run(request.startUrl);\n } else {\n throw error;\n }\n }\n\n const paths = await writeRunArtifacts(request.artifactDir, outcome, {\n includeSecrets: request.includeSecrets,\n // Known secrets never reach disk, even when the operator asked to keep\n // credential headers: a password, a bearer token, a session cookie value.\n secrets: request.auth ? authSecrets(request.auth) : undefined,\n });\n\n return {\n run: {\n ...outcome.run,\n summary: { ...outcome.run.summary, artifactDir: paths.dir },\n },\n paths,\n transactionsCaptured: outcome.transactions.length,\n transactions: outcome.transactions,\n };\n }\n\n public async dispose(): Promise<void> {\n this.disposed = true;\n await this.browser.close();\n }\n\n private resolveLimits(overrides?: Partial<ExplorationLimits>): ExplorationLimits {\n const merged: ExplorationLimits = { ...DEFAULT_EXPLORATION_LIMITS, ...overrides };\n return {\n maxPages: clampInt(merged.maxPages, 1, HARD_PAGE_CAP),\n maxDepth: clampInt(merged.maxDepth, 1, HARD_DEPTH_CAP),\n pageTimeoutMs: clampInt(merged.pageTimeoutMs, 1_000, 120_000),\n settleTimeoutMs: clampInt(merged.settleTimeoutMs, 0, 60_000),\n maxDurationMs: clampInt(merged.maxDurationMs, 1_000, 60 * 60_000),\n checkpointEveryPages: clampInt(merged.checkpointEveryPages, 1, 100),\n };\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min;\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\n/** Default artifact location used by the CLI when `--out` is not supplied. */\nexport function defaultArtifactDir(homeDir: string, taskId: string): string {\n return join(homeDir, '.luxray', 'runs', taskId);\n}\n\n/**\n * Every literal value that must be scrubbed from an artifact.\n *\n * The password is included even when form values are not captured, because a\n * page can echo a failed login back into an error message.\n */\nfunction authSecrets(auth: CrawlAuthOptions): readonly string[] {\n const secrets: string[] = [];\n if (auth.credentials) secrets.push(auth.credentials.password);\n secrets.push(...Object.values(auth.headers ?? {}));\n secrets.push(...(auth.cookies ?? []).map((cookie) => cookie.value));\n return secrets;\n}\n\nexport { ExplorationAbortedError } from './errors.js';\nexport { DEFAULT_EXPLORATION_LIMITS } from './crawl/types.js';\nexport type {\n ExplorationLimits,\n ExplorationRun,\n ExplorationRunSummary,\n PageObservation,\n} from './crawl/types.js';\nexport type { CrawlScope } from './crawl/url-policy.js';\nexport { canonicalizeUrl } from './crawl/url-canonicalizer.js';\nexport { isUrlInScope, isBlockedHost } from './crawl/url-policy.js';\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { CapturedTransaction, HttpHeaders } from '@luxray/shared';\nimport type { ExplorationRun } from '../crawl/types.js';\n\n/** Headers whose values must never be persisted in a run artifact. */\nconst SENSITIVE_HEADERS = new Set([\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'proxy-authorization',\n 'x-api-key',\n 'x-auth-token',\n 'x-csrf-token',\n]);\n\nconst DEFAULT_BODY_BUDGET_BYTES = 32 * 1024 * 1024;\nconst OMITTED_BODY = '[body omitted: artifact size budget reached]';\n\nexport interface ArtifactOptions {\n /** Keep credential-bearing headers verbatim. Off by default. */\n readonly includeSecrets?: boolean;\n /** Total response body bytes persisted before bodies are dropped. */\n readonly bodyBudgetBytes?: number;\n /**\n * Literal values scrubbed from every persisted string: passwords typed into\n * a sign-in form, mostly. Applied even when `includeSecrets` is set, because\n * a known secret is never evidence worth keeping.\n */\n readonly secrets?: readonly string[];\n}\n\n/** Shorter values are ignored: scrubbing \"a\" would mangle the whole artifact. */\nconst MIN_SECRET_LENGTH = 4;\nconst REDACTED = '[redacted]';\n\nexport interface ArtifactPaths {\n readonly dir: string;\n readonly runFile: string;\n readonly pagesFile: string;\n readonly transactionsFile: string;\n}\n\n/**\n * Writes the evidence for one run to disk.\n *\n * Until observation ingestion exists (Milestone 6) the artifacts are the only\n * durable record of what was crawled, so they are written as plain JSON beside\n * each other: `run.json` for the summary, `pages.json` for every observation and\n * `transactions.json` for the captured network traffic.\n *\n * Credentials are stripped before writing. Keeping them would turn a folder of\n * debugging output into a secret store.\n */\nexport async function writeRunArtifacts(\n dir: string,\n outcome: { run: ExplorationRun; transactions: readonly CapturedTransaction[] },\n options?: ArtifactOptions,\n): Promise<ArtifactPaths> {\n await mkdir(dir, { recursive: true });\n\n const paths: ArtifactPaths = {\n dir,\n runFile: join(dir, 'run.json'),\n pagesFile: join(dir, 'pages.json'),\n transactionsFile: join(dir, 'transactions.json'),\n };\n\n const transactions = redactTransactions(outcome.transactions, options);\n const secrets = usableSecrets(options?.secrets);\n\n await Promise.all([\n // The file records the directory it lives in, so a bundle copied away from\n // the workspace still says where it was produced.\n writeJson(paths.runFile, scrubValue({ ...outcome.run.summary, artifactDir: dir }, secrets)),\n writeJson(paths.pagesFile, scrubValue(outcome.run.pages, secrets)),\n writeJson(paths.transactionsFile, scrubValue(transactions, secrets)),\n ]);\n\n return paths;\n}\n\nexport function redactTransactions(\n transactions: readonly CapturedTransaction[],\n options?: ArtifactOptions,\n): CapturedTransaction[] {\n const budget = new Budget(options);\n const secrets = usableSecrets(options?.secrets);\n\n return transactions.map((transaction) => {\n const redacted =\n options?.includeSecrets === true\n ? transaction\n : {\n ...transaction,\n request: {\n ...transaction.request,\n headers: redactHeaders(transaction.request.headers),\n },\n ...(transaction.response\n ? {\n response: {\n ...transaction.response,\n headers: redactHeaders(transaction.response.headers),\n },\n }\n : {}),\n };\n\n return scrubValue(limitBody(redacted, budget), secrets);\n });\n}\n\nfunction usableSecrets(secrets: readonly string[] | undefined): readonly string[] {\n if (!secrets) return [];\n return secrets.filter((secret) => secret.length >= MIN_SECRET_LENGTH);\n}\n\n/** Deep copy with every known secret replaced, including request post data. */\nfunction scrubValue<T>(value: T, secrets: readonly string[]): T {\n return scrubUnknown(value, secrets) as T;\n}\n\nfunction scrubUnknown(value: unknown, secrets: readonly string[]): unknown {\n if (secrets.length === 0) return value;\n if (typeof value === 'string') {\n let scrubbed = value;\n for (const secret of secrets) {\n scrubbed = scrubbed.split(secret).join(REDACTED);\n }\n return scrubbed;\n }\n if (Array.isArray(value)) {\n return value.map((item) => scrubUnknown(item, secrets));\n }\n if (value !== null && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n result[key] = scrubUnknown(entry, secrets);\n }\n return result;\n }\n return value;\n}\n\nfunction redactHeaders(headers: HttpHeaders): HttpHeaders {\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n result[name] = SENSITIVE_HEADERS.has(name.toLowerCase()) ? '[redacted]' : value;\n }\n return result;\n}\n\nclass Budget {\n private remaining: number;\n\n public constructor(options?: ArtifactOptions) {\n this.remaining = options?.bodyBudgetBytes ?? DEFAULT_BODY_BUDGET_BYTES;\n }\n\n public take(bytes: number): boolean {\n if (bytes > this.remaining) return false;\n this.remaining -= bytes;\n return true;\n }\n}\n\n/** Drops bodies once the artifact budget is spent, keeping the metadata. */\nfunction limitBody(transaction: CapturedTransaction, budget: Budget): CapturedTransaction {\n const body = transaction.response?.body;\n if (!transaction.response || typeof body !== 'string' || body.length === 0) {\n return transaction;\n }\n if (budget.take(Buffer.byteLength(body, 'utf8'))) return transaction;\n\n return {\n ...transaction,\n response: {\n ...transaction.response,\n body: OMITTED_BODY,\n bodyEncoding: 'utf-8',\n bodyTruncated: true,\n },\n };\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await writeFile(path, `${JSON.stringify(value, null, 2)}\\n`, 'utf8');\n}\n","import { chromium, type Browser, type BrowserContext } from 'playwright';\n\n/** Cookies applied to a task context before the first navigation. */\nexport interface AuthCookie {\n readonly name: string;\n readonly value: string;\n}\n\nexport interface TaskBrowserOptions {\n readonly headless?: boolean;\n /** Viewport for every task context. */\n readonly viewport?: { readonly width: number; readonly height: number };\n}\n\n/**\n * Owns the Chromium process for an exploration worker.\n *\n * Isolation rule for M4: one `BrowserContext` per task, created fresh and\n * disposed at the end of the run. Nothing (cookies, storage, cache headers)\n * crosses tasks, and a task never sees the user's everyday browser profile.\n *\n * The browser process itself is shared across tasks in one agent process: it is\n * expensive, and isolation comes from the context, not the executable.\n */\nexport class TaskBrowser {\n private browser: Browser | null = null;\n private readonly headless: boolean;\n private readonly viewport: { readonly width: number; readonly height: number };\n private launchCount = 0;\n\n constructor(options?: TaskBrowserOptions) {\n this.headless = options?.headless ?? true;\n this.viewport = options?.viewport ?? { width: 1280, height: 720 };\n }\n\n /** Launches Chromium, or relaunches it after a crash. */\n public async ensureStarted(): Promise<Browser> {\n if (this.browser && this.browser.isConnected()) return this.browser;\n\n if (this.browser) {\n await this.browser.close().catch(() => {});\n this.browser = null;\n }\n\n const browser = await chromium.launch({ headless: this.headless });\n browser.on('disconnected', () => {\n if (this.browser === browser) this.browser = null;\n });\n this.browser = browser;\n this.launchCount += 1;\n return browser;\n }\n\n /**\n * Opens a fresh, isolated context for one task. `ignoreHTTPSErrors` is on so\n * local staging servers with self-signed certificates can be explored.\n *\n * `storageState` restores a previously saved session (cookies + localStorage)\n * so a crawl can reuse a sign-in instead of performing one. It is a path, not\n * an inline object, because the file is credential material and the operator\n * decides where it lives.\n *\n * `headers` and `cookies` are operator-supplied auth keys: a bearer token, an\n * API key, a session cookie. They apply to every request the context makes,\n * including the first one, which is what lets an authenticated crawl start on\n * a protected page instead of bouncing to the sign-in form.\n */\n public async openTaskContext(options?: {\n readonly storageState?: string;\n readonly headers?: Readonly<Record<string, string>>;\n readonly cookies?: readonly AuthCookie[];\n /** Origin the cookies belong to; required when `cookies` are given. */\n readonly cookieUrl?: string;\n }): Promise<BrowserContext> {\n const browser = await this.ensureStarted();\n const context = await browser.newContext({\n viewport: this.viewport,\n ignoreHTTPSErrors: true,\n serviceWorkers: 'block',\n ...(options?.storageState ? { storageState: options.storageState } : {}),\n ...(options?.headers && Object.keys(options.headers).length > 0\n ? { extraHTTPHeaders: { ...options.headers } }\n : {}),\n });\n\n if (options?.cookies && options.cookies.length > 0) {\n if (!options.cookieUrl) {\n await context.close().catch(() => {});\n throw new Error('cookieUrl is required when auth cookies are supplied.');\n }\n await context.addCookies(\n options.cookies.map((cookie) => ({\n name: cookie.name,\n value: cookie.value,\n url: options.cookieUrl,\n })),\n );\n }\n\n return context;\n }\n\n public isConnected(): boolean {\n return this.browser !== null && this.browser.isConnected();\n }\n\n public get launches(): number {\n return this.launchCount;\n }\n\n public async close(): Promise<void> {\n const browser = this.browser;\n this.browser = null;\n if (!browser) return;\n await browser.close().catch(() => {});\n }\n}\n","/** Raised when the run was stopped on purpose (cancel, pause, shutdown). */\nexport class ExplorationAbortedError extends Error {\n public constructor(message = 'Exploration was aborted.') {\n super(message);\n this.name = 'ExplorationAbortedError';\n }\n}\n\n/**\n * Raised when the operator asked for a signed-in crawl and the sign-in did not\n * take effect.\n *\n * Failing here is deliberate: continuing would crawl the login wall and report\n * a successful run full of unauthenticated shell pages, which is exactly the\n * outcome the sign-in step exists to prevent.\n */\nexport class AuthenticationFailedError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = 'AuthenticationFailedError';\n }\n}\n","import type { BrowserContext, Locator, Page } from 'playwright';\nimport { AuthenticationFailedError, ExplorationAbortedError } from '../errors.js';\n\n/**\n * Signs the operator in before a crawl starts.\n *\n * The control plane never sees these credentials: they are held by the agent\n * process for the duration of one run and typed into the page, exactly like a\n * human would. The task row only ever records that a sign-in happened.\n */\n\nexport interface SiteCredentials {\n readonly username: string;\n readonly password: string;\n}\n\nexport type LoginStrategy = 'form' | 'manual';\n\nexport interface LoginLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport interface LoginOptions {\n /** Page that renders the sign-in form. Defaults to the crawl's start page. */\n readonly loginUrl: string;\n readonly credentials: SiteCredentials;\n /** Budget for the first paint of the sign-in page. */\n readonly pageTimeoutMs?: number;\n /** How long to wait for the site to accept or reject the form. */\n readonly submitTimeoutMs?: number;\n /**\n * Escape hatch for captchas, 2FA prompts and device approvals: the operator\n * finishes the sign-in in a visible browser, then resolves this promise.\n * Without it an unverifiable sign-in is reported as a failure.\n */\n readonly manualAssist?: () => Promise<void>;\n readonly signal?: AbortSignal;\n readonly logger?: LoginLogger;\n}\n\nexport interface LoginResult {\n readonly strategy: LoginStrategy;\n readonly loginUrl: string;\n readonly finalUrl: string;\n /** Cookie count after the sign-in, used as a cheap sanity signal. */\n readonly cookies: number;\n}\n\nconst DEFAULT_PAGE_TIMEOUT_MS = 30_000;\nconst DEFAULT_SUBMIT_TIMEOUT_MS = 30_000;\nconst POLL_INTERVAL_MS = 200;\n\n/**\n * Username fields, most specific first. Sites that use a two-step flow still\n * expose an email field on the first screen, so this list intentionally ends\n * with plain text inputs.\n */\nconst USERNAME_SELECTORS = [\n 'input[autocomplete=\"username\"]',\n 'input[type=\"email\"]',\n 'input[name=\"username\"]',\n 'input[name=\"email\"]',\n 'input[id=\"username\"]',\n 'input[id=\"email\"]',\n 'input[name*=\"user\" i]',\n 'input[name*=\"email\" i]',\n 'input[id*=\"user\" i]',\n 'input[id*=\"email\" i]',\n 'input[type=\"text\"]',\n];\n\nconst PASSWORD_SELECTOR = 'input[type=\"password\"]';\n\nconst SUBMIT_SELECTORS = [\n 'form button[type=\"submit\"]',\n 'form input[type=\"submit\"]',\n 'button[type=\"submit\"]',\n 'input[type=\"submit\"]',\n 'form button',\n];\n\nexport async function signIn(\n context: BrowserContext,\n options: LoginOptions,\n): Promise<LoginResult> {\n const pageTimeoutMs = options.pageTimeoutMs ?? DEFAULT_PAGE_TIMEOUT_MS;\n const submitTimeoutMs = options.submitTimeoutMs ?? DEFAULT_SUBMIT_TIMEOUT_MS;\n\n // A dedicated page keeps the credential POST off the crawl's capture window:\n // transactions are attributed per page, so traffic here never reaches the\n // artifacts.\n const page = await context.newPage();\n try {\n page.setDefaultTimeout(pageTimeoutMs);\n await page.goto(options.loginUrl, { waitUntil: 'domcontentloaded', timeout: pageTimeoutMs });\n await settle(page, pageTimeoutMs);\n\n const passwordField = await visibleLocator(page, PASSWORD_SELECTOR);\n\n if (!passwordField) {\n return await assistManually(context, page, options);\n }\n\n const usernameField = await findUsernameField(page);\n if (!usernameField) {\n if (options.manualAssist) {\n options.logger?.warn(\n 'Sign-in page has a password field but no recognizable username field; asking the operator to finish it.',\n );\n return await assistManually(context, page, options);\n }\n throw new AuthenticationFailedError(\n `Found a password field at ${options.loginUrl} but no username/email field. ` +\n \"Pass --login-url with the site's form page, or run with --headed and sign in manually.\",\n );\n }\n\n await usernameField.fill(options.credentials.username);\n await passwordField.fill(options.credentials.password);\n options.logger?.info('Sign-in form filled; submitting.');\n\n await submit(page, passwordField);\n\n if (await waitForSignedIn(page, submitTimeoutMs, options.signal)) {\n return await result(context, page, 'form', options);\n }\n\n if (options.manualAssist) {\n options.logger?.warn(\n 'The site did not accept the scripted sign-in; asking the operator to finish it.',\n );\n return await assistManually(context, page, options);\n }\n\n throw new AuthenticationFailedError(\n `The sign-in form at ${options.loginUrl} did not accept the credentials ` +\n `(still on ${truncate(page.url())} after ${Math.round(submitTimeoutMs / 1000)}s). ` +\n 'Check the password, or run with --headed to sign in manually.',\n );\n } finally {\n await page.close().catch(() => {});\n }\n}\n\n/**\n * Hands the visible browser to the operator. Used for captchas, 2FA and device\n * approval, where no deterministic form fill can succeed.\n */\nasync function assistManually(\n context: BrowserContext,\n page: Page,\n options: LoginOptions,\n): Promise<LoginResult> {\n if (!options.manualAssist) {\n throw new AuthenticationFailedError(\n `No sign-in form was found at ${options.loginUrl}. ` +\n \"Pass --login-url with the site's login page, reuse a session with --auth-state, \" +\n 'or run with --headed to sign in interactively.',\n );\n }\n\n await options.manualAssist();\n\n if (await hasVisiblePasswordField(page)) {\n throw new AuthenticationFailedError(\n 'The sign-in still looks incomplete: the password form is still visible. ' +\n 'Nothing was crawled.',\n );\n }\n\n options.logger?.info('Manual sign-in completed.');\n return await result(context, page, 'manual', options);\n}\n\nasync function result(\n context: BrowserContext,\n page: Page,\n strategy: LoginStrategy,\n options: LoginOptions,\n): Promise<LoginResult> {\n const cookies = await context.cookies().catch(() => []);\n return {\n strategy,\n loginUrl: options.loginUrl,\n finalUrl: page.url(),\n cookies: cookies.length,\n };\n}\n\nasync function submit(page: Page, passwordField: Locator): Promise<void> {\n for (const selector of SUBMIT_SELECTORS) {\n const button = page.locator(selector).first();\n if (await button.isVisible().catch(() => false)) {\n await button.click({ timeout: 10_000 }).catch(() => {});\n return;\n }\n }\n // Many single-field forms submit on Enter only.\n await passwordField.press('Enter').catch(() => {});\n}\n\n/**\n * Waits until the password form is gone. That is the only signal most sites\n * give: the form is replaced by the signed-in shell, or by an error message\n * inside the same form.\n */\nasync function waitForSignedIn(\n page: Page,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (signal?.aborted) throw new ExplorationAbortedError();\n await sleep(POLL_INTERVAL_MS);\n if (signal?.aborted) throw new ExplorationAbortedError();\n if (!(await hasVisiblePasswordField(page))) return true;\n }\n return false;\n}\n\nasync function hasVisiblePasswordField(page: Page): Promise<boolean> {\n return (await visibleLocator(page, PASSWORD_SELECTOR)) !== null;\n}\n\n/** First visible match, or null. Tolerates navigation races. */\nasync function visibleLocator(page: Page, selector: string): Promise<Locator | null> {\n try {\n const matches = page.locator(selector);\n const count = await matches.count();\n for (let index = 0; index < count; index += 1) {\n const candidate = matches.nth(index);\n if (await candidate.isVisible().catch(() => false)) return candidate;\n }\n } catch {\n // The document was replaced mid-query; the caller polls again.\n }\n return null;\n}\n\nasync function findUsernameField(page: Page): Promise<Locator | null> {\n for (const selector of USERNAME_SELECTORS) {\n const field = await visibleLocator(page, selector);\n if (field) return field;\n }\n return null;\n}\n\nasync function settle(page: Page, timeoutMs: number): Promise<void> {\n await page\n .waitForLoadState('networkidle', { timeout: Math.min(3_000, timeoutMs) })\n .catch(() => {});\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction truncate(value: string, max = 300): string {\n return value.length > max ? `${value.slice(0, max)}…` : value;\n}\n","import { createHash } from 'node:crypto';\nimport type { Page } from 'playwright';\n\nexport interface StructuralNode {\n readonly tag: string;\n readonly depth: number;\n}\n\nexport interface PageSnapshot {\n readonly title: string | null;\n readonly links: readonly string[];\n readonly structure: readonly StructuralNode[];\n /**\n * True when a password input is rendered.\n *\n * This is the cheapest deterministic sign-in-wall signal: a page that asks\n * for a password and was reached without credentials is a gate, not content.\n */\n readonly hasPasswordField: boolean;\n /**\n * Body text of a JSON document, or null for anything else.\n *\n * API-first hosts answer with `application/json`. Chromium renders that in a\n * plain `<pre>`, so `links` is empty even when the payload points at every\n * other endpoint. The crawler mines this text instead of treating the page as\n * a dead end.\n */\n readonly jsonBody: string | null;\n /**\n * True when `jsonBody` was cut at `MAX_JSON_BODY_CHARS`.\n *\n * Truncated JSON cannot be parsed, so such a page is fingerprinted and\n * recorded but its links are not followed.\n */\n readonly jsonBodyTruncated: boolean;\n}\n\n/**\n * Structural fingerprint of a rendered document.\n *\n * Only element tags and their nesting depth are hashed: text, attributes,\n * classes and ids are discarded, because they differ between pages that render\n * from the same template. Two listing pages produced by one template therefore\n * share a fingerprint, which is how the crawler recognises a page it has\n * already understood without fetching its siblings forever.\n */\nexport function structuralFingerprint(structure: readonly StructuralNode[]): string {\n const canonical = structure.map((node) => `${node.depth}:${node.tag}`).join('|');\n return `sha256:${createHash('sha256').update(canonical).digest('hex')}`;\n}\n\nconst MAX_NODES = 4_000;\nconst MAX_LINKS = 2_000;\n\n/**\n * Upper bound on the JSON text carried out of the page, in characters.\n *\n * Roughly mirrors the capture engine's 2 MiB response-body budget. A larger\n * document is still fingerprinted (over the retained prefix) and recorded, but\n * its links are not mined, because half a JSON object is not parseable.\n */\nconst MAX_JSON_BODY_CHARS = 2 * 1024 * 1024;\n\n/** Longer strings are payloads (tokens, blobs), not crawlable links. */\nconst MAX_LINK_LENGTH = 2_048;\n\n/**\n * URLs a JSON document points at, in document order.\n *\n * The extracted values are candidates, not resolved URLs: relative paths are\n * returned as-is and go through the same canonicalization and scope filter as\n * anchors. Three shapes are rejected:\n *\n * - URI templates (`/repos/{owner}/{repo}`, `{?page,per_page}`) are patterns,\n * not resources; fetching one would request a literal `{`.\n * - Strings containing whitespace are prose that mentions a URL.\n * - Values longer than `MAX_LINK_LENGTH` are payloads.\n *\n * Order follows the serialized document so two crawls of the same host queue\n * the same URLs in the same order.\n */\nexport function extractJsonLinks(jsonBody: string): readonly string[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonBody);\n } catch {\n return [];\n }\n\n const links: string[] = [];\n const seen = new Set<string>();\n const stack: unknown[] = [parsed];\n\n while (stack.length > 0) {\n const value = stack.pop();\n\n if (Array.isArray(value)) {\n for (let index = value.length - 1; index >= 0; index -= 1) {\n stack.push(value[index]);\n }\n continue;\n }\n\n if (value !== null && typeof value === 'object') {\n const keys = Object.keys(value);\n for (let index = keys.length - 1; index >= 0; index -= 1) {\n const key = keys[index];\n if (key !== undefined) stack.push((value as Record<string, unknown>)[key]);\n }\n continue;\n }\n\n if (typeof value !== 'string') continue;\n const candidate = value.trim();\n if (!isJsonLinkCandidate(candidate)) continue;\n if (seen.has(candidate)) continue;\n seen.add(candidate);\n links.push(candidate);\n if (links.length >= MAX_LINKS) break;\n }\n\n return links;\n}\n\nfunction isJsonLinkCandidate(value: string): boolean {\n if (value.length === 0 || value.length > MAX_LINK_LENGTH) return false;\n if (value.includes('{') || value.includes('}')) return false;\n if (/\\s/.test(value)) return false;\n return /^https?:\\/\\//i.test(value) || value.startsWith('/');\n}\n\n/**\n * Content fingerprint of a JSON document.\n *\n * Every JSON response is rendered with the same `<pre>` wrapper, so\n * `structuralFingerprint` would call two unrelated endpoints duplicates. The\n * payload is the page here, so the payload is what gets hashed.\n */\nexport function jsonDocumentFingerprint(jsonBody: string): string {\n return `sha256:${createHash('sha256').update(jsonBody).digest('hex')}`;\n}\n\n/**\n * Reads the rendered page. The function passed to `evaluate` must be\n * self-contained: Playwright serializes it and runs it inside the browser, so\n * it cannot close over module scope.\n */\nexport async function readPageSnapshot(page: Page): Promise<PageSnapshot> {\n return page.evaluate(\n (limits: { maxNodes: number; maxLinks: number; maxJsonChars: number }) => {\n const SKIP = new Set([\n 'script',\n 'style',\n 'noscript',\n 'template',\n 'svg',\n 'path',\n 'link',\n 'meta',\n 'head',\n ]);\n const structure: Array<{ tag: string; depth: number }> = [];\n\n const walk = (element: Element, depth: number): void => {\n if (structure.length >= limits.maxNodes) return;\n const tag = element.tagName.toLowerCase();\n if (SKIP.has(tag)) return;\n structure.push({ tag, depth });\n for (const child of Array.from(element.children)) {\n walk(child, depth + 1);\n if (structure.length >= limits.maxNodes) return;\n }\n };\n\n if (document.body) walk(document.body, 0);\n\n const links: string[] = [];\n const anchors = document.querySelectorAll('a[href]');\n for (const anchor of Array.from(anchors)) {\n if (links.length >= limits.maxLinks) break;\n const href = (anchor as HTMLAnchorElement).href;\n if (href) links.push(href);\n }\n\n const passwordInput = document.querySelector('input[type=\"password\"]');\n const hasPasswordField =\n passwordInput !== null &&\n Array.from(passwordInput.getClientRects()).some(\n (rect) => rect.width > 0 && rect.height > 0,\n );\n\n // Chromium wraps a JSON response in a single `<pre>`, so `textContent` is\n // the exact payload. The second child the viewer appends carries no text.\n const isJson = document.contentType.toLowerCase().includes('json');\n const jsonText = isJson && document.body ? (document.body.textContent ?? '') : null;\n const jsonBody =\n jsonText === null ? null : jsonText.slice(0, limits.maxJsonChars);\n const jsonBodyTruncated =\n jsonText !== null && jsonText.length > limits.maxJsonChars;\n\n return {\n title: document.title.length > 0 ? document.title : null,\n links,\n structure,\n hasPasswordField,\n jsonBody,\n jsonBodyTruncated,\n };\n },\n { maxNodes: MAX_NODES, maxLinks: MAX_LINKS, maxJsonChars: MAX_JSON_BODY_CHARS },\n );\n}\n","import { fileURLToPath } from 'node:url';\nimport { CaptureEngine, type CaptureEngineOptions, type CaptureSession } from './capture-engine.js';\nimport { ProcessLifecycle } from './lifecycle/process-lifecycle.js';\n\nexport * from './capture-engine.js';\nexport * from './browser/browser-manager.js';\nexport * from './interceptor/network-interceptor.js';\nexport * from './interceptor/body-resolver.js';\nexport * from './transaction/transaction-correlator.js';\nexport * from './storage/transaction-storage.js';\nexport * from './storage/memory-storage.js';\nexport * from './lifecycle/process-lifecycle.js';\nexport * from './cdp/cdp-events.js';\n\n/**\n * CaptureWorker class wrapping CaptureEngine for backwards compatibility and clean service abstraction.\n */\nexport class CaptureWorker extends CaptureEngine {\n constructor(options?: CaptureEngineOptions) {\n super(options);\n }\n}\n\n// Minimal direct executable entry point\nconst isDirectExecution =\n process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];\n\nif (isDirectExecution) {\n const engine = new CaptureEngine({ headless: true });\n ProcessLifecycle.register(() => engine.stop());\n\n console.log('[CaptureEngine] Starting Luxray Capture Engine standalone process...');\n engine\n .start()\n .then(async () => {\n console.log('[CaptureEngine] Performing capture smoke verification...');\n const session = await engine.createCaptureSession();\n // Verify CDP communication\n const { protocolVersion } = (await session.cdpSession.send('Browser.getVersion')) as {\n protocolVersion: string;\n };\n console.log(`[CaptureEngine] Active CDP protocol version: ${protocolVersion}`);\n\n await session.close();\n await engine.stop();\n console.log('[CaptureEngine] Smoke verification completed successfully.');\n process.exit(0);\n })\n .catch((err) => {\n console.error('[CaptureEngine] Smoke verification failed:', err);\n process.exit(1);\n });\n}\n","import { chromium, type Browser, type BrowserContext, type Page, type CDPSession } from 'playwright';\nimport type { CaptureWorkerConfig } from '@luxray/shared';\n\nexport interface ManagedSession {\n readonly page: Page;\n readonly cdpSession: CDPSession;\n}\n\n/**\n * Manages Playwright Chromium lifecycle, contexts, and CDP session acquisition.\n */\nexport class BrowserManager {\n private browser: Browser | null = null;\n private context: BrowserContext | null = null;\n private readonly config: CaptureWorkerConfig;\n private readonly activeSessions = new Set<ManagedSession>();\n\n constructor(config?: Partial<CaptureWorkerConfig>) {\n this.config = {\n headless: config?.headless ?? true,\n viewport: config?.viewport ?? { width: 1280, height: 720 },\n userAgent: config?.userAgent,\n maxBodySizeBytes: config?.maxBodySizeBytes,\n maxStoredTransactions: config?.maxStoredTransactions,\n };\n }\n\n public async start(): Promise<void> {\n if (this.browser && this.context) {\n return;\n }\n\n this.browser = await chromium.launch({\n headless: this.config.headless,\n });\n\n this.context = await this.browser.newContext({\n viewport: this.config.viewport,\n userAgent: this.config.userAgent,\n });\n }\n\n /**\n * Spawns a new page and creates a dedicated CDP session for it.\n */\n public async createSession(url?: string): Promise<ManagedSession> {\n if (!this.context) {\n throw new Error('BrowserManager is not started. Call start() first.');\n }\n\n const page = await this.context.newPage();\n const cdpSession = await this.context.newCDPSession(page);\n const session: ManagedSession = { page, cdpSession };\n\n this.activeSessions.add(session);\n\n page.once('close', () => {\n this.activeSessions.delete(session);\n });\n\n if (url) {\n await page.goto(url, { waitUntil: 'domcontentloaded' });\n }\n\n return session;\n }\n\n /**\n * Closes a specific managed session.\n */\n public async closeSession(session: ManagedSession): Promise<void> {\n this.activeSessions.delete(session);\n try {\n await session.cdpSession.detach().catch(() => {});\n await session.page.close().catch(() => {});\n } catch {\n // Safe teardown\n }\n }\n\n /**\n * Shuts down all sessions, context, and browser instance.\n */\n public async stop(): Promise<void> {\n for (const session of Array.from(this.activeSessions)) {\n await this.closeSession(session);\n }\n this.activeSessions.clear();\n\n if (this.context) {\n await this.context.close().catch(() => {});\n this.context = null;\n }\n\n if (this.browser) {\n await this.browser.close().catch(() => {});\n this.browser = null;\n }\n }\n\n public isRunning(): boolean {\n return this.browser !== null && this.context !== null;\n }\n}\n\n","import type { CDPSession } from 'playwright';\nimport type {\n CDPRequestWillBeSentEvent,\n CDPResponseReceivedEvent,\n CDPLoadingFinishedEvent,\n CDPLoadingFailedEvent,\n CDPRequestWillBeSentExtraInfoEvent,\n CDPResponseReceivedExtraInfoEvent,\n} from '../cdp/cdp-events.js';\nimport type { TransactionCorrelator } from '../transaction/transaction-correlator.js';\n\nexport interface InterceptorOptions {\n /**\n * Maximum total buffer size for CDP network cache in bytes (default 10MB).\n */\n maxTotalBufferSize?: number;\n /**\n * Maximum single resource buffer size in bytes (default 5MB).\n */\n maxResourceBufferSize?: number;\n}\n\n/**\n * Manages CDP Network domain lifecycle, listeners, and event routing.\n */\nexport class NetworkInterceptor {\n private readonly cdpSession: CDPSession;\n private readonly correlator: TransactionCorrelator;\n private readonly options: InterceptorOptions;\n private isAttached = false;\n private unbindListeners: (() => void)[] = [];\n\n constructor(\n cdpSession: CDPSession,\n correlator: TransactionCorrelator,\n options?: InterceptorOptions\n ) {\n this.cdpSession = cdpSession;\n this.correlator = correlator;\n this.options = {\n maxTotalBufferSize: options?.maxTotalBufferSize ?? 10 * 1024 * 1024,\n maxResourceBufferSize: options?.maxResourceBufferSize ?? 5 * 1024 * 1024,\n };\n }\n\n /**\n * Enables CDP Network domain and wires event listeners.\n */\n public async attach(): Promise<void> {\n if (this.isAttached) {\n return;\n }\n\n // Enable Network instrumentation with buffer limits\n await this.cdpSession.send('Network.enable', {\n maxTotalBufferSize: this.options.maxTotalBufferSize,\n maxResourceBufferSize: this.options.maxResourceBufferSize,\n });\n\n const onRequestWillBeSent = (params: unknown) => {\n this.correlator.handleRequestWillBeSent(params as CDPRequestWillBeSentEvent);\n };\n\n const onResponseReceived = (params: unknown) => {\n this.correlator.handleResponseReceived(params as CDPResponseReceivedEvent);\n };\n\n const onLoadingFinished = (params: unknown) => {\n void this.correlator.handleLoadingFinished(params as CDPLoadingFinishedEvent);\n };\n\n const onLoadingFailed = (params: unknown) => {\n this.correlator.handleLoadingFailed(params as CDPLoadingFailedEvent);\n };\n\n const onRequestExtraInfo = (params: unknown) => {\n this.correlator.handleRequestExtraInfo(params as CDPRequestWillBeSentExtraInfoEvent);\n };\n\n const onResponseExtraInfo = (params: unknown) => {\n this.correlator.handleResponseExtraInfo(params as CDPResponseReceivedExtraInfoEvent);\n };\n\n this.cdpSession.on('Network.requestWillBeSent', onRequestWillBeSent);\n this.cdpSession.on('Network.responseReceived', onResponseReceived);\n this.cdpSession.on('Network.loadingFinished', onLoadingFinished);\n this.cdpSession.on('Network.loadingFailed', onLoadingFailed);\n this.cdpSession.on('Network.requestWillBeSentExtraInfo', onRequestExtraInfo);\n this.cdpSession.on('Network.responseReceivedExtraInfo', onResponseExtraInfo);\n\n this.unbindListeners = [\n () => this.cdpSession.off('Network.requestWillBeSent', onRequestWillBeSent),\n () => this.cdpSession.off('Network.responseReceived', onResponseReceived),\n () => this.cdpSession.off('Network.loadingFinished', onLoadingFinished),\n () => this.cdpSession.off('Network.loadingFailed', onLoadingFailed),\n () => this.cdpSession.off('Network.requestWillBeSentExtraInfo', onRequestExtraInfo),\n () => this.cdpSession.off('Network.responseReceivedExtraInfo', onResponseExtraInfo),\n ];\n\n this.isAttached = true;\n }\n\n /**\n * Unbinds all listeners and disables CDP Network domain.\n */\n public async detach(): Promise<void> {\n if (!this.isAttached) {\n return;\n }\n\n for (const unbind of this.unbindListeners) {\n try {\n unbind();\n } catch {\n // Safe disposal\n }\n }\n this.unbindListeners = [];\n\n try {\n await this.cdpSession.send('Network.disable');\n } catch {\n // Ignored if CDP session is already tearing down\n }\n\n this.correlator.cleanup();\n this.isAttached = false;\n }\n\n public getAttached(): boolean {\n return this.isAttached;\n }\n}\n\n","import type { CDPSession } from 'playwright';\nimport type { CDPGetResponseBodyResult } from '../cdp/cdp-events.js';\n\nexport interface BodyResolverOptions {\n /**\n * Maximum body size in bytes to store. Bodies larger than this will be truncated.\n * Default: 2MB (2,097,152 bytes)\n */\n maxBodySizeBytes?: number;\n /**\n * Maximum timeout in milliseconds to wait for CDP response body.\n * Default: 3000ms\n */\n timeoutMs?: number;\n}\n\nexport interface ResolvedBody {\n body: string | null;\n bodyEncoding: 'utf-8' | 'base64';\n bodyTruncated: boolean;\n}\n\n/**\n * Safely retrieves and bounds HTTP response bodies through Chrome DevTools Protocol.\n */\nexport class ResponseBodyResolver {\n private readonly maxBodySizeBytes: number;\n private readonly timeoutMs: number;\n\n constructor(options?: BodyResolverOptions) {\n this.maxBodySizeBytes = options?.maxBodySizeBytes ?? 2 * 1024 * 1024; // 2MB\n this.timeoutMs = options?.timeoutMs ?? 3000;\n }\n\n /**\n * Attempts to retrieve the response body for a completed request.\n * Never throws; returns null body gracefully on any failure.\n */\n public async resolve(\n cdpSession: CDPSession,\n requestId: string,\n mimeType?: string\n ): Promise<ResolvedBody> {\n try {\n const getBodyPromise = cdpSession.send('Network.getResponseBody', {\n requestId,\n }) as Promise<CDPGetResponseBodyResult>;\n\n let timer: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`Timeout (${this.timeoutMs}ms) retrieving response body for ${requestId}`));\n }, this.timeoutMs);\n });\n\n const result = await Promise.race([getBodyPromise, timeoutPromise]).finally(() => {\n if (timer) clearTimeout(timer);\n });\n\n if (!result || typeof result.body !== 'string' || result.body.length === 0) {\n return { body: null, bodyEncoding: 'utf-8', bodyTruncated: false };\n }\n\n let content = result.body;\n let encoding: 'utf-8' | 'base64' = result.base64Encoded ? 'base64' : 'utf-8';\n\n // If base64-encoded text or json, decode to utf-8 if possible\n if (result.base64Encoded && this.isTextualMimeType(mimeType)) {\n try {\n content = Buffer.from(content, 'base64').toString('utf-8');\n encoding = 'utf-8';\n } catch {\n // Keep base64 if decoding fails\n }\n }\n\n // Check and enforce size bounds\n const byteLength = Buffer.byteLength(content, encoding === 'base64' ? 'base64' : 'utf-8');\n if (byteLength > this.maxBodySizeBytes) {\n // Truncate safely\n const truncated = content.slice(0, this.maxBodySizeBytes);\n return {\n body: truncated,\n bodyEncoding: encoding,\n bodyTruncated: true,\n };\n }\n\n return {\n body: content,\n bodyEncoding: encoding,\n bodyTruncated: false,\n };\n } catch {\n // Body retrieval can fail naturally for redirects, 204/304, aborted requests, or cached responses.\n return { body: null, bodyEncoding: 'utf-8', bodyTruncated: false };\n }\n }\n\n private isTextualMimeType(mimeType?: string): boolean {\n if (!mimeType) return false;\n const lower = mimeType.toLowerCase();\n return (\n lower.includes('json') ||\n lower.includes('text') ||\n lower.includes('javascript') ||\n lower.includes('xml') ||\n lower.includes('html') ||\n lower.includes('graphql')\n );\n }\n}\n","import type { CDPSession } from 'playwright';\nimport { randomUUID } from 'node:crypto';\nimport type {\n CapturedRequest,\n CapturedResponse,\n CapturedTransaction,\n HttpHeaders,\n HttpMethod,\n} from '@luxray/shared';\nimport type {\n CDPRequestWillBeSentEvent,\n CDPResponseReceivedEvent,\n CDPLoadingFinishedEvent,\n CDPLoadingFailedEvent,\n CDPRequestWillBeSentExtraInfoEvent,\n CDPResponseReceivedExtraInfoEvent,\n CDPResponse,\n} from '../cdp/cdp-events.js';\nimport type { TransactionStorage } from '../storage/transaction-storage.js';\nimport type { ResponseBodyResolver } from '../interceptor/body-resolver.js';\n\ninterface InFlightTransaction {\n readonly transactionId: string;\n readonly cdpRequestId: string;\n readonly parentTransactionId?: string;\n hopIndex: number;\n url: string;\n method: string;\n requestHeaders: HttpHeaders;\n postData?: string | null;\n startTime: number;\n initiator?: string;\n resourceType?: string;\n response?: {\n status: number;\n statusText: string;\n headers: HttpHeaders;\n mimeType?: string;\n responseTime: number;\n };\n}\n\n/**\n * Correlates asynchronous CDP Network events into unified, immutable CapturedTransactions.\n */\nexport class TransactionCorrelator {\n private readonly inFlight = new Map<string, InFlightTransaction>();\n private readonly storage: TransactionStorage;\n private readonly bodyResolver: ResponseBodyResolver;\n private readonly cdpSession: CDPSession;\n\n constructor(\n cdpSession: CDPSession,\n storage: TransactionStorage,\n bodyResolver: ResponseBodyResolver\n ) {\n this.cdpSession = cdpSession;\n this.storage = storage;\n this.bodyResolver = bodyResolver;\n }\n\n /**\n * Handles Network.requestWillBeSent.\n * Accurately tracks initial requests and handles multi-hop redirects.\n */\n public handleRequestWillBeSent(event: CDPRequestWillBeSentEvent): void {\n const existing = this.inFlight.get(event.requestId);\n\n // If redirectResponse is present, the previous request completed with a redirect status\n if (event.redirectResponse && existing) {\n this.finalizeRedirectHop(existing, event.redirectResponse, event.request.url);\n }\n\n const hopIndex = existing ? existing.hopIndex + 1 : 0;\n const transactionId = `${event.requestId}-${hopIndex}-${randomUUID().slice(0, 8)}`;\n const startTime = event.wallTime ? Math.round(event.wallTime * 1000) : Date.now();\n\n const inFlightRecord: InFlightTransaction = {\n transactionId,\n cdpRequestId: event.requestId,\n parentTransactionId: existing?.transactionId,\n hopIndex,\n url: event.request.url,\n method: event.request.method,\n requestHeaders: this.normalizeHeaders(event.request.headers),\n postData: event.request.postData ?? null,\n startTime,\n initiator: event.initiator?.type,\n resourceType: event.type,\n };\n\n this.inFlight.set(event.requestId, inFlightRecord);\n\n const initialTx: CapturedTransaction = {\n id: transactionId,\n status: 'pending',\n request: {\n id: transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: startTime,\n },\n timing: {\n startTime,\n },\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(initialTx);\n }\n\n /**\n * Handles Network.responseReceived.\n */\n public handleResponseReceived(event: CDPResponseReceivedEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n const responseTime = Date.now();\n inFlightRecord.response = {\n status: event.response.status,\n statusText: event.response.statusText,\n headers: this.normalizeHeaders(event.response.headers),\n mimeType: event.response.mimeType,\n responseTime,\n };\n\n const currentTx = this.storage.get(inFlightRecord.transactionId);\n if (currentTx) {\n const updatedTx: CapturedTransaction = {\n ...currentTx,\n response: {\n status: inFlightRecord.response.status,\n statusText: inFlightRecord.response.statusText,\n headers: inFlightRecord.response.headers,\n mimeType: inFlightRecord.response.mimeType,\n timestamp: responseTime,\n },\n timing: {\n ...currentTx.timing,\n responseTime,\n },\n };\n this.storage.save(updatedTx);\n }\n }\n\n /**\n * Handles Network.loadingFinished.\n * Resolves the response body and marks the transaction completed.\n */\n public async handleLoadingFinished(event: CDPLoadingFinishedEvent): Promise<void> {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n // Remove from in-flight tracker to free memory\n this.inFlight.delete(event.requestId);\n\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - inFlightRecord.startTime);\n\n // Safely retrieve body through resolver\n const resolvedBody = await this.bodyResolver.resolve(\n this.cdpSession,\n event.requestId,\n inFlightRecord.response?.mimeType\n );\n\n const capturedResponse: CapturedResponse | undefined = inFlightRecord.response\n ? {\n status: inFlightRecord.response.status,\n statusText: inFlightRecord.response.statusText,\n headers: inFlightRecord.response.headers,\n mimeType: inFlightRecord.response.mimeType,\n body: resolvedBody.body,\n bodyEncoding: resolvedBody.bodyEncoding,\n bodyTruncated: resolvedBody.bodyTruncated,\n timestamp: inFlightRecord.response.responseTime,\n }\n : undefined;\n\n const completedTx: CapturedTransaction = {\n id: inFlightRecord.transactionId,\n status: 'completed',\n request: {\n id: inFlightRecord.transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: inFlightRecord.startTime,\n },\n response: capturedResponse,\n timing: {\n startTime: inFlightRecord.startTime,\n responseTime: inFlightRecord.response?.responseTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(completedTx);\n }\n\n /**\n * Handles Network.loadingFailed.\n */\n public handleLoadingFailed(event: CDPLoadingFailedEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n this.inFlight.delete(event.requestId);\n\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - inFlightRecord.startTime);\n const errorMessage = event.errorText || (event.canceled ? 'net::ERR_ABORTED' : 'net::ERR_FAILED');\n\n const failedTx: CapturedTransaction = {\n id: inFlightRecord.transactionId,\n status: 'failed',\n error: errorMessage,\n request: {\n id: inFlightRecord.transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: inFlightRecord.startTime,\n },\n timing: {\n startTime: inFlightRecord.startTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(failedTx);\n }\n\n /**\n * Handles Network.requestWillBeSentExtraInfo to enrich wire headers.\n */\n public handleRequestExtraInfo(event: CDPRequestWillBeSentExtraInfoEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (inFlightRecord) {\n inFlightRecord.requestHeaders = {\n ...inFlightRecord.requestHeaders,\n ...this.normalizeHeaders(event.headers),\n };\n }\n }\n\n /**\n * Handles Network.responseReceivedExtraInfo to enrich response wire headers.\n */\n public handleResponseExtraInfo(event: CDPResponseReceivedExtraInfoEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (inFlightRecord && inFlightRecord.response) {\n inFlightRecord.response.headers = {\n ...inFlightRecord.response.headers,\n ...this.normalizeHeaders(event.headers),\n };\n }\n }\n\n /**\n * Finalizes the previous redirect hop as a completed redirect transaction.\n */\n private finalizeRedirectHop(\n previous: InFlightTransaction,\n redirectResponse: CDPResponse,\n targetUrl: string\n ): void {\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - previous.startTime);\n const redirectHeaders = this.normalizeHeaders(redirectResponse.headers);\n\n const redirectTx: CapturedTransaction = {\n id: previous.transactionId,\n status: 'completed',\n isRedirect: true,\n redirectUrl: targetUrl,\n request: {\n id: previous.transactionId,\n url: previous.url,\n method: previous.method as HttpMethod,\n headers: previous.requestHeaders,\n postData: previous.postData,\n timestamp: previous.startTime,\n },\n response: {\n status: redirectResponse.status,\n statusText: redirectResponse.statusText,\n headers: redirectHeaders,\n mimeType: redirectResponse.mimeType,\n body: null,\n timestamp: endTime,\n },\n timing: {\n startTime: previous.startTime,\n responseTime: endTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: previous.initiator,\n resourceType: previous.resourceType,\n parentTransactionId: previous.parentTransactionId,\n };\n\n this.storage.save(redirectTx);\n }\n\n /**\n * Normalizes header key names to lower-case.\n */\n private normalizeHeaders(headers: Record<string, string>): HttpHeaders {\n const normalized: HttpHeaders = {};\n for (const [key, value] of Object.entries(headers)) {\n normalized[key.toLowerCase()] = String(value);\n }\n return normalized;\n }\n\n /**\n * Returns current count of in-flight tracked requests.\n */\n public getInFlightCount(): number {\n return this.inFlight.size;\n }\n\n /**\n * Cleans up all pending in-flight requests during shutdown.\n */\n public cleanup(): void {\n const now = Date.now();\n for (const [requestId, inFlightRecord] of this.inFlight) {\n const pendingTx = this.storage.get(inFlightRecord.transactionId);\n if (pendingTx && pendingTx.status === 'pending') {\n this.storage.save({\n ...pendingTx,\n status: 'failed',\n error: 'Worker session closed while request was in-flight',\n timing: {\n ...pendingTx.timing,\n endTime: now,\n durationMs: Math.max(0, now - inFlightRecord.startTime),\n },\n });\n }\n this.inFlight.delete(requestId);\n }\n }\n}\n\n","import type { CapturedTransaction } from '@luxray/shared';\nimport type { TransactionStorage } from './transaction-storage.js';\n\nexport interface InMemoryStorageOptions {\n /**\n * Maximum number of transactions retained before oldest are evicted.\n * Default: 1000\n */\n maxCapacity?: number;\n}\n\n/**\n * High-performance, memory-bounded in-memory transaction storage.\n * Maintains insertion order and enforces strict memory bounds.\n */\nexport class InMemoryTransactionStorage implements TransactionStorage {\n private readonly transactions = new Map<string, CapturedTransaction>();\n private readonly maxCapacity: number;\n private readonly listeners = new Set<(tx: CapturedTransaction) => void>();\n\n constructor(options?: InMemoryStorageOptions) {\n this.maxCapacity = Math.max(1, options?.maxCapacity ?? 1000);\n }\n\n public save(transaction: CapturedTransaction): void {\n // If updating existing, remove first to refresh insertion order\n if (this.transactions.has(transaction.id)) {\n this.transactions.delete(transaction.id);\n } else if (this.transactions.size >= this.maxCapacity) {\n // Evict oldest transaction (first key in iteration)\n const oldestKey = this.transactions.keys().next().value;\n if (oldestKey !== undefined) {\n this.transactions.delete(oldestKey);\n }\n }\n\n this.transactions.set(transaction.id, transaction);\n this.notifyListeners(transaction);\n }\n\n public get(id: string): CapturedTransaction | undefined {\n return this.transactions.get(id);\n }\n\n public getAll(): readonly CapturedTransaction[] {\n return Array.from(this.transactions.values());\n }\n\n public filter(predicate: (tx: CapturedTransaction) => boolean): CapturedTransaction[] {\n const results: CapturedTransaction[] = [];\n for (const tx of this.transactions.values()) {\n if (predicate(tx)) {\n results.push(tx);\n }\n }\n return results;\n }\n\n public getByUrl(urlSubstring: string): CapturedTransaction[] {\n return this.filter((tx) => tx.request.url.includes(urlSubstring));\n }\n\n public clear(): void {\n this.transactions.clear();\n }\n\n public size(): number {\n return this.transactions.size;\n }\n\n public onTransaction(listener: (transaction: CapturedTransaction) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private notifyListeners(tx: CapturedTransaction): void {\n for (const listener of this.listeners) {\n try {\n listener(tx);\n } catch (err) {\n console.error('[InMemoryTransactionStorage] Error in transaction listener:', err);\n }\n }\n }\n}\n\n","import type { Page, CDPSession } from 'playwright';\nimport type { CaptureWorkerConfig, WorkerLifecycleState } from '@luxray/shared';\nimport { BrowserManager, type ManagedSession } from './browser/browser-manager.js';\nimport { NetworkInterceptor } from './interceptor/network-interceptor.js';\nimport { ResponseBodyResolver } from './interceptor/body-resolver.js';\nimport { TransactionCorrelator } from './transaction/transaction-correlator.js';\nimport { InMemoryTransactionStorage } from './storage/memory-storage.js';\nimport type { TransactionStorage } from './storage/transaction-storage.js';\n\nexport interface CaptureSession {\n readonly page: Page;\n readonly cdpSession: CDPSession;\n readonly interceptor: NetworkInterceptor;\n readonly correlator: TransactionCorrelator;\n close(): Promise<void>;\n}\n\nexport interface CaptureEngineOptions extends Partial<CaptureWorkerConfig> {\n storage?: TransactionStorage;\n}\n\n/**\n * High-level coordinator orchestrating browser automation, CDP network interception,\n * event correlation, and transaction storage.\n */\nexport class CaptureEngine {\n private readonly browserManager: BrowserManager;\n private readonly storage: TransactionStorage;\n private readonly bodyResolver: ResponseBodyResolver;\n private readonly activeSessions = new Set<CaptureSession>();\n private state: WorkerLifecycleState = 'uninitialized';\n\n constructor(options?: CaptureEngineOptions) {\n this.browserManager = new BrowserManager(options);\n this.storage =\n options?.storage ??\n new InMemoryTransactionStorage({\n maxCapacity: options?.maxStoredTransactions ?? 1000,\n });\n this.bodyResolver = new ResponseBodyResolver({\n maxBodySizeBytes: options?.maxBodySizeBytes,\n });\n }\n\n public getState(): WorkerLifecycleState {\n return this.state;\n }\n\n public getStorage(): TransactionStorage {\n return this.storage;\n }\n\n /**\n * Initializes browser runtime.\n */\n public async start(): Promise<void> {\n if (this.state === 'running' || this.state === 'starting') {\n return;\n }\n\n this.state = 'starting';\n try {\n await this.browserManager.start();\n this.state = 'running';\n console.log('[CaptureEngine] Capture engine initialized successfully.');\n } catch (error) {\n this.state = 'error';\n console.error('[CaptureEngine] Failed to initialize capture engine:', error);\n await this.stop();\n throw error;\n }\n }\n\n /**\n * Creates an instrumented page with network capture actively running.\n */\n public async createCaptureSession(url?: string): Promise<CaptureSession> {\n if (this.state !== 'running') {\n throw new Error(`CaptureEngine is not running. Current state: ${this.state}`);\n }\n\n const managed: ManagedSession = await this.browserManager.createSession();\n const correlator = new TransactionCorrelator(\n managed.cdpSession,\n this.storage,\n this.bodyResolver\n );\n const interceptor = new NetworkInterceptor(managed.cdpSession, correlator);\n\n // Attach CDP network domain before navigation to ensure zero dropped packets\n await interceptor.attach();\n\n const session: CaptureSession = {\n page: managed.page,\n cdpSession: managed.cdpSession,\n interceptor,\n correlator,\n close: async () => {\n this.activeSessions.delete(session);\n await interceptor.detach().catch(() => {});\n await this.browserManager.closeSession(managed).catch(() => {});\n },\n };\n\n this.activeSessions.add(session);\n\n managed.page.once('close', () => {\n this.activeSessions.delete(session);\n void interceptor.detach().catch(() => {});\n });\n\n if (url) {\n await managed.page.goto(url, { waitUntil: 'domcontentloaded' });\n }\n\n return session;\n }\n\n /**\n * Gracefully shuts down all sessions, interceptors, and the browser process.\n */\n public async stop(): Promise<void> {\n if (this.state === 'stopping' || this.state === 'stopped') {\n return;\n }\n\n this.state = 'stopping';\n console.log('[CaptureEngine] Stopping capture engine and clearing sessions...');\n\n try {\n for (const session of Array.from(this.activeSessions)) {\n await session.close().catch(() => {});\n }\n this.activeSessions.clear();\n\n await this.browserManager.stop().catch(() => {});\n this.state = 'stopped';\n console.log('[CaptureEngine] Capture engine stopped gracefully.');\n } catch (error) {\n this.state = 'error';\n console.error('[CaptureEngine] Error while stopping capture engine:', error);\n throw error;\n }\n }\n}\n\n","export type ShutdownHandler = (signal: string) => Promise<void>;\n\n/**\n * Manages clean OS signal trapping, exception monitoring, and orderly exit.\n */\nexport class ProcessLifecycle {\n private static isShuttingDown = false;\n\n public static register(handler: ShutdownHandler): () => void {\n const onSignal = (signal: string) => {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n console.log(`\\n[ProcessLifecycle] Received ${signal}. Initiating orderly teardown...`);\n\n handler(signal)\n .then(() => {\n process.exit(0);\n })\n .catch((err) => {\n console.error('[ProcessLifecycle] Error during teardown:', err);\n process.exit(1);\n });\n };\n\n const sigintListener = () => onSignal('SIGINT');\n const sigtermListener = () => onSignal('SIGTERM');\n\n const unhandledRejectionListener = (reason: unknown) => {\n console.error('[ProcessLifecycle] Unhandled Rejection:', reason);\n };\n\n const uncaughtExceptionListener = (error: Error) => {\n console.error('[ProcessLifecycle] Uncaught Exception:', error);\n onSignal('uncaughtException');\n };\n\n process.on('SIGINT', sigintListener);\n process.on('SIGTERM', sigtermListener);\n process.on('unhandledRejection', unhandledRejectionListener);\n process.on('uncaughtException', uncaughtExceptionListener);\n\n return () => {\n process.off('SIGINT', sigintListener);\n process.off('SIGTERM', sigtermListener);\n process.off('unhandledRejection', unhandledRejectionListener);\n process.off('uncaughtException', uncaughtExceptionListener);\n };\n }\n\n public static resetForTesting(): void {\n this.isShuttingDown = false;\n }\n}\n\n","import type { BrowserContext, Page } from 'playwright';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport {\n InMemoryTransactionStorage,\n NetworkInterceptor,\n ResponseBodyResolver,\n TransactionCorrelator,\n} from '@luxray/capture-worker';\n\nexport interface TaskCaptureOptions {\n /** Transactions retained in memory for one task. */\n readonly maxTransactions?: number;\n readonly maxBodySizeBytes?: number;\n}\n\n/**\n * Wires the existing capture engine's CDP interceptor into one task context.\n *\n * The engine is reused rather than reimplemented: request/response correlation,\n * redirect handling and body decoding are the parts Milestone 1 already proved.\n * What this class adds is attribution: transactions are collected into a\n * per-page window so an observation can say how much network traffic that page\n * produced.\n */\nexport class TaskCapture {\n private readonly all = new Map<string, CapturedTransaction>();\n private current = new Map<string, CapturedTransaction>();\n private disposed = false;\n\n private constructor(\n private readonly cdpSession: Awaited<ReturnType<BrowserContext['newCDPSession']>>,\n private readonly interceptor: NetworkInterceptor,\n private readonly correlator: TransactionCorrelator,\n private readonly storage: InMemoryTransactionStorage,\n ) {\n this.storage.onTransaction((transaction) => {\n if (this.disposed) return;\n this.all.set(transaction.id, transaction);\n this.current.set(transaction.id, transaction);\n });\n }\n\n public static async attach(\n context: BrowserContext,\n page: Page,\n options?: TaskCaptureOptions,\n ): Promise<TaskCapture> {\n const cdpSession = await context.newCDPSession(page);\n const storage = new InMemoryTransactionStorage({\n maxCapacity: options?.maxTransactions ?? 5_000,\n });\n const correlator = new TransactionCorrelator(\n cdpSession,\n storage,\n new ResponseBodyResolver({ maxBodySizeBytes: options?.maxBodySizeBytes }),\n );\n const interceptor = new NetworkInterceptor(cdpSession, correlator);\n await interceptor.attach();\n return new TaskCapture(cdpSession, interceptor, correlator, storage);\n }\n\n /** Starts a fresh attribution window for the next navigation. */\n public beginPage(): void {\n this.current = new Map();\n }\n\n /**\n * Ends the window and returns every transaction seen in it. Sub-resources that\n * finish after this call are attributed to the next page; that only affects\n * counters, never crawl decisions.\n */\n public endPage(): CapturedTransaction[] {\n const transactions = Array.from(this.current.values());\n this.current = new Map();\n return transactions;\n }\n\n public allTransactions(): CapturedTransaction[] {\n return Array.from(this.all.values());\n }\n\n public async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n await this.interceptor.detach().catch(() => {});\n this.correlator.cleanup();\n await this.cdpSession.detach().catch(() => {});\n }\n}\n","export interface FrontierEntry {\n readonly url: string;\n readonly depth: number;\n}\n\n/**\n * Breadth-first frontier with canonical-URL deduplication.\n *\n * BFS rather than DFS keeps page order reproducible and makes \"closest pages\n * first\" true when a page limit truncates the crawl.\n */\nexport class Frontier {\n private readonly queue: FrontierEntry[] = [];\n private readonly seen = new Set<string>();\n\n constructor(\n startUrl: string,\n private readonly maxDepth: number,\n ) {\n this.enqueue(startUrl, 0);\n }\n\n /** Returns false when the URL was already scheduled or is too deep. */\n public enqueue(url: string, depth: number): boolean {\n if (depth > this.maxDepth) return false;\n if (this.seen.has(url)) return false;\n this.seen.add(url);\n this.queue.push({ url, depth });\n return true;\n }\n\n public next(): FrontierEntry | null {\n return this.queue.shift() ?? null;\n }\n\n public has(url: string): boolean {\n return this.seen.has(url);\n }\n\n public get size(): number {\n return this.queue.length;\n }\n\n public get scheduled(): number {\n return this.seen.size;\n }\n}\n","/**\n * URL canonicalization for deterministic crawls.\n *\n * Two spellings of the same resource must map to one string, otherwise the\n * frontier grows with duplicates and the same page is fetched repeatedly. The\n * rules here are deliberately conservative and documented: anything they drop\n * is either meaningless to an origin server or is a known tracking parameter.\n */\n\nconst DEFAULT_PORTS: Record<string, string> = {\n 'http:': '80',\n 'https:': '443',\n};\n\n/**\n * Query parameters that identify a campaign, not a resource. Removing them\n * keeps `?utm_source=x` from being crawled as a separate page from `/`.\n */\nconst TRACKING_PARAM_PREFIXES = ['utm_'];\nconst TRACKING_PARAMS = new Set(['fbclid', 'gclid', 'mc_cid', 'mc_eid', 'igshid']);\n\nexport interface CanonicalizeOptions {\n /** Base used to resolve relative URLs. Omit for absolute-only input. */\n readonly base?: string;\n}\n\n/**\n * Returns the canonical absolute form of an http(s) URL, or null when the input\n * is not an http(s) URL (mailto:, javascript:, data:, malformed...).\n */\nexport function canonicalizeUrl(raw: string, options?: CanonicalizeOptions): string | null {\n let parsed: URL;\n try {\n parsed = options?.base ? new URL(raw, options.base) : new URL(raw);\n } catch {\n return null;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;\n\n const url = new URL(parsed.toString());\n url.protocol = url.protocol.toLowerCase();\n url.hostname = url.hostname.toLowerCase();\n url.hash = '';\n\n // `URL` already drops the port when it equals the scheme default, but an\n // explicit default port in the input must not survive as a difference.\n const defaultPort = DEFAULT_PORTS[url.protocol];\n if (defaultPort && url.port === defaultPort) url.port = '';\n\n // Duplicate slashes are the same path for every server we target.\n url.pathname = url.pathname.replace(/\\/{2,}/g, '/');\n if (url.pathname.length > 1 && url.pathname.endsWith('/')) {\n url.pathname = url.pathname.slice(0, -1);\n }\n\n // Stable query order: two URLs with the same parameters in a different order\n // are the same resource.\n const entries = Array.from(url.searchParams.entries()).filter(([key]) => !isTrackingParam(key));\n entries.sort(([aKey, aValue], [bKey, bValue]) => {\n if (aKey === bKey) return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;\n return aKey < bKey ? -1 : 1;\n });\n url.search = '';\n for (const [key, value] of entries) {\n url.searchParams.append(key, value);\n }\n\n return url.toString();\n}\n\nfunction isTrackingParam(key: string): boolean {\n const normalized = key.toLowerCase();\n if (TRACKING_PARAMS.has(normalized)) return true;\n return TRACKING_PARAM_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** Hostname of a canonical URL, or null when it cannot be parsed. */\nexport function hostnameOf(url: string): string | null {\n try {\n return new URL(url).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n","import { hostnameOf } from './url-canonicalizer.js';\n\nexport interface CrawlScope {\n readonly allowedDomains: readonly string[];\n readonly includeSubdomains: boolean;\n}\n\n/**\n * Hosts that answer with cloud credentials rather than application data. A\n * crawl must never reach them, even when the operator put the whole domain in\n * scope: `169.254.169.254` is the EC2/GCP metadata service.\n */\nconst BLOCKED_HOSTS = new Set([\n 'metadata.google.internal',\n 'metadata.goog',\n 'instance-data',\n '169.254.169.254',\n '100.100.100.200',\n 'fd00:ec2::254',\n]);\n\n/** Link-local ranges, where metadata endpoints live. */\nfunction isLinkLocal(host: string): boolean {\n return host.startsWith('169.254.') || host.startsWith('fe80:') || host.startsWith('[fe80:');\n}\n\nexport function isBlockedHost(host: string): boolean {\n const normalized = host.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (BLOCKED_HOSTS.has(host.toLowerCase()) || BLOCKED_HOSTS.has(normalized)) return true;\n return isLinkLocal(normalized);\n}\n\n/**\n * True when a canonical URL may be crawled under this scope. The start host is\n * always allowed (the caller puts it in `allowedDomains`).\n */\nexport function isUrlInScope(url: string, scope: CrawlScope): boolean {\n const host = hostnameOf(url);\n if (!host) return false;\n if (isBlockedHost(host)) return false;\n\n return scope.allowedDomains.some((domain) => {\n if (host === domain) return true;\n return scope.includeSubdomains && host.endsWith(`.${domain}`);\n });\n}\n\n/** Extracts the hostname to treat as the crawl origin. */\nexport function startHostname(startUrl: string): string {\n const host = hostnameOf(startUrl);\n if (!host) {\n throw new Error(`Cannot determine the hostname of ${startUrl}.`);\n }\n return host;\n}\n\nexport function assertCrawlTarget(url: string): void {\n const host = hostnameOf(url);\n if (!host) {\n throw new Error(`Refusing to crawl an invalid URL: ${url}`);\n }\n if (isBlockedHost(host)) {\n throw new Error(\n `Refusing to crawl ${host}: it is a cloud metadata endpoint and must never be fetched.`,\n );\n }\n}\n","import type { Page } from 'playwright';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport { signIn, type LoginResult, type SiteCredentials } from '../auth/login.js';\nimport type { AuthCookie, TaskBrowser } from '../browser/task-browser.js';\nimport {\n extractJsonLinks,\n jsonDocumentFingerprint,\n readPageSnapshot,\n structuralFingerprint,\n} from '../browser/page-snapshot.js';\nimport { TaskCapture } from '../browser/task-capture.js';\nimport { ExplorationAbortedError } from '../errors.js';\nimport { Frontier } from './frontier.js';\nimport { canonicalizeUrl } from './url-canonicalizer.js';\nimport { isUrlInScope, type CrawlScope } from './url-policy.js';\nimport {\n type AuthenticationSummary,\n type ExplorationLimits,\n type ExplorationRun,\n type PageObservation,\n} from './types.js';\n\nexport interface CrawlLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/**\n * Operator-supplied authentication, applied before the first page is observed.\n *\n * Two shapes are supported and they are deliberately exclusive: a form sign-in\n * is a sequence of interactions, while auth keys are values the browser sends\n * with every request. Passing both would make it ambiguous which one the site\n * actually accepted, and the run record has to say something true.\n */\nexport interface CrawlAuthOptions {\n /** Form sign-in. */\n readonly credentials?: SiteCredentials;\n /** Defaults to the crawl's start URL. */\n readonly loginUrl?: string;\n readonly submitTimeoutMs?: number;\n readonly manualAssist?: () => Promise<void>;\n /** Arbitrary request headers, e.g. `Authorization: Bearer …`. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cookies installed on the task context before the first navigation. */\n readonly cookies?: readonly AuthCookie[];\n}\n\nexport interface CrawlOptions {\n readonly limits: ExplorationLimits;\n readonly scope: CrawlScope;\n readonly signal?: AbortSignal;\n readonly onProgress?: (percent: number, message: string) => void;\n readonly onCheckpoint?: (label: string, state: Record<string, unknown>) => void;\n /**\n * Fires once per observation, in visit order.\n *\n * A transport failure here must never abort a crawl: the artifact directory\n * is still the full record, and the page can be replayed from it. The crawler\n * therefore swallows hook errors and logs them.\n */\n readonly onPage?: (page: PageObservation, sequence: number) => void;\n readonly logger?: CrawlLogger;\n readonly auth?: CrawlAuthOptions;\n /** Restore a saved session instead of signing in. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n}\n\nexport interface CrawlOutcome {\n readonly run: ExplorationRun;\n readonly transactions: readonly CapturedTransaction[];\n}\n\nconst RECENT_URLS_IN_CHECKPOINT = 10;\nconst BODY_SETTLE_GRACE_MS = 250;\n\ninterface ObservationResult {\n readonly observation: PageObservation;\n /** Links to follow, already canonical and in scope. Empty for duplicates. */\n readonly nextUrls: readonly string[];\n}\n\n/**\n * Deterministic breadth-first discovery.\n *\n * The rule set is mechanical on purpose: follow in-scope links, hash the\n * rendered structure, and stop expanding pages that repeat a template already\n * seen. No model decides what to click, so the same site produces the same order\n * and any failure is explainable by a URL and a limit.\n */\nexport class DeterministicCrawler {\n constructor(\n private readonly browser: TaskBrowser,\n private readonly options: CrawlOptions,\n ) {}\n\n public async run(startUrl: string): Promise<CrawlOutcome> {\n const { limits, scope, signal, onProgress, onCheckpoint, onPage, logger } = this.options;\n\n const canonicalStart = canonicalizeUrl(startUrl);\n if (!canonicalStart) {\n throw new Error(`Cannot explore ${startUrl}: it is not a valid http(s) URL.`);\n }\n if (!isUrlInScope(canonicalStart, scope)) {\n throw new Error(\n `${canonicalStart} is outside the allowed domains (${scope.allowedDomains.join(', ')}).`,\n );\n }\n\n const authOptions = this.options.auth;\n const authHeaders = authOptions?.headers ?? {};\n const authCookies = authOptions?.cookies ?? [];\n const headerCount = Object.keys(authHeaders).length;\n const keyAuth = headerCount > 0 || authCookies.length > 0;\n const formAuth = Boolean(authOptions?.credentials);\n\n if (keyAuth && formAuth) {\n throw new Error(\n 'Pass either sign-in credentials (--login-url/--username) or auth keys ' +\n '(--auth-header/--auth-cookie), not both.',\n );\n }\n\n const context = await this.browser.openTaskContext({\n storageState: this.options.storageStatePath,\n headers: authHeaders,\n cookies: authCookies,\n cookieUrl: canonicalStart,\n });\n\n let authentication: AuthenticationSummary | null = keyAuth\n ? {\n strategy: headerCount > 0 ? 'headers' : 'cookies',\n loginUrl: null,\n finalUrl: null,\n cookies: authCookies.length,\n headers: headerCount,\n }\n : this.options.storageStatePath\n ? { strategy: 'session', loginUrl: null, finalUrl: null, cookies: null, headers: 0 }\n : null;\n\n // Sign in before the crawl page exists. The sign-in runs on its own page,\n // so the credential POST is never attributed to a crawl window or written\n // to the artifacts.\n if (formAuth && authOptions?.credentials) {\n const loginUrl = authOptions.loginUrl ?? canonicalStart;\n onProgress?.(0, `Signing in at ${loginUrl}`);\n logger?.info(`Signing in at ${loginUrl} before crawling.`);\n let signedIn: LoginResult;\n try {\n signedIn = await signIn(context, {\n loginUrl,\n credentials: authOptions.credentials,\n pageTimeoutMs: limits.pageTimeoutMs,\n submitTimeoutMs: authOptions.submitTimeoutMs,\n manualAssist: authOptions.manualAssist,\n signal,\n logger,\n });\n } catch (err) {\n await context.close().catch(() => {});\n throw err;\n }\n\n authentication = {\n strategy: signedIn.strategy,\n loginUrl: signedIn.loginUrl,\n finalUrl: signedIn.finalUrl,\n cookies: signedIn.cookies,\n headers: 0,\n };\n logger?.info(\n `Signed in (${signedIn.strategy}); ${signedIn.cookies} cookie(s) in the task context.`,\n );\n\n if (this.options.saveStorageStatePath) {\n try {\n await context.storageState({ path: this.options.saveStorageStatePath });\n logger?.info(`Session saved to ${this.options.saveStorageStatePath}.`);\n } catch (err) {\n logger?.warn(`Could not save the session: ${(err as Error).message}`);\n }\n }\n }\n\n // A crawl with no auth at all is expected to meet sign-in walls; it must\n // mark them instead of counting the login form as the page it asked for.\n const anonymous = authentication === null;\n\n const page = await context.newPage();\n const capture = await TaskCapture.attach(context, page);\n const abort = (): void => {\n // Closing the context is what interrupts a hung navigation; the loop below\n // only checks the flag between pages.\n void context.close().catch(() => {});\n };\n signal?.addEventListener('abort', abort, { once: true });\n\n const startedAt = Date.now();\n const frontier = new Frontier(canonicalStart, limits.maxDepth);\n const pages: PageObservation[] = [];\n const fingerprints = new Map<string, string>();\n let transactionsCaptured = 0;\n let linksDiscovered = 0;\n let truncatedByLimit = false;\n\n try {\n onProgress?.(0, `Opening ${canonicalStart}`);\n logger?.info(\n `Exploring ${canonicalStart} (max ${limits.maxPages} pages, depth ${limits.maxDepth}).`,\n );\n\n while (true) {\n if (signal?.aborted) throw new ExplorationAbortedError();\n\n if (pages.length >= limits.maxPages) {\n truncatedByLimit = frontier.size > 0;\n logger?.info(`Page limit reached (${limits.maxPages}); stopping.`);\n break;\n }\n const elapsed = Date.now() - startedAt;\n if (elapsed >= limits.maxDurationMs) {\n truncatedByLimit = frontier.size > 0;\n logger?.warn(`Time limit reached after ${elapsed}ms; stopping.`);\n break;\n }\n\n const entry = frontier.next();\n if (!entry) break;\n\n const { observation, nextUrls } = await this.observe(\n page,\n capture,\n entry.url,\n entry.depth,\n fingerprints,\n signal,\n anonymous,\n );\n pages.push(observation);\n transactionsCaptured += observation.transactions;\n linksDiscovered += observation.linksFound;\n\n let queued = 0;\n for (const nextUrl of nextUrls) {\n if (frontier.enqueue(nextUrl, entry.depth + 1)) queued += 1;\n }\n const recorded: PageObservation = { ...observation, linksQueued: queued };\n pages[pages.length - 1] = recorded;\n\n if (onPage) {\n try {\n onPage(recorded, pages.length);\n } catch (err) {\n logger?.warn(\n `Page hook failed for ${entry.url}: ${(err as Error).message}. Continuing the crawl.`,\n );\n }\n }\n\n const percent = Math.min(\n 95,\n Math.floor((pages.length / Math.max(1, limits.maxPages)) * 100),\n );\n const suffix = observation.authRequired\n ? ' (authentication required; skipped)'\n : observation.error\n ? ` (failed: ${observation.error})`\n : observation.duplicateOf\n ? ` (duplicate template of ${observation.duplicateOf}, links not followed)`\n : ` (+${queued} links, ${observation.transactions} requests)`;\n onProgress?.(percent, `page ${pages.length}/${limits.maxPages} — ${entry.url}${suffix}`);\n logger?.info(`[${pages.length}/${limits.maxPages}] ${entry.url}${suffix}`);\n\n if (onCheckpoint && pages.length % limits.checkpointEveryPages === 0) {\n onCheckpoint(`pages:${pages.length}`, {\n startUrl: canonicalStart,\n pagesVisited: pages.length,\n pagesFailed: pages.filter((item) => item.error !== null).length,\n duplicatePages: pages.filter((item) => item.duplicateOf !== null).length,\n transactionsCaptured,\n linksDiscovered,\n frontierQueued: frontier.size,\n frontierScheduled: frontier.scheduled,\n recentUrls: pages.slice(-RECENT_URLS_IN_CHECKPOINT).map((item) => item.url),\n elapsedMs: Date.now() - startedAt,\n });\n }\n }\n\n const finishedAt = Date.now();\n const run: ExplorationRun = {\n summary: {\n startUrl: canonicalStart,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n pagesVisited: pages.length,\n pagesFailed: pages.filter((item) => item.error !== null).length,\n duplicatePages: pages.filter((item) => item.duplicateOf !== null).length,\n transactionsCaptured,\n linksDiscovered,\n frontierRemaining: frontier.size,\n limits,\n artifactDir: '',\n truncatedByLimit,\n authentication: authentication,\n },\n pages,\n scope,\n };\n\n return { run, transactions: capture.allTransactions() };\n } finally {\n signal?.removeEventListener('abort', abort);\n await capture.dispose().catch(() => {});\n await context.close().catch(() => {});\n }\n }\n\n private async observe(\n page: Page,\n capture: TaskCapture,\n url: string,\n depth: number,\n fingerprints: Map<string, string>,\n signal: AbortSignal | undefined,\n anonymous: boolean,\n ): Promise<ObservationResult> {\n const { limits, scope } = this.options;\n const observedAt = Date.now();\n capture.beginPage();\n\n let httpStatus: number | null = null;\n let title: string | null = null;\n let hrefs: readonly string[] = [];\n let fingerprint = 'unavailable';\n let duplicateOf: string | null = null;\n let error: string | null = null;\n let authRequired = false;\n\n try {\n const response = await page.goto(url, {\n waitUntil: 'domcontentloaded',\n timeout: limits.pageTimeoutMs,\n });\n httpStatus = response?.status() ?? null;\n\n // Best effort: apps with long-lived connections never reach network idle,\n // so this wait is bounded and its timeout is not an error.\n await page\n .waitForLoadState('networkidle', { timeout: limits.settleTimeoutMs })\n .catch(() => {});\n await new Promise((resolve) => setTimeout(resolve, BODY_SETTLE_GRACE_MS));\n\n if (signal?.aborted) throw new ExplorationAbortedError();\n\n const snapshot = await readPageSnapshot(page);\n title = snapshot.title;\n\n // JSON documents have no anchors; the payload itself is the link index.\n // Candidates go through the same canonicalization and scope filter below,\n // and `linksFound` counts both sources because both were discovered.\n const jsonLinks =\n snapshot.jsonBody === null ? [] : extractJsonLinks(snapshot.jsonBody);\n hrefs = [...snapshot.links, ...jsonLinks];\n\n // The JSON viewer's markup is identical for every response, so the\n // structure hash would collapse unrelated endpoints into one duplicate.\n fingerprint =\n snapshot.jsonBody === null\n ? structuralFingerprint(snapshot.structure)\n : jsonDocumentFingerprint(snapshot.jsonBody);\n\n if (snapshot.jsonBodyTruncated) {\n this.options.logger?.debug(\n `JSON body at ${url} exceeded the snapshot limit; fingerprint truncated, links not mined.`,\n );\n }\n\n // Only an unauthenticated crawl can be \"walled\": with a session or keys,\n // a password field is ordinary page content (change password, admin).\n authRequired =\n anonymous &&\n (snapshot.hasPasswordField || isAuthRedirect(url, page.url()));\n } catch (err) {\n if (signal?.aborted || err instanceof ExplorationAbortedError) {\n throw new ExplorationAbortedError();\n }\n error = errorMessage(err);\n }\n\n // A walled page is not the page the frontier asked for, and its links lead\n // back into the gate. It is recorded as gated rather than expanded.\n if (error === null && !authRequired) {\n const seenOn = fingerprints.get(fingerprint);\n if (seenOn === undefined) {\n fingerprints.set(fingerprint, url);\n } else {\n duplicateOf = seenOn;\n }\n }\n\n const transactions = capture.endPage();\n const nextUrls =\n duplicateOf === null && error === null && !authRequired\n ? this.resolveLinks(hrefs, url, scope)\n : [];\n\n return {\n observation: {\n url,\n requestedUrl: url,\n depth,\n httpStatus,\n title,\n fingerprint,\n duplicateOf,\n linksFound: hrefs.length,\n linksQueued: 0,\n transactions: transactions.length,\n durationMs: Date.now() - observedAt,\n observedAt,\n error,\n authRequired: authRequired,\n },\n nextUrls,\n };\n }\n\n private resolveLinks(\n hrefs: readonly string[],\n baseUrl: string,\n scope: CrawlScope,\n ): readonly string[] {\n const resolved: string[] = [];\n const unique = new Set<string>();\n for (const href of hrefs) {\n const canonical = canonicalizeUrl(href, { base: baseUrl });\n if (!canonical) continue;\n if (!isUrlInScope(canonical, scope)) continue;\n if (unique.has(canonical)) continue;\n unique.add(canonical);\n resolved.push(canonical);\n }\n return resolved;\n }\n}\n\nfunction errorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.length > 500 ? `${message.slice(0, 500)}…` : message;\n}\n\n/**\n * Sign-in paths seen in the wild, as a path segment.\n *\n * Kept narrow on purpose: `/account` or `/auth-docs` are ordinary pages, so the\n * segment must be one of these exact names. A false positive would hide a page\n * from the crawl, which is worse than crawling one login form.\n */\nconst AUTH_PATH_SEGMENT =\n /(?:^|\\/)(?:login|log-in|log_in|signin|sign-in|sign_in|sso|session|oauth2?|authorize)(?:\\/|$)/i;\n\n/** True when a navigation was redirected to a sign-in route. */\nfunction isAuthRedirect(requestedUrl: string, finalUrl: string): boolean {\n if (finalUrl === requestedUrl) return false;\n try {\n return AUTH_PATH_SEGMENT.test(new URL(finalUrl).pathname);\n } catch {\n return false;\n }\n}\n","/**\n * Bounds for one deterministic exploration run.\n *\n * Every limit is enforced locally by the worker; the control plane also stores\n * `scope.maxPages` and `scope.maxDepth` with the task, and the runner passes\n * those values in. The remaining limits protect the machine the agent runs on,\n * so they are local defaults rather than task data.\n */\nexport interface ExplorationLimits {\n readonly maxPages: number;\n readonly maxDepth: number;\n /** Navigation timeout for a single page. */\n readonly pageTimeoutMs: number;\n /** How long to wait for quiet network after DOM content loaded. */\n readonly settleTimeoutMs: number;\n /** Hard wall-clock limit for the whole run. */\n readonly maxDurationMs: number;\n /** Emit a durable checkpoint every N visited pages. */\n readonly checkpointEveryPages: number;\n}\n\nexport const DEFAULT_EXPLORATION_LIMITS: ExplorationLimits = Object.freeze({\n maxPages: 25,\n maxDepth: 2,\n pageTimeoutMs: 20_000,\n settleTimeoutMs: 3_000,\n maxDurationMs: 8 * 60_000,\n checkpointEveryPages: 5,\n});\n\nexport interface ExplorationScope {\n readonly allowedDomains: readonly string[];\n readonly includeSubdomains: boolean;\n}\n\n/** One page the crawl actually loaded and observed. */\nexport interface PageObservation {\n /** Canonical URL used as the dedupe key. */\n readonly url: string;\n /** URL the browser was asked for, before canonicalization. */\n readonly requestedUrl: string;\n readonly depth: number;\n readonly httpStatus: number | null;\n readonly title: string | null;\n /** Structural hash of the rendered DOM; identical pages share a hash. */\n readonly fingerprint: string;\n /** First page with the same fingerprint, when this page was a duplicate. */\n readonly duplicateOf: string | null;\n readonly linksFound: number;\n readonly linksQueued: number;\n readonly transactions: number;\n readonly durationMs: number;\n readonly observedAt: number;\n readonly error: string | null;\n /**\n * True when the response was a sign-in wall rather than the page's content.\n *\n * Anonymous crawls mark these instead of counting the login form as the\n * visited page, so a dashboard can tell \"not crawled\" from \"crawled empty\".\n */\n readonly authRequired: boolean;\n}\n\nexport interface ExplorationRunSummary {\n readonly startUrl: string;\n readonly startedAt: number;\n readonly finishedAt: number;\n readonly durationMs: number;\n readonly pagesVisited: number;\n readonly pagesFailed: number;\n readonly duplicatePages: number;\n readonly transactionsCaptured: number;\n readonly linksDiscovered: number;\n readonly frontierRemaining: number;\n readonly limits: ExplorationLimits;\n readonly artifactDir: string;\n /** True when a limit stopped the crawl rather than an empty frontier. */\n readonly truncatedByLimit: boolean;\n /**\n * Present when the operator asked for a signed-in crawl. Counts and URLs\n * only: credentials are never part of a run record.\n */\n readonly authentication?: AuthenticationSummary | null;\n}\n\n/**\n * What the run record may say about authentication. Counts and URLs only:\n * credential values are never part of a run record.\n *\n * `null` fields are meaningful: a headers/cookies run has no sign-in URL, and a\n * restored session's cookie count is unknown without opening the context.\n */\nexport interface AuthenticationSummary {\n readonly strategy: 'form' | 'manual' | 'headers' | 'cookies' | 'session';\n readonly loginUrl: string | null;\n readonly finalUrl: string | null;\n readonly cookies: number | null;\n /** Number of request headers supplied by the operator. */\n readonly headers: number;\n}\n\nexport interface ExplorationRun {\n readonly summary: ExplorationRunSummary;\n readonly pages: readonly PageObservation[];\n readonly scope: ExplorationScope;\n}\n","import { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type {\n CapturedTransaction,\n ExplorationOpenApiDocument,\n ExplorationOpenApiSpec,\n} from '@luxray/shared';\nimport { EndpointAggregator, EndpointNormalizer } from '@luxray/normalization';\nimport {\n OpenApiGenerator,\n serializeToJson,\n serializeToYaml,\n} from '@luxray/openapi-generator';\nimport { RelationshipDiscoveryEngine } from '@luxray/relationship-discovery';\nimport { SchemaInferenceEngine } from '@luxray/schema-inference';\n\n/**\n * Budget for the two documents carried in one completion frame.\n *\n * Kafka's default record limit is 1 MiB. The structured report already takes\n * up to 64 KiB of the frame, and the envelope adds a little more, so the specs\n * are held well below the limit instead of relying on broker configuration.\n */\nexport const OPENAPI_TRANSPORT_BUDGET_BYTES = 768 * 1024;\n\n/** Capture resource types that represent programmatic API traffic. */\nconst API_RESOURCE_TYPES = new Set(['xhr', 'fetch']);\n\n/**\n * Resource types that are the operation itself rather than a page load.\n *\n * On an API-first host the address bar is the only client, so every endpoint a\n * crawl visits arrives as a `document` navigation. A JSON payload proves the\n * response is data, not markup, which is enough to document it.\n */\nconst DATA_DOCUMENT_RESOURCE_TYPES = new Set(['document']);\n\n/** Response media types that are never API payloads worth documenting. */\nconst NON_API_MIME_PREFIXES = ['image/', 'audio/', 'video/', 'font/'];\n\nexport interface GenerateOpenApiSpecInput {\n readonly taskId: string;\n readonly attempt: number;\n readonly startUrl: string;\n /** Document title; usually the task name. */\n readonly title: string;\n readonly transactions: readonly CapturedTransaction[];\n readonly now?: () => number;\n}\n\n/**\n * True when a captured transaction belongs in the discovered API contract.\n *\n * The crawler captures everything the browser loaded, including images and\n * stylesheets. An OpenAPI document built from those would describe the site's\n * assets rather than its API, so only programmatic requests are considered.\n * Redirects are dropped because the hop is transport, not an operation.\n */\nexport function isExportableApiTransaction(transaction: CapturedTransaction): boolean {\n if (transaction.status !== 'completed') return false;\n if (!transaction.response) return false;\n if (transaction.isRedirect) return false;\n\n const method = String(transaction.request.method).toUpperCase();\n if (method === 'OPTIONS' || method === 'HEAD') return false;\n\n const status = transaction.response.status;\n if (status <= 0 || (status >= 300 && status < 400)) return false;\n\n try {\n const url = new URL(transaction.request.url);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;\n } catch {\n return false;\n }\n\n const mime = responseMimeType(transaction);\n if (NON_API_MIME_PREFIXES.some((prefix) => mime.startsWith(prefix))) return false;\n\n const resourceType = (transaction.resourceType ?? '').trim().toLowerCase();\n if (resourceType.length > 0) {\n if (API_RESOURCE_TYPES.has(resourceType)) return true;\n // A direct navigation to a JSON response is still an operation: API-first\n // hosts have no HTML shell to issue an XHR. HTML documents stay excluded.\n return DATA_DOCUMENT_RESOURCE_TYPES.has(resourceType) && mime.includes('json');\n }\n\n // Older capture records may omit the CDP resource type. Fall back to the\n // payload itself rather than silently dropping genuine API traffic.\n return mime.includes('json');\n}\n\n/**\n * Runs the deterministic discovery pipeline over an exploration's traffic and\n * serializes the result as OpenAPI 3.1.0 JSON and YAML.\n *\n * Returns null when nothing survived filtering: a crawl of a purely\n * server-rendered site has no API to document, and an empty specification\n * would be a misleading artifact.\n */\nexport function generateOpenApiSpec(\n input: GenerateOpenApiSpecInput,\n): ExplorationOpenApiSpec | null {\n const transactions = orderTransactions(\n dedupeTransactions(input.transactions.filter(isExportableApiTransaction)),\n );\n if (transactions.length === 0) return null;\n\n // One normalizer instance for both engines: the schema aggregate is keyed by\n // the same endpoint identity the aggregator produced, which is what lets the\n // generator join operations to request/response schemas.\n const normalizer = new EndpointNormalizer();\n const aggregator = new EndpointAggregator(normalizer);\n const schemas = new SchemaInferenceEngine({ normalizer });\n\n for (const transaction of transactions) {\n aggregator.ingest(transaction);\n schemas.ingestTransaction(transaction);\n }\n\n const endpoints = aggregator.getAll();\n const schemaAggregates = schemas.getAllAggregates();\n\n const discovery = new RelationshipDiscoveryEngine();\n discovery.registerEndpoints(endpoints);\n discovery.registerSchemas(schemaAggregates);\n const relationships = discovery.discoverRelationships();\n\n const generator = new OpenApiGenerator({\n openApiVersion: '3.1.0',\n info: {\n title: input.title,\n version: '1.0.0',\n description:\n `Discovered by Luxray from ${transactions.length} captured API transaction(s) ` +\n `during a crawl of ${input.startUrl}.`,\n },\n });\n\n const generationInput = { endpoints, schemas: schemaAggregates, relationships };\n const generatedAt = (input.now ?? Date.now)();\n\n // One document, two serializations. The generator stamps the document with\n // its own wall-clock time; that would make the same traffic produce\n // different bytes on every run, so the crawl's clock is written instead. The\n // timestamp is metadata, not API structure, and pinning it makes a spec\n // reproducible from the same traffic.\n const document = generator.generate(generationInput);\n document['x-luxray-generated-at'] = generatedAt;\n\n const json = toDocument('json', 'application/json', serializeToJson(document));\n const yaml = toDocument('yaml', 'application/yaml', serializeToYaml(document));\n\n return {\n version: 1,\n taskId: input.taskId,\n attempt: input.attempt,\n summary: {\n version: '3.1.0',\n endpointCount: endpoints.length,\n schemaCount: schemaAggregates.length,\n relationshipCount: relationships.length,\n sourceTransactions: transactions.length,\n generatedAt,\n jsonBytes: json.byteLength,\n yamlBytes: yaml.byteLength,\n omission: null,\n },\n json,\n yaml,\n };\n}\n\n/**\n * Applies the transport budget without truncating anything.\n *\n * A partial OpenAPI document is worse than none: it looks valid while hiding\n * operations. When both documents cannot fit, their content is omitted whole\n * and the summary records the size, so the operator can still pick the files\n * up from the agent's artifact directory.\n */\nexport function applyOpenApiTransportBudget(\n spec: ExplorationOpenApiSpec,\n limitBytes: number = OPENAPI_TRANSPORT_BUDGET_BYTES,\n): ExplorationOpenApiSpec {\n const byteLength = spec.summary.jsonBytes + spec.summary.yamlBytes;\n if (byteLength <= limitBytes) return spec;\n\n return {\n ...spec,\n json: null,\n yaml: null,\n summary: {\n ...spec.summary,\n omission: { reason: 'too-large', limitBytes, byteLength },\n },\n };\n}\n\n/**\n * Writes both serializations next to the crawl artifacts.\n *\n * These files are the operator's copy even when the documents are too large to\n * travel over the task stream.\n */\nexport async function writeOpenApiArtifacts(\n directory: string,\n spec: ExplorationOpenApiSpec,\n): Promise<{ readonly jsonPath: string; readonly yamlPath: string }> {\n if (!spec.json || !spec.yaml) {\n throw new Error('OpenAPI artifact content was omitted before it could be written.');\n }\n\n const jsonPath = join(directory, 'openapi.json');\n const yamlPath = join(directory, 'openapi.yaml');\n await writeFile(jsonPath, spec.json.content, 'utf8');\n await writeFile(yamlPath, spec.yaml.content, 'utf8');\n return { jsonPath, yamlPath };\n}\n\nfunction toDocument(\n format: ExplorationOpenApiDocument['format'],\n contentType: ExplorationOpenApiDocument['contentType'],\n content: string,\n): ExplorationOpenApiDocument {\n return {\n format,\n contentType,\n byteLength: Buffer.byteLength(content, 'utf8'),\n content,\n };\n}\n\nfunction responseMimeType(transaction: CapturedTransaction): string {\n const direct = transaction.response?.mimeType;\n if (direct) return direct.toLowerCase();\n\n const headers = transaction.response?.headers ?? {};\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() === 'content-type') return value.toLowerCase();\n }\n return '';\n}\n\nfunction dedupeTransactions(\n transactions: readonly CapturedTransaction[],\n): readonly CapturedTransaction[] {\n const seen = new Set<string>();\n const unique: CapturedTransaction[] = [];\n for (const transaction of transactions) {\n if (seen.has(transaction.id)) continue;\n seen.add(transaction.id);\n unique.push(transaction);\n }\n return unique;\n}\n\n/**\n * Visit order is whatever the capture engine produced; the pipeline needs a\n * stable order so two runs over the same traffic serialize identically.\n */\nfunction orderTransactions(\n transactions: readonly CapturedTransaction[],\n): readonly CapturedTransaction[] {\n return [...transactions].sort((left, right) => {\n const byTime = left.timing.startTime - right.timing.startTime;\n return byTime !== 0 ? byTime : left.id.localeCompare(right.id);\n });\n}\n","import type { ParsedUrl } from './types.js';\n\nconst DUMMY_BASE = 'http://localhost';\n\n/**\n * Safely decodes a URI component without throwing on malformed sequences.\n */\nexport function safeDecodeURIComponent(component: string): string {\n try {\n return decodeURIComponent(component);\n } catch {\n return component;\n }\n}\n\n/**\n * Robust, deterministic URL parser and sanitizer.\n * Complies with RFC 3986 URL semantics and normalizes whitespace, repeated slashes,\n * trailing slashes, and casing.\n */\nexport class UrlParser {\n /**\n * Parses an absolute or relative URL into a structured ParsedUrl entity.\n */\n public static parse(inputUrl: string): ParsedUrl {\n const raw = inputUrl.trim();\n let urlObj: URL;\n let isRelative = false;\n\n try {\n urlObj = new URL(raw);\n } catch {\n // Input might be a relative path like \"/api/users/123?page=1\"\n try {\n urlObj = new URL(raw.startsWith('/') ? raw : `/${raw}`, DUMMY_BASE);\n isRelative = true;\n } catch {\n // Fallback for severely malformed strings\n urlObj = new URL('/', DUMMY_BASE);\n isRelative = true;\n }\n }\n\n const protocol = isRelative ? '' : urlObj.protocol.toLowerCase();\n const hostname = isRelative ? '' : urlObj.hostname.toLowerCase();\n const port = isRelative ? '' : urlObj.port;\n\n // Build canonical origin\n let origin = '';\n if (!isRelative && hostname) {\n const hasDefaultPort =\n (protocol === 'http:' && (port === '80' || port === '')) ||\n (protocol === 'https:' && (port === '443' || port === ''));\n\n origin = hasDefaultPort || !port\n ? `${protocol}//${hostname}`\n : `${protocol}//${hostname}:${port}`;\n }\n\n // Process pathname: split into clean segments, collapsing empty ones\n const rawPath = urlObj.pathname;\n const splitSegments = rawPath.split('/');\n const cleanSegments: string[] = [];\n\n for (const segment of splitSegments) {\n if (segment.length > 0) {\n cleanSegments.push(safeDecodeURIComponent(segment));\n }\n }\n\n // Build canonical clean path (strip trailing slash unless root)\n const cleanPath = cleanSegments.length === 0 ? '/' : `/${cleanSegments.join('/')}`;\n\n // Extract query parameters\n const searchParams = new Map<string, string[]>();\n for (const [key, value] of urlObj.searchParams.entries()) {\n // Normalize array-bracket notation in key: \"filter[]\" -> \"filter\"\n const normalizedKey = key.endsWith('[]') ? key.slice(0, -2) : key;\n const existing = searchParams.get(normalizedKey);\n if (existing) {\n existing.push(value);\n } else {\n searchParams.set(normalizedKey, [value]);\n }\n }\n\n const fragment = urlObj.hash ? urlObj.hash.slice(1) : undefined;\n\n return {\n rawUrl: raw,\n protocol,\n hostname,\n port,\n origin,\n rawPath,\n cleanPath,\n segments: cleanSegments,\n searchParams,\n fragment,\n };\n }\n}\n\n","/**\n * Regular expressions and validation patterns for dynamic identifier detection.\n */\n\n// Pure integer ID (e.g. \"123\", \"4567890\")\nexport const NUMERIC_ID_REGEX = /^\\d+$/;\n\n// Standard UUID (v1-v5, case-insensitive)\nexport const UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n// Relaxed UUID (any 8-4-4-4-12 hex string)\nexport const RELAXED_UUID_REGEX =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n// ULID (26-character Crockford's Base32)\nexport const ULID_REGEX = /^[0-9A-HJ-KM-NP-Za-km-np-z]{26}$/;\n\n// MongoDB ObjectId (24 hex characters)\nexport const OBJECT_ID_REGEX = /^[0-9a-fA-F]{24}$/;\n\n// Generic long hex hash (16, 32, 40, or 64 hex characters, with at least one digit to avoid all-letter words)\nexport const HEX_HASH_REGEX = /^(?=.*\\d)[0-9a-fA-F]{16,64}$/;\n\n// Prefixed identifier (e.g. \"cus_12345\", \"ch_1A2b3C\", \"ORD-2026-001\", \"INV-2023-99\", \"USR_8899\")\nexport const PREFIXED_ID_REGEX = /^[a-zA-Z]{2,6}[-_][a-zA-Z0-9]+(-[0-9]+)*$/;\n\n// Slug pattern (words joined by hyphens)\nexport const SLUG_REGEX = /^[a-z0-9]+(-[a-z0-9]+)+$/i;\n\n// Hashid / Short alphanumeric mixed identifier (length 6 to 16, must contain both letters and numbers)\nexport const HASHID_REGEX = /^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9_-]{6,20}$/;\n\n// Version pattern: e.g. \"v1\", \"v2\", \"v1.0\", \"v2023-01-01\", \"v1beta1\"\nexport const VERSION_REGEX = /^v\\d+(\\.\\d+)?([a-zA-Z]+[0-9]*)?(-[a-zA-Z0-9]+)*$/i;\n","import { VERSION_REGEX } from './patterns.js';\n\n/**\n * Common REST actions, architectural words, and static keywords that should\n * NEVER be considered dynamic parameters even if they resemble slugs or identifiers.\n */\nexport const RESERVED_STATIC_WORDS = new Set<string>([\n // Infrastructure & routing\n 'api',\n 'rest',\n 'graphql',\n 'rpc',\n 'grpc',\n 'ws',\n 'wss',\n 'internal',\n 'admin',\n 'public',\n 'private',\n 'dev',\n 'staging',\n 'prod',\n 'v1',\n 'v2',\n 'v3',\n\n // Authentication & Session\n 'auth',\n 'oauth',\n 'oauth2',\n 'login',\n 'logout',\n 'signin',\n 'signup',\n 'signout',\n 'register',\n 'token',\n 'session',\n 'sessions',\n 'refresh',\n 'verify',\n 'verification',\n 'reset-password',\n 'forgot-password',\n 'change-password',\n 'mfa',\n '2fa',\n 'sso',\n\n // Actions & Operations\n 'new',\n 'create',\n 'edit',\n 'update',\n 'delete',\n 'destroy',\n 'remove',\n 'cancel',\n 'confirm',\n 'approve',\n 'reject',\n 'archive',\n 'archived',\n 'restore',\n 'submit',\n 'execute',\n 'run',\n 'start',\n 'stop',\n 'pause',\n 'resume',\n 'publish',\n 'unpublish',\n 'activate',\n 'deactivate',\n 'enable',\n 'disable',\n\n // Query & Data Manipulation\n 'search',\n 'query',\n 'filter',\n 'find',\n 'export',\n 'import',\n 'upload',\n 'download',\n 'sync',\n 'batch',\n 'bulk',\n 'aggregate',\n 'stats',\n 'analytics',\n 'summary',\n 'count',\n\n // Self & Metadata\n 'me',\n 'self',\n 'my',\n 'current',\n 'active',\n 'all',\n 'recent',\n 'popular',\n 'featured',\n 'trending',\n 'status',\n 'health',\n 'healthz',\n 'live',\n 'ready',\n 'ping',\n 'metrics',\n 'info',\n 'version',\n 'config',\n 'configuration',\n 'settings',\n 'profile',\n 'schema',\n 'openapi',\n 'swagger',\n 'docs',\n 'spec',\n\n // Notifications & Webhooks\n 'callback',\n 'callbacks',\n 'webhook',\n 'webhooks',\n 'notifications',\n 'alerts',\n 'events',\n 'logs',\n 'audit',\n]);\n\n/**\n * Checks whether a given path segment is a reserved static keyword or API version.\n */\nexport function isReservedStaticSegment(segment: string): boolean {\n const lower = segment.toLowerCase();\n if (RESERVED_STATIC_WORDS.has(lower)) {\n return true;\n }\n // Check version pattern: v1, v2, v2024-01-01, v1beta1, etc.\n if (VERSION_REGEX.test(segment)) {\n return true;\n }\n // Check file extensions: e.g. \"favicon.ico\", \"robots.txt\", \"data.json\"\n if (/\\.[a-zA-Z0-9]{1,5}$/.test(segment)) {\n return true;\n }\n return false;\n}\n\n","import {\n NUMERIC_ID_REGEX,\n UUID_REGEX,\n RELAXED_UUID_REGEX,\n ULID_REGEX,\n OBJECT_ID_REGEX,\n HEX_HASH_REGEX,\n PREFIXED_ID_REGEX,\n SLUG_REGEX,\n HASHID_REGEX,\n} from './patterns.js';\nimport { isReservedStaticSegment } from './static-words.js';\n\nexport type DynamicSegmentKind =\n | 'numeric'\n | 'uuid'\n | 'ulid'\n | 'objectid'\n | 'hex'\n | 'prefixed'\n | 'slug'\n | 'hashid';\n\nexport interface SegmentClassification {\n readonly isDynamic: boolean;\n readonly kind?: DynamicSegmentKind;\n readonly confidence: number; // 0.0 to 1.0\n}\n\n/**\n * Deterministically classifies an individual path segment as static or dynamic.\n * Follows conservative heuristics to prevent false-positive route merging.\n */\nexport class SegmentClassifier {\n public static classify(\n segment: string,\n previousSegment?: string\n ): SegmentClassification {\n const trimmed = segment.trim();\n\n // 1. Empty or whitespace-only is never dynamic\n if (trimmed.length === 0) {\n return { isDynamic: false, confidence: 1.0 };\n }\n\n // 2. Reserved static words and API version strings are strictly static\n if (isReservedStaticSegment(trimmed)) {\n return { isDynamic: false, confidence: 1.0 };\n }\n\n // 3. Numeric ID (e.g. \"123\", \"4567890\")\n if (NUMERIC_ID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'numeric', confidence: 1.0 };\n }\n\n // 4. Standard or Relaxed UUID\n if (UUID_REGEX.test(trimmed) || RELAXED_UUID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'uuid', confidence: 1.0 };\n }\n\n // 5. ULID (26-character Base32)\n if (ULID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'ulid', confidence: 0.95 };\n }\n\n // 6. MongoDB ObjectId (24 hex characters)\n if (OBJECT_ID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'objectid', confidence: 0.95 };\n }\n\n // 7. Generic Hex Hash (16-64 hex chars with digits)\n if (HEX_HASH_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'hex', confidence: 0.9 };\n }\n\n // 8. Prefixed ID (e.g. \"cus_12345\", \"ORD-2026-001\", \"INV-2023-99\", \"USR_8899\")\n // Explicitly targets:\n // a) Underscore-separated IDs (e.g. Stripe \"cus_12345\", \"ch_1A2b3C\")\n // b) Uppercase business prefixes with numeric suffixes (e.g. \"ORD-2026-001\", \"INV-2023-99\")\n if (\n /^[a-zA-Z]{2,6}_[a-zA-Z0-9]+$/.test(trimmed) ||\n /^[A-Z]{2,6}-\\d+(-\\d+)*$/.test(trimmed)\n ) {\n return { isDynamic: true, kind: 'prefixed', confidence: 0.95 };\n }\n\n // 9. Slug (e.g. \"how-to-build-apis\", \"my-first-post-2026\", \"tech-news\")\n // Hyphenated string with 3+ parts, OR 2+ parts when preceded by a resource collection\n if (SLUG_REGEX.test(trimmed)) {\n const parts = trimmed.split('-');\n if (parts.length >= 3) {\n return { isDynamic: true, kind: 'slug', confidence: 0.85 };\n }\n if (\n previousSegment &&\n /^(posts|articles|blogs|stories|topics|categories|items)$/i.test(previousSegment)\n ) {\n return { isDynamic: true, kind: 'slug', confidence: 0.85 };\n }\n }\n\n // Fallback prefixed ID for general kebab with digits (e.g. \"usr-12345\")\n if (PREFIXED_ID_REGEX.test(trimmed) && /\\d/.test(trimmed)) {\n return { isDynamic: true, kind: 'prefixed', confidence: 0.9 };\n }\n\n // 10. Alphanumeric mixed ID / Hashid (e.g. \"abc123\", \"usr88a99\")\n // Length between 6 and 20, must have both letters and numbers\n if (HASHID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'hashid', confidence: 0.8 };\n }\n\n // Default fallback: preserve segment as static\n return { isDynamic: false, confidence: 0.9 };\n }\n}\n","/**\n * Basic, robust English noun singularization for parameter naming.\n * Covers regular plurals, -ies, -es, and irregular common nouns.\n */\n\nconst IRREGULAR_PLURALS: Record<string, string> = {\n people: 'person',\n children: 'child',\n men: 'man',\n women: 'woman',\n data: 'data',\n media: 'medium',\n criteria: 'criterion',\n indices: 'index',\n};\n\nconst UNCOUNTABLE_OR_SINGULAR_S: Set<string> = new Set([\n 'status',\n 'news',\n 'series',\n 'species',\n 'analytics',\n 'metrics',\n 'address',\n 'process',\n 'access',\n 'business',\n 'class',\n 'pass',\n]);\n\n/**\n * Returns the singular form of an English noun.\n */\nexport function singularize(word: string): string {\n const lower = word.toLowerCase().trim();\n\n if (lower.length <= 2) {\n return word;\n }\n\n // Check irregulars\n const irregular = IRREGULAR_PLURALS[lower];\n if (irregular) {\n return irregular;\n }\n\n // Words that end in s but are already singular\n if (UNCOUNTABLE_OR_SINGULAR_S.has(lower)) {\n return word;\n }\n\n // -ies -> -y (e.g. categories -> category, companies -> company)\n if (lower.endsWith('ies') && lower.length > 4) {\n return word.slice(0, -3) + 'y';\n }\n\n // -ses, -shes, -ches, -xes, -zes -> strip -es (e.g. statuses -> status, boxes -> box, watches -> watch)\n if (/(sses|shes|ches|xes|zes|ses)$/i.test(lower)) {\n return word.slice(0, -2);\n }\n\n // standard -s plural (e.g. users -> user, products -> product)\n if (lower.endsWith('s') && !lower.endsWith('ss')) {\n return word.slice(0, -1);\n }\n\n return word;\n}\n","import { singularize } from './singularize.js';\nimport type { DynamicSegmentKind } from '../heuristics/segment-classifier.js';\n\nexport interface DynamicSegmentContext {\n readonly index: number;\n readonly value: string;\n readonly kind: DynamicSegmentKind;\n readonly previousSegment?: string;\n}\n\n/**\n * Deterministically infers parameter names from contextual path hierarchy.\n */\nexport class ParameterNamer {\n /**\n * Generates parameter names for all dynamic segments in a path.\n */\n public static nameParameters(\n segments: readonly string[],\n dynamicIndices: ReadonlyMap<number, DynamicSegmentKind>\n ): Map<number, string> {\n const result = new Map<number, string>();\n const totalDynamic = dynamicIndices.size;\n const usedNames = new Set<string>();\n\n for (const [index, kind] of dynamicIndices.entries()) {\n const prevSegment = index > 0 ? segments[index - 1] : undefined;\n let paramName: string;\n\n if (kind === 'slug') {\n paramName = totalDynamic === 1 ? 'slug' : prevSegment ? `${singularize(prevSegment)}Slug` : 'slug';\n } else if (totalDynamic === 1) {\n // Single dynamic parameter: use standard \":id\" fallback as in \"/api/users/:id\"\n paramName = 'id';\n } else {\n // Nested / multiple dynamic parameters: use context to disambiguate,\n // e.g. \"/products/:productId/reviews/:reviewId\"\n if (prevSegment && prevSegment.length > 1) {\n const singular = singularize(prevSegment);\n paramName = `${singular}Id`;\n } else {\n paramName = 'id';\n }\n }\n\n // Avoid collision if multiple parameters derive the same name\n let uniqueName = paramName;\n let counter = 2;\n while (usedNames.has(uniqueName)) {\n uniqueName = `${paramName}_${counter}`;\n counter++;\n }\n\n usedNames.add(uniqueName);\n result.set(index, `:${uniqueName}`);\n }\n\n return result;\n }\n}\n\n","import type { QueryParamInferredType, QueryParamMetadata } from '@luxray/shared';\n\n/**\n * Analyzes and classifies query parameters observed across HTTP requests.\n */\nexport class QueryAnalyzer {\n /**\n * Infers primitive scalar data type from a query parameter string value.\n */\n public static inferType(value: string): QueryParamInferredType {\n const trimmed = value.trim();\n\n if (trimmed === '' || trimmed.toLowerCase() === 'null') {\n return 'null';\n }\n\n if (trimmed === 'true' || trimmed === 'false') {\n return 'boolean';\n }\n\n // Number check: pure integer or float\n if (/^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n return 'number';\n }\n\n return 'string';\n }\n\n /**\n * Merges a newly observed parameter values array into an existing or new QueryParamMetadata record.\n */\n public static merge(\n paramName: string,\n existing: QueryParamMetadata | undefined,\n observedValues: readonly string[],\n totalEndpointObservations: number\n ): QueryParamMetadata {\n const isArrayObservation = observedValues.length > 1;\n const observedTypes = new Set<QueryParamInferredType>(existing?.types ?? []);\n\n for (const val of observedValues) {\n observedTypes.add(this.inferType(val));\n }\n\n if (isArrayObservation) {\n observedTypes.add('array');\n }\n\n const occurrences = (existing?.occurrences ?? 0) + 1;\n const required = occurrences === totalEndpointObservations;\n\n // Collect bounded set of unique sample values (max 5)\n const samples = new Set<string>(existing?.sampleValues ?? []);\n for (const val of observedValues) {\n if (samples.size < 5) {\n samples.add(val);\n }\n }\n\n return {\n name: paramName,\n types: Array.from(observedTypes),\n isArray: existing?.isArray || isArrayObservation,\n required,\n occurrences,\n sampleValues: Array.from(samples),\n };\n }\n}\n\n","import type { EndpointIdentity, NormalizedEndpoint } from '@luxray/shared';\nimport { UrlParser } from '../url/url-parser.js';\nimport { SegmentClassifier, type DynamicSegmentKind } from '../heuristics/segment-classifier.js';\nimport { ParameterNamer } from '../naming/parameter-namer.js';\n\nexport interface NormalizerOptions {\n /**\n * If true, always formats parameter names contextually (e.g. \":userId\")\n * instead of \":id\" when only one dynamic parameter is present.\n * Default: false\n */\n alwaysUseContextualNames?: boolean;\n}\n\n/**\n * Deterministic API Endpoint Normalizer.\n * Analyzes raw HTTP request URLs and converts them into standardized API endpoint identities.\n */\nexport class EndpointNormalizer {\n private readonly options: NormalizerOptions;\n\n constructor(options?: NormalizerOptions) {\n this.options = {\n alwaysUseContextualNames: options?.alwaysUseContextualNames ?? false,\n };\n }\n\n /**\n * Normalizes a raw URL and HTTP method into a NormalizedEndpoint entity.\n */\n public normalize(url: string, method = 'GET'): NormalizedEndpoint {\n const parsed = UrlParser.parse(url);\n const upperMethod = method.toUpperCase().trim();\n const segments = parsed.segments;\n\n const dynamicIndices = new Map<number, DynamicSegmentKind>();\n\n // Step 1: Classify each segment\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]!;\n const prevSegment = i > 0 ? segments[i - 1] : undefined;\n const classification = SegmentClassifier.classify(segment, prevSegment);\n\n if (classification.isDynamic && classification.kind) {\n dynamicIndices.set(i, classification.kind);\n }\n }\n\n // Step 2: Infer parameter names\n const parameterTokens = ParameterNamer.nameParameters(segments, dynamicIndices);\n\n // Step 3: Reconstruct normalized path and extract path parameters\n const pathParameters: Record<string, string> = {};\n const normalizedSegments: string[] = [];\n\n for (let i = 0; i < segments.length; i++) {\n const rawSegment = segments[i]!;\n const token = parameterTokens.get(i);\n\n if (token) {\n normalizedSegments.push(token);\n const paramKey = token.slice(1); // remove leading colon\n pathParameters[paramKey] = rawSegment;\n } else {\n normalizedSegments.push(rawSegment);\n }\n }\n\n const normalizedPath =\n normalizedSegments.length === 0 ? '/' : `/${normalizedSegments.join('/')}`;\n\n // Step 4: Construct canonical endpoint identity\n const originPart = parsed.origin ? parsed.origin : '';\n const identityId = `${upperMethod} ${originPart}${normalizedPath}`;\n\n const identity: EndpointIdentity = {\n id: identityId,\n method: upperMethod,\n origin: parsed.origin,\n pathname: normalizedPath,\n };\n\n // Step 5: Convert searchParams Map to plain object\n const queryParameters: Record<string, string[]> = {};\n for (const [key, values] of parsed.searchParams.entries()) {\n queryParameters[key] = [...values];\n }\n\n return {\n identity,\n rawUrl: parsed.rawUrl,\n rawPath: parsed.rawPath,\n normalizedPath,\n pathParameters,\n queryParameters,\n };\n }\n}\n\n","import type {\n CapturedTransaction,\n EndpointAggregate,\n QueryParamMetadata,\n} from '@luxray/shared';\nimport { EndpointNormalizer } from './endpoint-normalizer.js';\nimport { QueryAnalyzer } from '../query/query-analyzer.js';\n\ninterface MutableAggregate {\n aggregate: EndpointAggregate;\n transactions: CapturedTransaction[];\n latencies: number[];\n}\n\n/**\n * Aggregates raw CapturedTransactions into structured API endpoint intelligence.\n * Tracks observation counts, latency profiles, status distributions, and query schemas.\n */\nexport class EndpointAggregator {\n private readonly normalizer: EndpointNormalizer;\n private readonly aggregates = new Map<string, MutableAggregate>();\n\n constructor(normalizer?: EndpointNormalizer) {\n this.normalizer = normalizer ?? new EndpointNormalizer();\n }\n\n /**\n * Ingests a single captured transaction, updating or creating an EndpointAggregate.\n */\n public ingest(transaction: CapturedTransaction): EndpointAggregate {\n const method = String(transaction.request.method);\n const normalized = this.normalizer.normalize(transaction.request.url, method);\n const endpointId = normalized.identity.id;\n const timestamp = transaction.request.timestamp || Date.now();\n\n const existing = this.aggregates.get(endpointId);\n\n if (!existing) {\n // First observation\n const isSuccess =\n transaction.status === 'completed' &&\n (!transaction.response ||\n (transaction.response.status >= 200 && transaction.response.status < 400));\n\n const statusCodes: Record<number, number> = {};\n if (transaction.response?.status) {\n statusCodes[transaction.response.status] = 1;\n }\n\n // Initialize query params\n const queryParams: Record<string, QueryParamMetadata> = {};\n for (const [key, values] of Object.entries(normalized.queryParameters)) {\n queryParams[key] = QueryAnalyzer.merge(key, undefined, values, 1);\n }\n\n const durationMs = transaction.timing.durationMs;\n const latencies = durationMs !== undefined ? [durationMs] : [];\n\n const newAggregate: EndpointAggregate = {\n identity: normalized.identity,\n observationCount: 1,\n firstObservedAt: timestamp,\n lastObservedAt: timestamp,\n statusCodes,\n successCount: isSuccess ? 1 : 0,\n failureCount: isSuccess ? 0 : 1,\n latency:\n durationMs !== undefined\n ? { minMs: durationMs, maxMs: durationMs, avgMs: durationMs }\n : undefined,\n queryParams,\n sampleUrls: [transaction.request.url],\n transactionIds: [transaction.id],\n };\n\n this.aggregates.set(endpointId, {\n aggregate: newAggregate,\n transactions: [transaction],\n latencies,\n });\n\n return newAggregate;\n }\n\n // Subsequent observations: mutate state\n const current = existing.aggregate;\n const observationCount = current.observationCount + 1;\n const firstObservedAt = Math.min(current.firstObservedAt, timestamp);\n const lastObservedAt = Math.max(current.lastObservedAt, timestamp);\n\n // Update status code counts\n const statusCodes = { ...current.statusCodes };\n if (transaction.response?.status) {\n const code = transaction.response.status;\n statusCodes[code] = (statusCodes[code] ?? 0) + 1;\n }\n\n const isSuccess =\n transaction.status === 'completed' &&\n (!transaction.response ||\n (transaction.response.status >= 200 && transaction.response.status < 400));\n\n const successCount = current.successCount + (isSuccess ? 1 : 0);\n const failureCount = current.failureCount + (isSuccess ? 0 : 1);\n\n // Update latency metrics\n if (transaction.timing.durationMs !== undefined) {\n existing.latencies.push(transaction.timing.durationMs);\n }\n\n let latency = current.latency;\n if (existing.latencies.length > 0) {\n const sorted = [...existing.latencies].sort((a, b) => a - b);\n const minMs = sorted[0]!;\n const maxMs = sorted[sorted.length - 1]!;\n const sum = sorted.reduce((acc, val) => acc + val, 0);\n const avgMs = Math.round((sum / sorted.length) * 10) / 10;\n latency = { minMs, maxMs, avgMs };\n }\n\n // Update query parameters\n const updatedQueryParams: Record<string, QueryParamMetadata> = { ...current.queryParams };\n for (const [key, values] of Object.entries(normalized.queryParameters)) {\n updatedQueryParams[key] = QueryAnalyzer.merge(\n key,\n updatedQueryParams[key],\n values,\n observationCount\n );\n }\n\n // Recalculate required flag for all query params against total observations\n for (const [key, meta] of Object.entries(updatedQueryParams)) {\n if (meta.occurrences !== observationCount) {\n updatedQueryParams[key] = { ...meta, required: false };\n }\n }\n\n // Retain bounded sample URLs (max 5)\n const sampleUrls = current.sampleUrls.includes(transaction.request.url)\n ? current.sampleUrls\n : current.sampleUrls.length < 5\n ? [...current.sampleUrls, transaction.request.url]\n : current.sampleUrls;\n\n // Retain transaction IDs\n const transactionIds = [...current.transactionIds, transaction.id];\n existing.transactions.push(transaction);\n\n const updatedAggregate: EndpointAggregate = {\n identity: current.identity,\n observationCount,\n firstObservedAt,\n lastObservedAt,\n statusCodes,\n successCount,\n failureCount,\n latency,\n queryParams: updatedQueryParams,\n sampleUrls,\n transactionIds,\n };\n\n existing.aggregate = updatedAggregate;\n return updatedAggregate;\n }\n\n /**\n * Ingests an array of transactions in sequential order.\n */\n public ingestBatch(transactions: readonly CapturedTransaction[]): readonly EndpointAggregate[] {\n for (const tx of transactions) {\n this.ingest(tx);\n }\n return this.getAll();\n }\n\n /**\n * Retrieves an aggregate by its unique endpoint identity string.\n */\n public get(endpointId: string): EndpointAggregate | undefined {\n return this.aggregates.get(endpointId)?.aggregate;\n }\n\n /**\n * Returns all aggregated endpoints.\n */\n public getAll(): readonly EndpointAggregate[] {\n return Array.from(this.aggregates.values()).map((m) => m.aggregate);\n }\n\n /**\n * Returns all original captured transactions associated with an endpoint.\n */\n public getTransactions(endpointId: string): readonly CapturedTransaction[] {\n return this.aggregates.get(endpointId)?.transactions ?? [];\n }\n\n /**\n * Filters aggregated endpoints by predicate.\n */\n public filter(predicate: (agg: EndpointAggregate) => boolean): EndpointAggregate[] {\n return this.getAll().filter(predicate);\n }\n\n /**\n * Finds endpoints whose normalized path contains the specified substring.\n */\n public findByPath(pathnameSubstring: string): EndpointAggregate[] {\n return this.filter((agg) => agg.identity.pathname.includes(pathnameSubstring));\n }\n\n public size(): number {\n return this.aggregates.size;\n }\n\n public clear(): void {\n this.aggregates.clear();\n }\n}\n\n","import { singularize } from '@luxray/normalization';\nimport type { ResourceCandidate } from '../domain/types.js';\n\nexport { singularize };\n\nexport const DEFAULT_STRIP_PREFIXES: readonly string[] = [\n '/api',\n '/v1',\n '/v2',\n '/v3',\n '/v4',\n '/v5',\n '/rest',\n '/public',\n '/internal',\n];\n\nexport const DEFAULT_ACTION_VERBS: ReadonlySet<string> = new Set([\n 'activate',\n 'deactivate',\n 'enable',\n 'disable',\n 'verify',\n 'checkout',\n 'search',\n 'export',\n 'import',\n 'login',\n 'logout',\n 'sync',\n 'reset',\n 'cancel',\n 'archive',\n 'unarchive',\n 'publish',\n 'unpublish',\n 'clone',\n 'fork',\n 'submit',\n 'validate',\n 'confirm',\n 'reorder',\n 'download',\n 'upload',\n 'lock',\n 'unlock',\n 'process',\n 'approve',\n 'reject',\n 'history',\n 'stats',\n 'summary',\n 'overview',\n 'preview',\n 'details',\n 'feed',\n 'recent',\n]);\n\n/**\n * Common REST pseudo-parameters representing the caller's identity (e.g. /users/me).\n */\nexport const IDENTITY_ALIAS_SEGMENTS: ReadonlySet<string> = new Set([\n 'me',\n 'self',\n 'current',\n 'mine',\n]);\n\n/**\n * Result of decomposing a path into its resource hierarchy and optional terminal action.\n */\nexport interface PathResourceHierarchy {\n /** The clean path with prefixes stripped */\n readonly normalizedPath: string;\n /** Primary resource candidate (e.g. 'user' for /users/:userId) */\n readonly primaryResource?: ResourceCandidate;\n /** Secondary/nested resource candidate (e.g. 'order' for /users/:userId/orders) */\n readonly nestedResource?: ResourceCandidate;\n /** All resource candidates found along the path in hierarchical order */\n readonly resources: readonly ResourceCandidate[];\n /** Action verb if terminal segment is an operational action rather than a resource */\n readonly action?: string;\n /** Parameter segments mapped to their preceding resource, e.g. { user: 'userId', order: 'orderId' } */\n readonly resourceParams: ReadonlyMap<string, string>;\n}\n\n/**\n * Strips configured API prefixes from the beginning of a URL path.\n */\nexport function stripApiPrefixes(\n pathname: string,\n prefixes: readonly string[] = DEFAULT_STRIP_PREFIXES,\n): string {\n let cleaned = pathname.trim();\n if (!cleaned.startsWith('/')) {\n cleaned = `/${cleaned}`;\n }\n\n let matched = true;\n while (matched) {\n matched = false;\n for (const prefix of prefixes) {\n const normalizedPrefix = prefix.startsWith('/') ? prefix : `/${prefix}`;\n if (cleaned.toLowerCase().startsWith(normalizedPrefix.toLowerCase())) {\n const nextChar = cleaned[normalizedPrefix.length];\n if (nextChar === '/' || nextChar === undefined) {\n cleaned = cleaned.slice(normalizedPrefix.length);\n if (!cleaned.startsWith('/')) {\n cleaned = `/${cleaned}`;\n }\n matched = true;\n break;\n }\n }\n }\n }\n\n return cleaned === '' ? '/' : cleaned;\n}\n\n/**\n * Checks whether a path segment represents a parameter (e.g. `:userId`, `{id}`).\n */\nexport function isParameterSegment(segment: string): boolean {\n if (!segment) return false;\n return (\n segment.startsWith(':') ||\n (segment.startsWith('{') && segment.endsWith('}')) ||\n (segment.startsWith('[') && segment.endsWith(']'))\n );\n}\n\n/**\n * Extracts the clean parameter name without parameter syntax delimiters.\n */\nexport function extractParamName(segment: string): string {\n if (segment.startsWith(':')) {\n return segment.slice(1);\n }\n if (\n (segment.startsWith('{') && segment.endsWith('}')) ||\n (segment.startsWith('[') && segment.endsWith(']'))\n ) {\n return segment.slice(1, -1);\n }\n return segment;\n}\n\n/**\n * Checks whether a segment represents an action verb.\n */\nexport function isActionVerb(\n segment: string,\n customVerbs?: ReadonlySet<string>,\n): boolean {\n const lower = segment.toLowerCase().trim();\n const verbs = customVerbs ?? DEFAULT_ACTION_VERBS;\n return verbs.has(lower);\n}\n\n/**\n * Decomposes an endpoint path template into resource candidates, nesting hierarchy, and actions.\n */\nexport function extractPathHierarchy(\n pathTemplate: string,\n options?: {\n stripPrefixes?: readonly string[];\n actionVerbs?: ReadonlySet<string>;\n },\n): PathResourceHierarchy {\n const strippedPath = stripApiPrefixes(pathTemplate, options?.stripPrefixes);\n const segments = strippedPath\n .split('/')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n const resources: ResourceCandidate[] = [];\n const resourceParams = new Map<string, string>();\n let action: string | undefined;\n\n let currentSubpath = '';\n let parentResourceName: string | undefined;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]!;\n currentSubpath += `/${segment}`;\n\n if (isParameterSegment(segment)) {\n const paramName = extractParamName(segment);\n if (resources.length > 0) {\n const lastResource = resources[resources.length - 1]!;\n resourceParams.set(lastResource.name, paramName);\n }\n continue;\n }\n\n // Check if segment is an identity alias following a resource (e.g. /users/me, /accounts/current)\n if (resources.length > 0 && IDENTITY_ALIAS_SEGMENTS.has(segment.toLowerCase())) {\n const lastResource = resources[resources.length - 1]!;\n resourceParams.set(lastResource.name, segment.toLowerCase());\n continue;\n }\n\n const isTerminal = i === segments.length - 1;\n // Check if terminal segment is an action verb or preceded by a param and not plural\n if (isTerminal && isActionVerb(segment, options?.actionVerbs)) {\n action = segment;\n break;\n }\n\n // Singularize segment to derive canonical resource name\n const singular = singularize(segment).toLowerCase();\n const isPlural = singular !== segment.toLowerCase();\n const isNested = resources.length > 0;\n\n // If terminal segment is not plural, but follows a parameter, check if it's an action\n if (isTerminal && !isPlural && i > 0 && isParameterSegment(segments[i - 1]!)) {\n // If it looks like a verb or known action\n if (isActionVerb(segment, options?.actionVerbs) || segment.endsWith('e') || segment.endsWith('ing')) {\n action = segment;\n break;\n }\n }\n\n const candidate: ResourceCandidate = {\n name: singular,\n pluralName: isPlural ? segment.toLowerCase() : `${singular}s`,\n rawSegment: segment,\n path: currentSubpath,\n isNested,\n parentResource: parentResourceName,\n };\n\n resources.push(candidate);\n parentResourceName = singular;\n }\n\n const primaryResource = resources[0];\n const nestedResource = resources.length > 1 ? resources[1] : undefined;\n\n return {\n normalizedPath: strippedPath,\n primaryResource,\n nestedResource,\n resources,\n action,\n resourceParams,\n };\n}\n","import type {\n EndpointClassification,\n EndpointClassificationType,\n HttpMethod,\n} from '../domain/types.js';\nimport {\n extractPathHierarchy,\n isParameterSegment,\n IDENTITY_ALIAS_SEGMENTS,\n type PathResourceHierarchy,\n} from './resource-identifier.js';\n\nexport interface EndpointClassificationInput {\n readonly id: string;\n readonly method: HttpMethod | string;\n readonly pathTemplate: string;\n}\n\nexport const SYSTEM_UTILITY_SEGMENTS: ReadonlySet<string> = new Set([\n 'health',\n 'healthz',\n 'ping',\n 'live',\n 'livez',\n 'ready',\n 'readyz',\n 'metrics',\n 'version',\n 'info',\n 'docs',\n 'openapi',\n 'swagger',\n]);\n\n/**\n * Classifies an endpoint based on its HTTP method and path hierarchy.\n */\nexport function classifyEndpoint(\n endpoint: EndpointClassificationInput,\n options?: {\n stripPrefixes?: readonly string[];\n actionVerbs?: ReadonlySet<string>;\n },\n): EndpointClassification {\n const method = (endpoint.method?.toUpperCase() ?? 'GET') as HttpMethod;\n\n const hierarchy: PathResourceHierarchy = extractPathHierarchy(\n endpoint.pathTemplate,\n options,\n );\n\n const rawSegments = hierarchy.normalizedPath\n .split('/')\n .filter((s) => s.length > 0);\n\n // If path is a recognized non-resource system check (e.g. /health, /ping)\n if (\n rawSegments.length === 1 &&\n SYSTEM_UTILITY_SEGMENTS.has(rawSegments[0]!.toLowerCase())\n ) {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'UNKNOWN',\n confidence: 0.9,\n };\n }\n\n const lastSegment = rawSegments.length > 0 ? rawSegments[rawSegments.length - 1]! : '';\n const isTerminalParam =\n isParameterSegment(lastSegment) ||\n IDENTITY_ALIAS_SEGMENTS.has(lastSegment.toLowerCase());\n\n // If hierarchy identified an explicit action\n if (hierarchy.action) {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'ACTION',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n actionName: hierarchy.action,\n confidence: 0.95,\n };\n }\n\n // Nested resource patterns (hierarchy has >= 2 resources)\n if (hierarchy.resources.length >= 2) {\n if (isTerminalParam) {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'NESTED_RESOURCE_READ',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.9,\n };\n }\n if (method === 'PUT' || method === 'PATCH') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_UPDATE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n if (method === 'DELETE') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_DELETE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n } else {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'NESTED_COLLECTION_READ',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.9,\n };\n }\n if (method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_CREATE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n }\n }\n\n // Single resource patterns\n if (hierarchy.primaryResource) {\n if (isTerminalParam) {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_READ',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'PUT' || method === 'PATCH') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_UPDATE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'DELETE') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_DELETE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n } else {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'COLLECTION_READ',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_CREATE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n }\n }\n\n // Fallbacks: non-GET terminal or root actions\n if (rawSegments.length > 0 && !isTerminalParam && method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'ACTION',\n actionName: lastSegment,\n confidence: 0.7,\n };\n }\n\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'UNKNOWN',\n confidence: 0.5,\n };\n}\n","import { createHmac } from 'node:crypto';\nimport type {\n EndpointAggregate,\n EndpointSchemaAggregate,\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n} from '@luxray/shared';\nimport type {\n DiscoveryEngineOptions,\n IdentifierCandidate,\n IdentifierLocation,\n} from '../domain/types.js';\nimport {\n extractParamName,\n extractPathHierarchy,\n isParameterSegment,\n} from '../resources/resource-identifier.js';\n\nexport const SENSITIVE_IDENTIFIER_SUBSTRINGS: readonly string[] = [\n 'password',\n 'passwd',\n 'secret',\n 'token',\n 'apikey',\n 'api_key',\n 'privatekey',\n 'private_key',\n 'authkey',\n 'auth_key',\n 'authcode',\n 'auth_code',\n 'authtoken',\n 'auth_token',\n 'sessionkey',\n 'bearer',\n 'authorization',\n 'cookie',\n 'cvv',\n 'cvc',\n 'ssn',\n 'pin',\n 'otp',\n 'passcode',\n 'signature',\n];\n\n/**\n * Computes an HMAC-SHA-256 cryptographic fingerprint for an identifier sample value.\n * Requires an explicit secret key (e.g. per-workspace or per-tenant).\n * Never uses a hardcoded fallback.\n */\nexport function computeHmacFingerprint(\n val: string | number,\n secretKey: string,\n): string {\n if (!secretKey || secretKey.trim().length === 0) {\n throw new Error(\n 'computeHmacFingerprint requires an explicit, non-empty secretKey.',\n );\n }\n return createHmac('sha256', secretKey.trim())\n .update(String(val))\n .digest('hex')\n .slice(0, 32);\n}\n\n/**\n * Backward-compatible wrapper for keyed fingerprinting.\n */\nexport function computeSaltedFingerprint(\n val: string | number,\n secretKey?: string,\n): string {\n if (!secretKey) {\n throw new Error(\n 'Fingerprinting requires an explicit secret key. No hardcoded default fallback is permitted.',\n );\n }\n return computeHmacFingerprint(val, secretKey);\n}\n\nexport interface EndpointInput {\n readonly id: string;\n readonly method: string;\n readonly pathTemplate: string;\n readonly queryParams?: EndpointAggregate['queryParams'];\n readonly sampleUrls?: readonly string[];\n}\n\n/**\n * Normalizes property name to a lowercase alphanumeric string for fuzzy comparison.\n * e.g. \"userId\", \"user_id\", \"user-id\", \"UserID\" -> \"userid\"\n */\nexport function canonicalizeIdentifierName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n\n/**\n * Checks whether a property or parameter name looks like an entity identifier.\n * Automatically rejects sensitive credentials and secret keywords.\n */\nexport function isIdentifierName(name: string): boolean {\n const lower = name.toLowerCase().replace(/[-_]/g, '');\n\n // Reject credentials, passwords, tokens, API keys, and OTPs\n for (const sensitive of SENSITIVE_IDENTIFIER_SUBSTRINGS) {\n if (lower.includes(sensitive.replace(/[-_]/g, ''))) {\n return false;\n }\n }\n\n if (lower === 'id' || lower === 'uuid' || lower === 'pk' || lower === 'slug') {\n return true;\n }\n return (\n lower.endsWith('id') ||\n lower.endsWith('uuid') ||\n lower.endsWith('slug') ||\n (lower.endsWith('key') && !lower.includes('secret') && !lower.includes('auth')) ||\n (lower.endsWith('code') && !lower.includes('pin') && !lower.includes('otp'))\n );\n}\n\n/**\n * Attempts to parse sample parameter values from sample URLs given a path template.\n */\nexport function extractPathSamplesFromUrls(\n pathTemplate: string,\n sampleUrls?: readonly string[],\n): Map<string, string[]> {\n const paramSamples = new Map<string, string[]>();\n if (!sampleUrls || sampleUrls.length === 0) {\n return paramSamples;\n }\n\n const templateSegments = pathTemplate\n .split('/')\n .filter((s) => s.length > 0);\n\n for (const urlStr of sampleUrls) {\n try {\n const parsed = new URL(urlStr, 'https://example.local');\n const actualSegments = parsed.pathname\n .split('/')\n .filter((s) => s.length > 0);\n\n // Find offset if path template has prefixes or vice versa\n if (actualSegments.length >= templateSegments.length) {\n const offset = actualSegments.length - templateSegments.length;\n for (let i = 0; i < templateSegments.length; i++) {\n const tSeg = templateSegments[i]!;\n if (isParameterSegment(tSeg)) {\n const paramName = extractParamName(tSeg);\n const actualVal = actualSegments[offset + i];\n if (actualVal) {\n const existing = paramSamples.get(paramName) ?? [];\n if (!existing.includes(actualVal)) {\n existing.push(actualVal);\n paramSamples.set(paramName, existing);\n }\n }\n }\n }\n }\n } catch {\n // Ignore URL parsing errors\n }\n }\n\n return paramSamples;\n}\n\n/**\n * Normalizes endpoint input from either an EndpointAggregate or custom EndpointInput.\n */\nexport function normalizeEndpointInput(\n endpoint: EndpointAggregate | EndpointInput,\n): EndpointInput {\n if ('identity' in endpoint) {\n return {\n id: endpoint.identity.id,\n method: endpoint.identity.method,\n pathTemplate: endpoint.identity.pathname,\n queryParams: endpoint.queryParams,\n sampleUrls: endpoint.sampleUrls,\n };\n }\n return endpoint;\n}\n\n/**\n * Safely extracts primitive scalar sample values from schema or field metadata.\n */\nexport function sanitizeSampleValues(\n rawSamples?: readonly unknown[],\n maxCount = 50,\n): readonly (string | number)[] {\n if (!rawSamples || !Array.isArray(rawSamples)) {\n return [];\n }\n const clean: (string | number)[] = [];\n const seen = new Set<string>();\n\n for (const val of rawSamples) {\n if (val === null || val === undefined) continue;\n if (typeof val === 'string' || typeof val === 'number') {\n const key = `${typeof val}:${val}`;\n if (!seen.has(key)) {\n seen.add(key);\n clean.push(val);\n if (clean.length >= maxCount) break;\n }\n }\n }\n\n return clean;\n}\n\n/**\n * Extracts candidate identifiers from an endpoint's path and query parameters.\n */\nexport function extractEndpointParamIdentifiers(\n endpoint: EndpointInput,\n options?: DiscoveryEngineOptions,\n): IdentifierCandidate[] {\n const candidates: IdentifierCandidate[] = [];\n const hierarchy = extractPathHierarchy(endpoint.pathTemplate, {\n stripPrefixes: options?.stripPrefixes,\n });\n\n const pathSamples = extractPathSamplesFromUrls(\n endpoint.pathTemplate,\n endpoint.sampleUrls,\n );\n\n const secretKey = options?.fingerprintSecret?.trim();\n\n // Extract from path parameters\n for (const [resource, paramName] of hierarchy.resourceParams.entries()) {\n const canonical = canonicalizeIdentifierName(paramName);\n const samples = (pathSamples.get(paramName) ?? []).slice(\n 0,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? samples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `path.${paramName}`,\n location: 'path_param',\n type: 'string', // Path segments default to string unless known\n sampleFingerprints: fingerprints,\n sampleValues: samples,\n endpointId: endpoint.id,\n isPrimaryKeyCandidate: true,\n });\n }\n\n // Also check raw segments for any other path params not tied to a recognized resource\n const rawSegments = endpoint.pathTemplate.split('/').filter((s) => s.length > 0);\n for (const seg of rawSegments) {\n if (isParameterSegment(seg)) {\n const paramName = extractParamName(seg);\n if (!candidates.some((c) => c.name === paramName)) {\n const canonical = canonicalizeIdentifierName(paramName);\n const samples = (pathSamples.get(paramName) ?? []).slice(\n 0,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? samples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `path.${paramName}`,\n location: 'path_param',\n type: 'string',\n sampleFingerprints: fingerprints,\n sampleValues: samples,\n endpointId: endpoint.id,\n isPrimaryKeyCandidate: true,\n });\n }\n }\n }\n\n // Extract from query parameters\n if (endpoint.queryParams) {\n for (const [paramName, meta] of Object.entries(endpoint.queryParams)) {\n if (isIdentifierName(paramName)) {\n const canonical = canonicalizeIdentifierName(paramName);\n const inferredType = meta.types.includes('number')\n ? 'number'\n : meta.types.includes('string')\n ? 'string'\n : 'unknown';\n const cleanSamples = sanitizeSampleValues(\n meta.sampleValues,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? cleanSamples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `query.${paramName}`,\n location: 'query_param',\n type: inferredType,\n sampleFingerprints: fingerprints,\n sampleValues: cleanSamples,\n endpointId: endpoint.id,\n isForeignKeyCandidate: true,\n });\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Recursively traverses an inferred schema to find identifier properties.\n */\nfunction traverseSchemaForIdentifiers(\n schema: InferredSchema,\n currentPath: string,\n location: IdentifierLocation,\n endpointId: string,\n results: IdentifierCandidate[],\n currentDepth: number,\n maxDepth: number,\n maxSampleValues: number,\n secretKey?: string,\n): void {\n if (!schema || !schema.type || currentDepth > maxDepth) return;\n\n if (schema.type === 'object') {\n const obj = schema as InferredObjectSchema;\n if (!obj.fields) return;\n for (const [fieldName, fieldMeta] of Object.entries(obj.fields)) {\n if (!fieldMeta) continue;\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n const childSchema = fieldMeta.schema;\n\n if (isIdentifierName(fieldName)) {\n let type:\n | 'string'\n | 'number'\n | 'integer'\n | 'boolean'\n | 'object'\n | 'array'\n | 'unknown' = 'unknown';\n let format: string | undefined;\n\n if (childSchema) {\n if (childSchema.type === 'string') {\n type = 'string';\n } else if (childSchema.type === 'integer') {\n type = 'integer';\n } else if (childSchema.type === 'number') {\n type = 'number';\n } else if (childSchema.type === 'boolean') {\n type = 'boolean';\n } else if (childSchema.type === 'object') {\n type = 'object';\n } else if (childSchema.type === 'array') {\n type = 'array';\n }\n }\n\n const isPk =\n fieldName.toLowerCase() === 'id' ||\n fieldName.toLowerCase() === '_id' ||\n fieldName.toLowerCase() === 'uuid';\n const isFk = !isPk && isIdentifierName(fieldName);\n\n const cleanSamples = sanitizeSampleValues(\n fieldMeta.sampleValues,\n maxSampleValues,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? cleanSamples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n results.push({\n name: fieldName,\n canonicalName: canonicalizeIdentifierName(fieldName),\n propertyPath: `${location}.${fieldPath}`,\n location,\n type,\n format,\n sampleFingerprints: fingerprints,\n sampleValues: cleanSamples,\n endpointId,\n isPrimaryKeyCandidate: isPk,\n isForeignKeyCandidate: isFk,\n });\n }\n\n // Recurse into nested object or array\n if (childSchema && (childSchema.type === 'object' || childSchema.type === 'array')) {\n traverseSchemaForIdentifiers(\n childSchema,\n fieldPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n }\n } else if (schema.type === 'array') {\n const arr = schema as InferredArraySchema & { items?: InferredSchema };\n const child = arr.itemSchema ?? arr.items;\n if (child) {\n const itemPath = `${currentPath}[]`;\n traverseSchemaForIdentifiers(\n child,\n itemPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n } else if (schema.type === 'union') {\n for (const variant of schema.variants) {\n if (variant.type === 'object' || variant.type === 'array') {\n traverseSchemaForIdentifiers(\n variant,\n currentPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n }\n }\n}\n\n/**\n * Extracts candidate identifiers from an endpoint schema aggregate.\n */\nexport function extractSchemaIdentifiers(\n endpointId: string,\n schemaAggregate: EndpointSchemaAggregate,\n options?: DiscoveryEngineOptions,\n): IdentifierCandidate[] {\n const candidates: IdentifierCandidate[] = [];\n const maxDepth = options?.maxSchemaDepth ?? 5;\n const maxSamples = options?.maxSampleValues ?? 50;\n const secretKey = options?.fingerprintSecret?.trim();\n\n // Inspect request schema\n if (schemaAggregate.request?.schema) {\n traverseSchemaForIdentifiers(\n schemaAggregate.request.schema,\n 'body',\n 'request_body',\n endpointId,\n candidates,\n 1,\n maxDepth,\n maxSamples,\n secretKey,\n );\n }\n\n // Inspect 2xx responses (prioritizing 200 and 201)\n const statusCodes = schemaAggregate.responses\n ? Object.keys(schemaAggregate.responses)\n .map(Number)\n .filter((code) => code >= 200 && code < 300)\n .sort((a, b) => a - b)\n : [];\n\n for (const status of statusCodes) {\n const mediaMap = schemaAggregate.responses[status];\n if (!mediaMap) continue;\n\n for (const resDef of Object.values(mediaMap)) {\n if (resDef.schema) {\n traverseSchemaForIdentifiers(\n resDef.schema,\n 'body',\n 'response_body',\n endpointId,\n candidates,\n 1,\n maxDepth,\n maxSamples,\n secretKey,\n );\n }\n }\n }\n\n return candidates;\n}\n","import type { EvidenceRecord } from '../domain/types.js';\nimport type { IdentifierCandidate } from '../domain/types.js';\n\nexport interface IdentifierMatchResult {\n readonly isMatch: boolean;\n readonly score: number;\n readonly evidence: readonly EvidenceRecord[];\n readonly sourceCandidate: IdentifierCandidate;\n readonly targetCandidate: IdentifierCandidate;\n readonly contradictionDetected: boolean;\n}\n\n/**\n * Checks whether two identifier names match by exact, canonical, or resource-prefixed heuristics.\n */\nexport function matchIdentifierNames(\n nameA: string,\n nameB: string,\n resourceA?: string,\n resourceB?: string,\n): { isMatch: boolean; kind: 'exact' | 'canonical' | 'resource_prefixed' | 'none' } {\n const canonA = nameA.toLowerCase().replace(/[^a-z0-9]/g, '');\n const canonB = nameB.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n // If both are simply generic \"id\", \"uuid\", or \"pk\", but belong to two different resources,\n // they are independent primary keys of different entities, not a reference relationship.\n if (\n (canonA === 'id' || canonA === 'uuid' || canonA === 'pk') &&\n (canonB === 'id' || canonB === 'uuid' || canonB === 'pk')\n ) {\n if (resourceA && resourceB && resourceA.toLowerCase() !== resourceB.toLowerCase()) {\n return { isMatch: false, kind: 'none' };\n }\n return { isMatch: true, kind: 'exact' };\n }\n\n if (nameA === nameB) {\n return { isMatch: true, kind: 'exact' };\n }\n\n if (canonA === canonB) {\n return { isMatch: true, kind: 'canonical' };\n }\n\n // Check resource prefix:\n // Case 1: Source A is resourceA, with id='id', matching foreign key 'resourceAId' on Target B\n if (resourceA) {\n const resA = resourceA.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (canonA === 'id' && (canonB === `${resA}id` || canonB === `${resA}uuid`)) {\n return { isMatch: true, kind: 'resource_prefixed' };\n }\n }\n\n // Case 2: Target B is resourceB, with id='id', matching foreign key 'resourceBId' on Source A\n if (resourceB) {\n const resB = resourceB.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (canonB === 'id' && (canonA === `${resB}id` || canonA === `${resB}uuid`)) {\n return { isMatch: true, kind: 'resource_prefixed' };\n }\n }\n\n return { isMatch: false, kind: 'none' };\n}\n\n/**\n * Evaluates type compatibility between two identifier candidates.\n */\nexport function evaluateTypeCompatibility(\n typeA: string,\n typeB: string,\n): { compatible: boolean; contradiction: boolean } {\n if (typeA === 'unknown' || typeB === 'unknown') {\n return { compatible: true, contradiction: false };\n }\n\n if (typeA === typeB) {\n return { compatible: true, contradiction: false };\n }\n\n if (\n (typeA === 'number' && typeB === 'integer') ||\n (typeA === 'integer' && typeB === 'number')\n ) {\n return { compatible: true, contradiction: false };\n }\n\n // If one is string and the other is integer/number, check if string could be numeric id\n // In HTTP REST APIs, path params are often strings while JSON payloads use numbers.\n // This is weakly compatible rather than a strict contradiction, unless sample values clash.\n if (\n (typeA === 'string' && (typeB === 'number' || typeB === 'integer')) ||\n (typeB === 'string' && (typeA === 'number' || typeA === 'integer'))\n ) {\n return { compatible: true, contradiction: false };\n }\n\n // Contradiction: incompatible scalar types\n return { compatible: false, contradiction: true };\n}\n\nfunction extractComparisonItems(\n input:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n): readonly string[] {\n // If raw array is passed directly (e.g. testing the mathematical set logic), compare those\n if (Array.isArray(input)) {\n return (input as readonly (string | number)[]).map(String);\n }\n\n const obj = input as {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n };\n\n // For identifier candidates, strictly require keyed HMAC fingerprints.\n // Never silently fall back to plaintext comparisons when unconfigured.\n if (obj.sampleFingerprints && obj.sampleFingerprints.length > 0) {\n return obj.sampleFingerprints;\n }\n\n return [];\n}\n\n/**\n * Calculates sample value overlap between two candidate identifiers using privacy-preserving fingerprints.\n * Accepts either identifier candidate objects or raw sample arrays.\n */\nexport function calculateSampleOverlap(\n candidateA:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n candidateB:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n): {\n overlapRatio: number;\n intersectionCount: number;\n sampleAStats: number;\n sampleBStats: number;\n sharedFingerprints: readonly string[];\n sharedSamples?: readonly string[];\n} {\n const itemsA = extractComparisonItems(candidateA);\n const itemsB = extractComparisonItems(candidateB);\n\n if (itemsA.length === 0 || itemsB.length === 0) {\n return {\n overlapRatio: 0,\n intersectionCount: 0,\n sampleAStats: itemsA.length,\n sampleBStats: itemsB.length,\n sharedFingerprints: [],\n };\n }\n\n const setA = new Set(itemsA);\n const setB = new Set(itemsB);\n\n const intersection: string[] = [];\n for (const item of setA) {\n if (setB.has(item)) {\n intersection.push(item);\n }\n }\n\n const minSetSize = Math.min(setA.size, setB.size);\n const overlapRatio = minSetSize > 0 ? intersection.length / minSetSize : 0;\n\n return {\n overlapRatio,\n intersectionCount: intersection.length,\n sampleAStats: setA.size,\n sampleBStats: setB.size,\n sharedFingerprints: intersection.slice(0, 10),\n sharedSamples: intersection.slice(0, 10),\n };\n}\n\n/**\n * Compares two identifier candidates and produces match evidence and score.\n */\nexport function matchIdentifierCandidates(\n source: IdentifierCandidate,\n target: IdentifierCandidate,\n sourceResource?: string,\n targetResource?: string,\n): IdentifierMatchResult {\n const evidence: EvidenceRecord[] = [];\n let score = 0;\n let contradictionDetected = false;\n\n // If both candidates are generic \"id\" or \"uuid\" on different resources,\n // they are independent primary keys (e.g. user.id vs order.id).\n // They must not match, even if numerical sample values happen to overlap.\n const isBothGenericIdOnDifferentResources =\n Boolean(sourceResource) &&\n Boolean(targetResource) &&\n sourceResource?.toLowerCase() !== targetResource?.toLowerCase() &&\n (source.name.toLowerCase() === 'id' || source.name.toLowerCase() === 'uuid') &&\n (target.name.toLowerCase() === 'id' || target.name.toLowerCase() === 'uuid');\n\n if (isBothGenericIdOnDifferentResources) {\n return {\n isMatch: false,\n score: 0,\n evidence: [],\n sourceCandidate: source,\n targetCandidate: target,\n contradictionDetected: false,\n };\n }\n\n // 1. Name Match\n const nameMatch = matchIdentifierNames(\n source.name,\n target.name,\n sourceResource,\n targetResource,\n );\n\n if (nameMatch.isMatch) {\n let weight = 0.25;\n if (nameMatch.kind === 'exact') {\n weight = 0.3;\n } else if (nameMatch.kind === 'resource_prefixed') {\n weight = 0.35;\n }\n score += weight;\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight,\n description: `Identifier name match between '${source.propertyPath}' and '${target.propertyPath}' (${nameMatch.kind})`,\n details: {\n sourceProperty: source.propertyPath,\n targetProperty: target.propertyPath,\n sourceName: source.name,\n targetName: target.name,\n matchKind: nameMatch.kind,\n },\n });\n } else {\n // If names don't match at all, they might still be related if sample values overlap strongly,\n // but without name match or sample overlap, it's not a match.\n }\n\n // 2. Type Compatibility\n const typeComp = evaluateTypeCompatibility(source.type, target.type);\n if (typeComp.contradiction) {\n contradictionDetected = true;\n score -= 0.5;\n evidence.push({\n kind: 'CONTRADICTION',\n weight: -0.5,\n description: `Type incompatibility between '${source.propertyPath}' (${source.type}) and '${target.propertyPath}' (${target.type})`,\n details: {\n sourceType: source.type,\n targetType: target.type,\n },\n });\n } else if (nameMatch.isMatch && typeComp.compatible) {\n const typeWeight = 0.15;\n score += typeWeight;\n evidence.push({\n kind: 'SCHEMA_TYPE_MATCH',\n weight: typeWeight,\n description: `Compatible schema types: source '${source.type}', target '${target.type}'`,\n details: {\n sourceType: source.type,\n targetType: target.type,\n },\n });\n }\n\n // 3. Sample Value Overlap\n const overlap = calculateSampleOverlap(source, target);\n\n if (overlap.intersectionCount > 0) {\n const overlapWeight = Math.min(0.35, 0.15 + overlap.overlapRatio * 0.2);\n score += overlapWeight;\n evidence.push({\n kind: 'SAMPLE_VALUE_OVERLAP',\n weight: overlapWeight,\n description: `Observed ${overlap.intersectionCount} overlapping sample identifier values via keyed HMAC-SHA-256`,\n details: {\n intersectionCount: overlap.intersectionCount,\n overlapRatio: overlap.overlapRatio,\n },\n });\n }\n\n // Final match determination\n // Must have name match or sample value overlap, and overall positive score\n const isMatch = (nameMatch.isMatch || overlap.intersectionCount > 0) && score > 0.2;\n\n return {\n isMatch,\n score: Math.max(0, Math.min(1.0, score)),\n evidence,\n sourceCandidate: source,\n targetCandidate: target,\n contradictionDetected,\n };\n}\n","import type {\n EndpointTopologyType,\n EntityCardinality,\n EvidenceRecord,\n RelationshipConfidence,\n RelationshipConfidenceTier,\n RelationshipType,\n} from '../domain/types.js';\n\nexport interface ScoreComputationResult {\n readonly confidence: RelationshipConfidence;\n readonly inferredType: RelationshipType;\n}\n\n/**\n * Extracts a stable evidence identity key to prevent duplicate evidence inflation\n * while ensuring distinct properties sharing descriptions are not collapsed.\n */\nfunction getEvidenceIdentity(item: EvidenceRecord): string {\n const details = item.details as Record<string, unknown> | undefined;\n const src = details?.sourceProperty ? String(details.sourceProperty) : '';\n const tgt = details?.targetProperty ? String(details.targetProperty) : '';\n const desc = item.description ?? '';\n return `${item.kind}|${src}->${tgt}|${desc}`;\n}\n\n/**\n * Computes relationship confidence and assigns tier, reasons, and penalties.\n * Deduplicates evidence to ensure duplicate observations do not falsely inflate confidence.\n */\nexport function computeRelationshipConfidence(\n evidence: readonly EvidenceRecord[],\n): RelationshipConfidence {\n // Deduplicate evidence records by stable identity\n const seen = new Set<string>();\n const uniqueEvidence: EvidenceRecord[] = [];\n for (const item of evidence) {\n const key = getEvidenceIdentity(item);\n if (!seen.has(key)) {\n seen.add(key);\n uniqueEvidence.push(item);\n }\n }\n\n let score = 0;\n const reasons: string[] = [];\n const penalties: string[] = [];\n\n for (const item of uniqueEvidence) {\n score += item.weight;\n if (item.weight > 0) {\n reasons.push(item.description);\n } else if (item.weight < 0) {\n penalties.push(item.description);\n }\n }\n\n // Multi-observation consistency bonus strictly requires >= 3 distinct signal kinds and no contradictions\n const positiveSignalKinds = new Set<string>();\n for (const item of uniqueEvidence) {\n if (item.weight > 0) {\n positiveSignalKinds.add(item.kind);\n }\n }\n\n if (positiveSignalKinds.size >= 3 && penalties.length === 0) {\n const multiObsBonus = 0.1;\n score += multiObsBonus;\n reasons.push(\n `Multiple distinct corroborating signal kinds observed (${positiveSignalKinds.size} distinct kinds)`,\n );\n }\n\n // Clamp score strictly between 0.0 and 1.0\n const clampedScore = Math.max(0, Math.min(1.0, Math.round(score * 1000) / 1000));\n\n let tier: RelationshipConfidenceTier = 'LOW';\n if (clampedScore >= 0.8) {\n tier = 'HIGH';\n } else if (clampedScore >= 0.5) {\n tier = 'MEDIUM';\n }\n\n return {\n score: clampedScore,\n tier,\n reasons,\n penalties,\n };\n}\n\n/**\n * Infers relationship type, endpoint topology, and entity cardinality.\n * Strictly separates endpoint routing topology from entity-level data model cardinality.\n */\nexport function inferRelationshipSemantics(options: {\n isStructuralHierarchy?: boolean;\n hasIdentifierReference?: boolean;\n isCollectionToInstance?: boolean;\n isActionDispatch?: boolean;\n sourceClassification?: string;\n targetClassification?: string;\n sourceIsParent?: boolean;\n}): {\n type: RelationshipType;\n topology: EndpointTopologyType;\n cardinality: EntityCardinality;\n} {\n const {\n isStructuralHierarchy,\n hasIdentifierReference,\n isCollectionToInstance,\n isActionDispatch,\n sourceClassification,\n targetClassification,\n } = options;\n\n // Case 1: Action dispatch (e.g. POST /users/:id/activate)\n if (isActionDispatch) {\n return {\n type: 'ACTION',\n topology: 'ACTION_DISPATCH',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 2: Collection to instance relationship (e.g. GET /users -> GET /users/:id)\n if (isCollectionToInstance) {\n return {\n type: 'COLLECTION_INSTANCE',\n topology: 'COLLECTION_TO_INSTANCE',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 3: Pure structural hierarchy (e.g. GET /users/:id -> GET /users/:id/orders)\n if (isStructuralHierarchy && !hasIdentifierReference) {\n return {\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 4: Cross-resource identifier reference\n if (hasIdentifierReference) {\n // If source is a collection referencing a target single resource detail (MANY_TO_ONE)\n if (\n (sourceClassification === 'COLLECTION_READ' ||\n sourceClassification === 'NESTED_COLLECTION_READ') &&\n targetClassification === 'RESOURCE_READ'\n ) {\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'MANY_TO_ONE',\n };\n }\n\n // If source is a single resource referencing a target collection (ONE_TO_MANY)\n if (\n sourceClassification === 'RESOURCE_READ' &&\n (targetClassification === 'NESTED_COLLECTION_READ' ||\n targetClassification === 'COLLECTION_READ')\n ) {\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'ONE_TO_MANY',\n };\n }\n\n // Generic cross-endpoint foreign key reference when uniqueness is unverified (e.g. detail to detail)\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'UNKNOWN',\n };\n }\n\n if (isStructuralHierarchy) {\n return {\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n };\n }\n\n return {\n type: 'UNKNOWN',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'UNKNOWN',\n };\n}\n\n/**\n * Infers relationship type and cardinality based on endpoint classifications and evidence.\n */\nexport function inferRelationshipType(options: {\n isStructuralHierarchy: boolean;\n hasIdentifierReference: boolean;\n sourceClassification?: string;\n targetClassification?: string;\n sourceIsParent?: boolean;\n}): RelationshipType {\n return inferRelationshipSemantics(options).type;\n}\n\n","import type {\n ApiRelationship,\n DiscoveryEngineOptions,\n DiscoveryMetrics,\n EndpointAggregate,\n EndpointClassification,\n EndpointSchemaAggregate,\n EvidenceRecord,\n IdentifierCandidate,\n RelationshipType,\n} from '../domain/types.js';\nimport {\n extractEndpointParamIdentifiers,\n extractSchemaIdentifiers,\n normalizeEndpointInput,\n type EndpointInput,\n} from '../identifiers/identifier-extractor.js';\nimport { matchIdentifierCandidates } from '../identifiers/identifier-matcher.js';\nimport { classifyEndpoint } from '../resources/endpoint-classifier.js';\nimport {\n extractPathHierarchy,\n type PathResourceHierarchy,\n} from '../resources/resource-identifier.js';\nimport {\n computeRelationshipConfidence,\n inferRelationshipSemantics,\n inferRelationshipType,\n} from '../scoring/relationship-scorer.js';\n\n/**\n * Extracts indexing keys for an endpoint to prune non-viable candidate pair comparisons.\n */\nfunction extractEndpointIndexKeys(\n candidates: readonly IdentifierCandidate[],\n primaryResourceName?: string,\n): Set<string> {\n const keys = new Set<string>();\n const res = primaryResourceName?.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n for (const c of candidates) {\n const canon = c.name.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (!canon) continue;\n\n if (canon === 'id' || canon === 'uuid' || canon === 'pk') {\n if (res) {\n keys.add(`${res}id`);\n keys.add(`${res}uuid`);\n } else {\n keys.add(canon);\n }\n } else {\n keys.add(canon);\n }\n }\n\n return keys;\n}\n\nexport class RelationshipDiscoveryEngine {\n private readonly endpoints = new Map<string, EndpointInput>();\n private readonly schemas = new Map<string, EndpointSchemaAggregate>();\n private readonly classifications = new Map<string, EndpointClassification>();\n private readonly relationships = new Map<string, ApiRelationship>();\n private readonly options: DiscoveryEngineOptions;\n private lastMetrics?: DiscoveryMetrics;\n\n constructor(options?: DiscoveryEngineOptions) {\n this.options = {\n minConfidence: 0.3,\n maxSchemaDepth: 5,\n maxSampleValues: 50,\n stripPrefixes: [\n '/api',\n '/v1',\n '/v2',\n '/v3',\n '/v4',\n '/rest',\n '/public',\n '/internal',\n ],\n ...options,\n };\n }\n\n /**\n * Updates the HMAC fingerprint secret for privacy-preserving identifier matching.\n * Enables runtime key rotation without losing existing manual confirmation states.\n */\n public setFingerprintSecret(secret?: string): void {\n (this.options as { fingerprintSecret?: string }).fingerprintSecret = secret;\n }\n\n /**\n * Retrieves telemetry metrics from the most recent discovery run, if any.\n */\n public getLastMetrics(): DiscoveryMetrics | undefined {\n return this.lastMetrics;\n }\n\n /**\n * Registers a single endpoint aggregate or endpoint input.\n */\n public registerEndpoint(endpoint: EndpointAggregate | EndpointInput): void {\n const normalized = normalizeEndpointInput(endpoint);\n this.endpoints.set(normalized.id, normalized);\n\n // Compute classification\n const classification = classifyEndpoint(normalized, {\n stripPrefixes: this.options.stripPrefixes,\n });\n this.classifications.set(normalized.id, classification);\n }\n\n /**\n * Registers multiple endpoints in batch.\n */\n public registerEndpoints(\n endpoints: readonly (EndpointAggregate | EndpointInput)[],\n ): void {\n for (const ep of endpoints) {\n this.registerEndpoint(ep);\n }\n }\n\n /**\n * Registers a schema aggregate for an endpoint.\n */\n public registerSchema(schemaAggregate: EndpointSchemaAggregate): void {\n this.schemas.set(schemaAggregate.endpointId, schemaAggregate);\n }\n\n /**\n * Registers multiple schema aggregates in batch.\n */\n public registerSchemas(\n schemaAggregates: readonly EndpointSchemaAggregate[],\n ): void {\n for (const sa of schemaAggregates) {\n this.registerSchema(sa);\n }\n }\n\n /**\n * Retrieves the classification for a registered endpoint.\n */\n public getClassification(\n endpointId: string,\n ): EndpointClassification | undefined {\n return this.classifications.get(endpointId);\n }\n\n /**\n * Discovers relationships across all registered endpoints.\n */\n public discoverRelationships(\n options?: DiscoveryEngineOptions,\n ): readonly ApiRelationship[] {\n return this.discoverRelationshipsWithMetrics(options).relationships;\n }\n\n /**\n * Discovers relationships across all registered endpoints and returns execution metrics.\n */\n public discoverRelationshipsWithMetrics(\n options?: DiscoveryEngineOptions,\n ): { relationships: readonly ApiRelationship[]; metrics: DiscoveryMetrics } {\n const startTime = performance.now();\n const opts = { ...this.options, ...options };\n const endpointList = Array.from(this.endpoints.values());\n const minConfidence = opts.minConfidence ?? 0.3;\n\n // Cache pre-computed path hierarchies for each endpoint (O(N) instead of O(N^2))\n const endpointHierarchies = new Map<string, PathResourceHierarchy>();\n for (const ep of endpointList) {\n endpointHierarchies.set(\n ep.id,\n extractPathHierarchy(ep.pathTemplate, {\n stripPrefixes: opts.stripPrefixes,\n }),\n );\n }\n\n // Cache extracted identifiers per endpoint\n const endpointIdentifiers = new Map<string, IdentifierCandidate[]>();\n for (const ep of endpointList) {\n const paramIds = extractEndpointParamIdentifiers(ep, opts);\n const schemaAggregate = this.schemas.get(ep.id);\n const schemaIds = schemaAggregate\n ? extractSchemaIdentifiers(ep.id, schemaAggregate, opts)\n : [];\n endpointIdentifiers.set(ep.id, [...paramIds, ...schemaIds]);\n }\n\n // Build resource and identifier indices to prune non-viable candidate pairs\n const endpointsByResource = new Map<string, number[]>();\n const endpointsByIdKey = new Map<string, number[]>();\n\n for (let i = 0; i < endpointList.length; i++) {\n const ep = endpointList[i]!;\n const hier = endpointHierarchies.get(ep.id)!;\n const ids = endpointIdentifiers.get(ep.id) ?? [];\n\n if (hier.primaryResource?.name) {\n const resKey = hier.primaryResource.name.toLowerCase();\n const list = endpointsByResource.get(resKey) ?? [];\n list.push(i);\n endpointsByResource.set(resKey, list);\n }\n\n const keys = extractEndpointIndexKeys(ids, hier.primaryResource?.name);\n for (const key of keys) {\n const list = endpointsByIdKey.get(key) ?? [];\n list.push(i);\n endpointsByIdKey.set(key, list);\n }\n }\n\n const extractionTimeMs = performance.now() - startTime;\n const scoringStartTime = performance.now();\n\n const newlyDiscovered = new Map<string, ApiRelationship>();\n const now = Date.now();\n let evaluatedPairs = 0;\n let evaluatedIdentifierComparisons = 0;\n\n for (let i = 0; i < endpointList.length; i++) {\n const epA = endpointList[i]!;\n const classA = this.classifications.get(epA.id);\n const idsA = endpointIdentifiers.get(epA.id) ?? [];\n const hierA = endpointHierarchies.get(epA.id)!;\n\n // Identify candidate target endpoints via index lookup\n const candidateTargets = new Set<number>();\n\n if (hierA.primaryResource?.name) {\n const resMatches = endpointsByResource.get(\n hierA.primaryResource.name.toLowerCase(),\n );\n if (resMatches) {\n for (const idx of resMatches) {\n if (idx !== i) candidateTargets.add(idx);\n }\n }\n }\n\n const keysA = extractEndpointIndexKeys(idsA, hierA.primaryResource?.name);\n for (const key of keysA) {\n const idMatches = endpointsByIdKey.get(key);\n if (idMatches) {\n for (const idx of idMatches) {\n if (idx !== i) candidateTargets.add(idx);\n }\n }\n }\n\n for (const j of candidateTargets) {\n evaluatedPairs++;\n const epB = endpointList[j]!;\n const classB = this.classifications.get(epB.id);\n const idsB = endpointIdentifiers.get(epB.id) ?? [];\n const hierB = endpointHierarchies.get(epB.id)!;\n\n // ---------------------------------------------------------------------\n // 1. Structural Hierarchy Discovery (PARENT_CHILD)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierB.nestedResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n (classA?.type === 'RESOURCE_READ' || classA?.type === 'COLLECTION_READ') &&\n epB.pathTemplate.startsWith(epA.pathTemplate) &&\n (classB?.type === 'NESTED_COLLECTION_READ' ||\n classB?.type === 'NESTED_RESOURCE_READ' ||\n (classB?.type !== 'ACTION' && hierB.nestedResource))\n ) {\n const parentParam = hierB.resourceParams.get(hierA.primaryResource.name);\n if (parentParam) {\n const parentHasParam = hierA.resourceParams.has(hierA.primaryResource.name);\n if (!parentHasParam) {\n // epA is a root collection (e.g. /users) without the required instance param,\n // so it is not the direct parent of /users/:userId/orders\n continue;\n }\n }\n\n // B has A as a parent resource!\n // e.g. A is /users/:userId, and B is /users/:userId/orders\n const relId = `rel:structural:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.45,\n description: `Path nesting: resource '${hierB.nestedResource.name}' in '${epB.pathTemplate}' is hierarchically nested under parent resource '${hierA.primaryResource.name}' in '${epA.pathTemplate}'`,\n details: {\n parentResource: hierA.primaryResource.name,\n nestedResource: hierB.nestedResource.name,\n parentPath: epA.pathTemplate,\n childPath: epB.pathTemplate,\n },\n },\n ];\n\n // If B has parameter matching A's resource\n if (parentParam) {\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight: 0.25,\n description: `Child endpoint path includes parent parameter ':${parentParam}'`,\n details: { parentParam },\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n\n // ---------------------------------------------------------------------\n // 2. Collection vs Resource Read Relationship (COLLECTION_INSTANCE)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n !hierA.nestedResource &&\n !hierB.nestedResource\n ) {\n if (\n classA?.type === 'COLLECTION_READ' &&\n classB?.type === 'RESOURCE_READ'\n ) {\n const relId = `rel:collection:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.4,\n description: `Collection-to-resource hierarchy for resource '${hierA.primaryResource.name}'`,\n details: {\n collectionPath: epA.pathTemplate,\n detailPath: epB.pathTemplate,\n resource: hierA.primaryResource.name,\n },\n },\n ];\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'COLLECTION_INSTANCE',\n topology: 'COLLECTION_TO_INSTANCE',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n }\n\n // ---------------------------------------------------------------------\n // 3. Action Dispatch Relationship (ACTION)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n classA?.type === 'RESOURCE_READ' &&\n classB?.type === 'ACTION' &&\n epB.pathTemplate.startsWith(epA.pathTemplate)\n ) {\n const relId = `rel:action:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.5,\n description: `Action dispatch operation '${hierB.action ?? 'action'}' executed on resource '${hierA.primaryResource.name}'`,\n details: {\n resource: hierA.primaryResource.name,\n actionVerb: hierB.action,\n instancePath: epA.pathTemplate,\n actionPath: epB.pathTemplate,\n },\n },\n ];\n\n const parentParam = hierB.resourceParams.get(hierA.primaryResource.name);\n if (parentParam) {\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight: 0.25,\n description: `Action endpoint path includes instance parameter ':${parentParam}'`,\n details: { parentParam },\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'ACTION',\n topology: 'ACTION_DISPATCH',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n\n // ---------------------------------------------------------------------\n // 4. Identifier Reference Discovery (REFERENCES / Cross-Resource)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name\n ) {\n // Operations within the same primary resource domain are governed by\n // structural hierarchy (PARENT_CHILD), collection-to-instance (COLLECTION_INSTANCE),\n // or action dispatch (ACTION). They do not create cross-resource REFERENCES.\n continue;\n }\n\n // Target of a foreign key reference must be a canonical instance read resource endpoint\n const isCanonicalTarget =\n classB?.type === 'RESOURCE_READ' ||\n classB?.type === 'NESTED_RESOURCE_READ';\n\n if (!isCanonicalTarget) {\n continue;\n }\n\n const seenMatches = new Set<string>();\n\n for (const idA of idsA) {\n for (const idB of idsB) {\n // Target identifier must be a primary key candidate of the target resource\n const isTargetPrimaryKey =\n idB.isPrimaryKeyCandidate === true ||\n idB.name.toLowerCase() === 'id' ||\n idB.name.toLowerCase() === 'uuid' ||\n (hierB.primaryResource &&\n (idB.name.toLowerCase() ===\n `${hierB.primaryResource.name.toLowerCase()}id` ||\n idB.name.toLowerCase() ===\n `${hierB.primaryResource.name.toLowerCase()}uuid`)) ||\n idB.location === 'path_param';\n\n if (!isTargetPrimaryKey) {\n continue;\n }\n\n evaluatedIdentifierComparisons++;\n const matchKey = `${idA.propertyPath}->${idB.propertyPath}`;\n if (seenMatches.has(matchKey)) continue;\n\n const resA = hierA.primaryResource?.name;\n const resB = hierB.primaryResource?.name;\n\n const matchResult = matchIdentifierCandidates(\n idA,\n idB,\n resA,\n resB,\n );\n\n if (matchResult.isMatch) {\n seenMatches.add(matchKey);\n\n const evidence: EvidenceRecord[] = [...matchResult.evidence];\n\n // Check if structural hierarchy also supports this reference\n const isStructural =\n Boolean(hierB.nestedResource) &&\n hierA.primaryResource?.name === hierB.primaryResource?.name;\n\n if (isStructural) {\n evidence.push({\n kind: 'PATH_HIERARCHY',\n weight: 0.2,\n description: `Path structure corroborates identifier reference from parent '${hierA.primaryResource?.name}' to child '${hierB.nestedResource?.name}'`,\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n\n if (confidence.score >= minConfidence) {\n const semantics = inferRelationshipSemantics({\n isStructuralHierarchy: false,\n hasIdentifierReference: true,\n sourceClassification: classA?.type,\n targetClassification: classB?.type,\n });\n\n // Stable relationship ID: one canonical edge per source foreign key property to target endpoint\n const relId = `rel:reference:${epA.id}->${epB.id}:${idA.propertyPath}`;\n const existingDiscovered = newlyDiscovered.get(relId);\n if (\n existingDiscovered &&\n existingDiscovered.confidence.score >= confidence.score\n ) {\n continue;\n }\n\n const existingPersisted = this.relationships.get(relId);\n const status = existingPersisted ? existingPersisted.status : 'INFERRED';\n\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: semantics.type,\n topology: semantics.topology,\n cardinality: semantics.cardinality,\n status,\n confidence,\n evidence,\n sourceProperty: idA.propertyPath,\n targetProperty: idB.propertyPath,\n metadata: {\n sourceProperty: idA.propertyPath,\n targetProperty: idB.propertyPath,\n sourceName: idA.name,\n targetName: idB.name,\n sourceType: idA.type,\n targetType: idB.type,\n sourceLocation: idA.location,\n targetLocation: idB.location,\n },\n discoveredAt: existingPersisted ? existingPersisted.discoveredAt : now,\n updatedAt: now,\n };\n\n newlyDiscovered.set(relId, relationship);\n }\n }\n }\n }\n }\n }\n\n // Prune stale INFERRED relationships that are no longer supported by current observations,\n // while strictly preserving user CONFIRMED and REJECTED decisions.\n for (const [id, rel] of this.relationships.entries()) {\n if (rel.status === 'INFERRED' && !newlyDiscovered.has(id)) {\n this.relationships.delete(id);\n }\n }\n\n // Merge discovered relationships into store, keeping existing confirmed/rejected states\n for (const [id, rel] of newlyDiscovered.entries()) {\n const existing = this.relationships.get(id);\n if (existing) {\n this.relationships.set(id, {\n ...rel,\n status: existing.status, // preserve status\n discoveredAt: existing.discoveredAt,\n });\n } else {\n this.relationships.set(id, rel);\n }\n }\n\n const scoringTimeMs = performance.now() - scoringStartTime;\n const totalTimeMs = performance.now() - startTime;\n const totalPossiblePairs =\n endpointList.length * Math.max(0, endpointList.length - 1);\n const prunedPairs = Math.max(0, totalPossiblePairs - evaluatedPairs);\n\n const resultRelationships = this.getRelationships();\n\n this.lastMetrics = {\n totalEndpoints: endpointList.length,\n evaluatedPairs,\n prunedPairs,\n evaluatedIdentifierComparisons,\n discoveredRelationships: resultRelationships.length,\n extractionTimeMs,\n scoringTimeMs,\n totalTimeMs,\n };\n\n return {\n relationships: resultRelationships,\n metrics: this.lastMetrics,\n };\n }\n\n /**\n * Confirms an inferred relationship explicitly.\n */\n public confirmRelationship(id: string): ApiRelationship {\n const existing = this.relationships.get(id);\n if (!existing) {\n throw new Error(`Cannot confirm non-existent relationship: '${id}'`);\n }\n\n const updated: ApiRelationship = {\n ...existing,\n status: 'CONFIRMED',\n updatedAt: Date.now(),\n };\n this.relationships.set(id, updated);\n return updated;\n }\n\n /**\n * Rejects an inferred relationship explicitly.\n */\n public rejectRelationship(id: string): ApiRelationship {\n const existing = this.relationships.get(id);\n if (!existing) {\n throw new Error(`Cannot reject non-existent relationship: '${id}'`);\n }\n\n const updated: ApiRelationship = {\n ...existing,\n status: 'REJECTED',\n updatedAt: Date.now(),\n };\n this.relationships.set(id, updated);\n return updated;\n }\n\n /**\n * Retrieves all relationships sorted deterministically.\n */\n public getRelationships(): readonly ApiRelationship[] {\n return Array.from(this.relationships.values()).sort((a, b) => {\n // Sort by confidence score descending\n if (b.confidence.score !== a.confidence.score) {\n return b.confidence.score - a.confidence.score;\n }\n // Sort deterministically by id\n return a.id.localeCompare(b.id);\n });\n }\n\n /**\n * Retrieves a single relationship by id.\n */\n public getRelationship(id: string): ApiRelationship | undefined {\n return this.relationships.get(id);\n }\n\n /**\n * Retrieves all relationships involving a specific endpoint (either as source or target).\n */\n public getRelationshipsForEndpoint(\n endpointId: string,\n ): readonly ApiRelationship[] {\n return this.getRelationships().filter(\n (rel) =>\n rel.sourceEndpointId === endpointId ||\n rel.targetEndpointId === endpointId,\n );\n }\n\n /**\n * Clears all registered endpoints, schemas, and discovered relationships.\n */\n public clear(): void {\n this.endpoints.clear();\n this.schemas.clear();\n this.classifications.clear();\n this.relationships.clear();\n }\n}\n\n","import { singularize } from '@luxray/normalization';\nimport { extractPathHierarchy } from '@luxray/relationship-discovery';\n\n/**\n * Converts Express-style colon parameters (/users/:userId) to OpenAPI braces (/users/{userId}).\n */\nexport function toOpenApiPath(pathTemplate: string): string {\n return pathTemplate.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');\n}\n\n/**\n * Extracts parameter names from an Express-style or OpenAPI path template.\n */\nexport function extractPathParameterNames(pathTemplate: string): string[] {\n const params: string[] = [];\n // Match :param\n const colonMatches = pathTemplate.matchAll(/:([a-zA-Z0-9_]+)/g);\n for (const match of colonMatches) {\n if (match[1]) params.push(match[1]);\n }\n // Match {param}\n const braceMatches = pathTemplate.matchAll(/\\{([a-zA-Z0-9_]+)\\}/g);\n for (const match of braceMatches) {\n if (match[1] && !params.includes(match[1])) params.push(match[1]);\n }\n return params;\n}\n\n/**\n * Capitalizes the first letter of a string.\n */\nfunction capitalize(str: string): string {\n if (!str) return '';\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts camelCase, snake_case, kebab-case to PascalCase words.\n */\nfunction toPascalCase(str: string): string {\n return str\n .replace(/[^a-zA-Z0-9]+/g, ' ')\n .split(' ')\n .filter(Boolean)\n .map((word) => capitalize(word.toLowerCase()))\n .join('');\n}\n\n/**\n * Generates a clean, deterministic operationId from method, path template, and resource semantics.\n */\nexport function generateOperationId(\n method: string,\n pathTemplate: string,\n resourceName?: string,\n): string {\n const upperMethod = method.toUpperCase();\n const hierarchy = extractPathHierarchy(pathTemplate);\n const primary = resourceName ?? hierarchy.primaryResource?.name ?? 'Resource';\n const nested = hierarchy.nestedResource?.name;\n const action = hierarchy.action;\n const isTerminalParam =\n pathTemplate.endsWith('}') || /:[a-zA-Z0-9_]+$/.test(pathTemplate);\n\n // If terminal action verb (e.g. POST /users/:id/activate)\n if (action) {\n const actionPart = toPascalCase(action);\n const primaryPart = toPascalCase(singularize(primary));\n return `${action.toLowerCase()}${primaryPart}`;\n }\n\n // Nested resource (e.g. /users/:id/orders)\n if (nested) {\n const primarySingular = toPascalCase(singularize(primary));\n const nestedPlural = toPascalCase(hierarchy.nestedResource?.rawSegment ?? nested);\n const nestedSingular = toPascalCase(singularize(nested));\n\n if (upperMethod === 'GET') {\n return isTerminalParam\n ? `get${primarySingular}${nestedSingular}ById`\n : `list${primarySingular}${nestedPlural}`;\n }\n if (upperMethod === 'POST') {\n return `create${primarySingular}${nestedSingular}`;\n }\n if (upperMethod === 'PUT' || upperMethod === 'PATCH') {\n return `update${primarySingular}${nestedSingular}ById`;\n }\n if (upperMethod === 'DELETE') {\n return `delete${primarySingular}${nestedSingular}ById`;\n }\n }\n\n // Flat resource (e.g. /users or /users/:id)\n const primaryPlural = toPascalCase(hierarchy.primaryResource?.rawSegment ?? primary);\n const primarySingular = toPascalCase(singularize(primary));\n\n switch (upperMethod) {\n case 'GET':\n return isTerminalParam ? `get${primarySingular}ById` : `list${primaryPlural}`;\n case 'POST':\n return `create${primarySingular}`;\n case 'PUT':\n return `update${primarySingular}ById`;\n case 'PATCH':\n return `patch${primarySingular}ById`;\n case 'DELETE':\n return `delete${primarySingular}ById`;\n case 'HEAD':\n return `head${primaryPlural}`;\n case 'OPTIONS':\n return `options${primaryPlural}`;\n default:\n return `${method.toLowerCase()}${primarySingular}`;\n }\n}\n\n/**\n * Derives the OpenAPI tag for an endpoint based on its primary resource.\n */\nexport function deriveEndpointTag(pathTemplate: string): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const raw = hierarchy.primaryResource?.rawSegment ?? hierarchy.primaryResource?.name;\n if (!raw) return 'Default';\n return toPascalCase(raw);\n}\n\n/**\n * Generates an informative summary for an operation.\n */\nexport function generateOperationSummary(\n method: string,\n pathTemplate: string,\n resourceName?: string,\n): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const primary = resourceName ?? hierarchy.primaryResource?.name ?? 'item';\n const nested = hierarchy.nestedResource?.name;\n const action = hierarchy.action;\n const upperMethod = method.toUpperCase();\n const isTerminalParam =\n pathTemplate.endsWith('}') || /:[a-zA-Z0-9_]+$/.test(pathTemplate);\n\n if (action) {\n return `${capitalize(action)} ${singularize(primary)}`;\n }\n\n if (nested) {\n const parentSing = singularize(primary);\n const childSing = singularize(nested);\n const childPlural =\n hierarchy.nestedResource?.pluralName ??\n (nested.endsWith('s') ? nested : `${nested}s`);\n\n if (upperMethod === 'GET') {\n return isTerminalParam\n ? `Retrieve a specific ${childSing} for a ${parentSing}`\n : `List ${childPlural} for a ${parentSing}`;\n }\n if (upperMethod === 'POST') return `Create a new ${childSing} for a ${parentSing}`;\n if (upperMethod === 'PUT' || upperMethod === 'PATCH') return `Update ${childSing} for a ${parentSing}`;\n if (upperMethod === 'DELETE') return `Delete ${childSing} for a ${parentSing}`;\n }\n\n const sing = singularize(primary);\n const plural =\n hierarchy.primaryResource?.pluralName ??\n (primary.endsWith('s') ? primary : `${primary}s`);\n\n switch (upperMethod) {\n case 'GET':\n return isTerminalParam ? `Retrieve a ${sing} by ID` : `List all ${plural}`;\n case 'POST':\n return `Create a new ${sing}`;\n case 'PUT':\n case 'PATCH':\n return `Update an existing ${sing}`;\n case 'DELETE':\n return `Delete a ${sing}`;\n default:\n return `${upperMethod} on ${primary}`;\n }\n}\n\nexport const deriveResourceTag = deriveEndpointTag;\nexport const deriveOperationSummary = generateOperationSummary;\n","import { URL } from 'node:url';\nimport type { EndpointAggregate, QueryParamMetadata } from '@luxray/shared';\nimport type { ParameterObject, SchemaObject } from '../domain/openapi-types.js';\nimport { extractPathParameterNames } from './path-converter.js';\n\nexport interface ParameterConverterOptions {\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst INTEGER_REGEX = /^-?\\d+$/;\n\n/**\n * Checks if a sample value is safe to expose in OpenAPI examples.\n * Rejects redacted tokens, JWTs, authorization headers, and secrets.\n */\nexport function isSafeExampleValue(value: unknown): boolean {\n if (value === null || value === undefined) return false;\n if (typeof value === 'boolean' || typeof value === 'number') return true;\n if (typeof value === 'string') {\n if (value.trim() === '') return false;\n if (value.includes('[REDACTED]') || value.includes('***')) return false;\n if (/^(bearer|basic)\\s+/i.test(value)) return false;\n // JWT pattern\n if (/^[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}$/.test(value)) return false;\n // Common secret patterns\n if (/^(sk_live|sk_test|api_key|token)_[a-zA-Z0-9]+$/i.test(value)) return false;\n return true;\n }\n return false;\n}\n\n/**\n * Extracts sample values corresponding specifically to paramName from sample URLs based on pathTemplate.\n */\nexport function extractParamSampleValues(\n paramName: string,\n pathTemplate: string,\n sampleUrls: readonly string[] = [],\n): string[] {\n const templateSegments = pathTemplate.split('/').filter(Boolean);\n const paramIndex = templateSegments.findIndex(\n (seg) => seg === `:${paramName}` || seg === `{${paramName}}`,\n );\n if (paramIndex === -1) return [];\n\n const samples: string[] = [];\n\n for (const urlStr of sampleUrls) {\n try {\n const url = new URL(urlStr, 'https://example.com');\n const segments = url.pathname.split('/').filter(Boolean);\n\n // 1. Direct index match if segment lengths align\n if (segments.length === templateSegments.length && segments[paramIndex]) {\n samples.push(segments[paramIndex]);\n continue;\n }\n\n // 2. Relative alignment matching adjacent static segments\n if (paramIndex > 0) {\n const prevStatic = templateSegments[paramIndex - 1];\n if (prevStatic && !prevStatic.startsWith(':') && !prevStatic.startsWith('{')) {\n const matchIdx = segments.indexOf(prevStatic);\n const nextVal = matchIdx !== -1 ? segments[matchIdx + 1] : undefined;\n if (nextVal) {\n samples.push(nextVal);\n continue;\n }\n }\n }\n\n // 3. Fallback: if paramIndex is within bounds\n const boundVal = segments[paramIndex];\n if (boundVal) {\n samples.push(boundVal);\n }\n } catch {\n // Ignore malformed URL\n }\n }\n\n return samples.filter((s): s is string => Boolean(s));\n}\n\n/**\n * Heuristically detects scalar type and format of a path parameter from actual observed samples.\n */\nexport function inferPathParameterSchema(\n paramName: string,\n pathTemplate: string,\n sampleUrls: readonly string[] = [],\n): SchemaObject {\n const samples = extractParamSampleValues(paramName, pathTemplate, sampleUrls);\n\n if (samples.length > 0) {\n if (samples.every((s) => UUID_REGEX.test(s))) {\n return { type: 'string', format: 'uuid' };\n }\n\n if (samples.every((s) => INTEGER_REGEX.test(s))) {\n return { type: 'integer' };\n }\n\n return { type: 'string' };\n }\n\n return { type: 'string' };\n}\n\n/**\n * Converts observed path parameters to OpenAPI ParameterObject array.\n * Enforces OpenAPI requirement that path parameters MUST have required: true.\n */\nexport function convertPathParameters(\n endpoint: EndpointAggregate,\n): ParameterObject[] {\n const pathTemplate = endpoint.identity?.pathname ?? '';\n const paramNames = extractPathParameterNames(pathTemplate);\n const parameters: ParameterObject[] = [];\n\n for (const name of paramNames) {\n const schema = inferPathParameterSchema(name, pathTemplate, endpoint.sampleUrls);\n const paramObj: ParameterObject = {\n name,\n in: 'path',\n required: true,\n description: `Path parameter ${name}`,\n schema,\n };\n parameters.push(paramObj);\n }\n\n return parameters;\n}\n\n/**\n * Converts QueryParamMetadata from endpoint aggregate into an OpenAPI ParameterObject.\n * Employs conservative contract semantics: observed presence does not imply contract requiredness.\n */\nfunction convertQueryParam(\n paramName: string,\n meta: QueryParamMetadata,\n totalObservations: number,\n options: ParameterConverterOptions = {},\n): ParameterObject {\n let schema: SchemaObject;\n\n if (meta.isArray) {\n const itemType = meta.types.includes('number')\n ? 'number'\n : meta.types.includes('boolean')\n ? 'boolean'\n : 'string';\n schema = {\n type: 'array',\n items: { type: itemType },\n };\n } else if (meta.types.includes('number') && meta.types.length === 1) {\n schema = { type: 'number' };\n } else if (meta.types.includes('boolean') && meta.types.length === 1) {\n schema = { type: 'boolean' };\n } else {\n schema = { type: 'string' };\n }\n\n // Contract requirement: query parameters are optional by default in REST APIs\n // Observed presence is recorded in analytical metadata\n const paramObj: ParameterObject = {\n name: paramName,\n in: 'query',\n required: false,\n description: `Query parameter ${paramName}`,\n schema,\n };\n\n if (options.includeExtensions !== false) {\n const ext = paramObj as unknown as Record<string, unknown>;\n const isAlwaysObserved = totalObservations > 0 && meta.occurrences >= totalObservations;\n ext['x-luxray-observed-presence'] = isAlwaysObserved ? 'always' : 'optional';\n ext['x-luxray-occurrences'] = meta.occurrences;\n ext['x-luxray-total-observations'] = totalObservations;\n }\n\n if (\n options.includeExamples !== false &&\n meta.sampleValues &&\n meta.sampleValues.length > 0 &&\n isSafeExampleValue(meta.sampleValues[0])\n ) {\n paramObj.example = meta.sampleValues[0];\n }\n\n return paramObj;\n}\n\n/**\n * Converts all query parameters of an endpoint aggregate to OpenAPI ParameterObjects.\n */\nexport function convertQueryParameters(\n endpoint: EndpointAggregate,\n options: ParameterConverterOptions = {},\n): ParameterObject[] {\n const parameters: ParameterObject[] = [];\n const queryParams = endpoint.queryParams ?? {};\n\n for (const [name, meta] of Object.entries(queryParams)) {\n parameters.push(convertQueryParam(name, meta, endpoint.observationCount, options));\n }\n\n return parameters.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Extracts and combines all parameters (path and query) for an endpoint.\n */\nexport function convertEndpointParameters(\n endpoint: EndpointAggregate,\n options: ParameterConverterOptions = {},\n): ParameterObject[] {\n const pathParams = convertPathParameters(endpoint);\n const queryParams = convertQueryParameters(endpoint, options);\n return [...pathParams, ...queryParams];\n}\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n InferredUnionSchema,\n} from '@luxray/shared';\nimport type {\n OpenApiVersion,\n ReferenceObject,\n SchemaObject,\n SchemaType,\n} from '../domain/openapi-types.js';\nimport { isSafeExampleValue } from './parameter-converter.js';\n\nexport interface SchemaRefResolver {\n getRefForSchema(schema: InferredSchema): string | undefined;\n}\n\nexport interface SchemaConverterOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst ISO_DATETIME_REGEX =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/i;\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst URI_REGEX = /^https?:\\/\\/[^\\s/$.?#].[^\\s]*$/i;\nconst IPV4_REGEX = /^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$/;\n\n/**\n * Detects standard OpenAPI format string for string values based on observed samples.\n */\nexport function inferStringFormat(samples: readonly unknown[] = []): string | undefined {\n const strSamples = samples.filter((s): s is string => typeof s === 'string' && s.length > 0);\n if (strSamples.length === 0) return undefined;\n\n if (strSamples.every((s) => UUID_REGEX.test(s))) return 'uuid';\n if (strSamples.every((s) => ISO_DATETIME_REGEX.test(s))) return 'date-time';\n if (strSamples.every((s) => ISO_DATE_REGEX.test(s))) return 'date';\n if (strSamples.every((s) => EMAIL_REGEX.test(s))) return 'email';\n if (strSamples.every((s) => URI_REGEX.test(s))) return 'uri';\n if (strSamples.every((s) => IPV4_REGEX.test(s))) return 'ipv4';\n\n return undefined;\n}\n\n/**\n * Converts a primitive InferredPrimitiveSchema to OpenAPI SchemaObject.\n */\nfunction convertPrimitiveSchema(\n schema: InferredPrimitiveSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n if (schema.type === 'any') {\n return isNullable && !isOpenApi31 ? { nullable: true } : {};\n }\n\n if (schema.type === 'null') {\n if (isOpenApi31) {\n return { type: 'null' };\n }\n return { nullable: true };\n }\n\n const result: SchemaObject = {};\n const baseType = schema.type as SchemaType;\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = [baseType, 'null'];\n } else {\n result.type = baseType;\n result.nullable = true;\n }\n } else {\n result.type = baseType;\n }\n\n if (schema.type === 'string') {\n const format = inferStringFormat(schema.sampleValues);\n if (format) {\n result.format = format;\n }\n } else if (schema.type === 'integer') {\n const numbers = (schema.sampleValues ?? []).filter(\n (v: unknown): v is number => typeof v === 'number',\n );\n if (numbers.length > 0 && numbers.some((n: number) => n > 2147483647 || n < -2147483648)) {\n result.format = 'int64';\n } else if (numbers.length > 0) {\n result.format = 'int32';\n }\n }\n\n if (\n options.includeExamples !== false &&\n schema.sampleValues &&\n schema.sampleValues.length > 0 &&\n isSafeExampleValue(schema.sampleValues[0])\n ) {\n result.example = schema.sampleValues[0];\n }\n\n return result;\n}\n\n/**\n * Directly converts an InferredObjectSchema properties without attempting to resolve the root schema as a $ref.\n * Enables recursive and mutually recursive schema definitions in components.\n */\nexport function convertObjectSchemaDirect(\n schema: InferredObjectSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n const result: SchemaObject = {};\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = ['object', 'null'];\n } else {\n result.type = 'object';\n result.nullable = true;\n }\n } else {\n result.type = 'object';\n }\n\n const properties: Record<string, SchemaObject | ReferenceObject> = {};\n const requiredFields: string[] = [];\n\n const fieldEntries = (Object.entries(schema.fields ?? {}) as [string, FieldMetadata][]).sort(\n ([a], [b]) => a.localeCompare(b),\n );\n\n for (const [fieldName, fieldMeta] of fieldEntries) {\n const fieldSchema =\n fieldMeta.isNullable && !fieldMeta.schema.isNullable\n ? ({ ...fieldMeta.schema, isNullable: true } as InferredSchema)\n : fieldMeta.schema;\n\n properties[fieldName] = convertSchema(fieldSchema, options);\n\n if (!fieldMeta.isOptional) {\n requiredFields.push(fieldName);\n }\n }\n\n result.properties = properties;\n if (requiredFields.length > 0) {\n result.required = requiredFields;\n }\n\n return result;\n}\n\n/**\n * Converts an InferredObjectSchema to OpenAPI SchemaObject or ReferenceObject.\n */\nfunction convertObjectSchema(\n schema: InferredObjectSchema,\n options: SchemaConverterOptions,\n): SchemaObject | ReferenceObject {\n // Check if ref resolver has an existing component reference for this schema\n if (options.refResolver) {\n const ref = options.refResolver.getRefForSchema(schema);\n if (ref) {\n return { $ref: ref };\n }\n }\n\n return convertObjectSchemaDirect(schema, options);\n}\n\n/**\n * Converts an InferredArraySchema to OpenAPI SchemaObject.\n */\nfunction convertArraySchema(\n schema: InferredArraySchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n const result: SchemaObject = {};\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = ['array', 'null'];\n } else {\n result.type = 'array';\n result.nullable = true;\n }\n } else {\n result.type = 'array';\n }\n\n result.items = convertSchema(schema.itemSchema, options);\n\n return result;\n}\n\n/**\n * Converts an InferredUnionSchema to OpenAPI SchemaObject.\n * In OpenAPI 3.0.3, eliminates invalid { type: 'null' } variants in favor of nullable: true on anyOf.\n */\nfunction convertUnionSchema(\n schema: InferredUnionSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n if (!isOpenApi31) {\n let hasNullVariant = false;\n const nonNullVariants: (SchemaObject | ReferenceObject)[] = [];\n\n for (const v of schema.variants ?? []) {\n if (v.type === 'null') {\n hasNullVariant = true;\n } else {\n nonNullVariants.push(convertSchema(v, options));\n }\n }\n\n const shouldBeNullable = isNullable || hasNullVariant;\n if (shouldBeNullable) {\n return { anyOf: nonNullVariants, nullable: true };\n }\n return { anyOf: nonNullVariants };\n }\n\n const variants = (schema.variants ?? []).map((v: InferredSchema) =>\n convertSchema(v, options),\n );\n\n // If nullable in OpenAPI 3.1, ensure null type is present\n if (isNullable) {\n const hasNull = variants.some(\n (v: SchemaObject | ReferenceObject) =>\n 'type' in v &&\n (v.type === 'null' || (Array.isArray(v.type) && v.type.includes('null'))),\n );\n if (!hasNull) {\n variants.push({ type: 'null' });\n }\n return { anyOf: variants };\n }\n\n return { anyOf: variants };\n}\n\n/**\n * Main conversion function: converts any InferredSchema to an OpenAPI SchemaObject or ReferenceObject.\n */\nexport function convertSchema(\n schema: InferredSchema,\n options: SchemaConverterOptions = {},\n): SchemaObject | ReferenceObject {\n if (!schema) {\n return {};\n }\n\n switch (schema.type) {\n case 'string':\n case 'number':\n case 'integer':\n case 'boolean':\n case 'null':\n case 'any':\n return convertPrimitiveSchema(schema, options);\n\n case 'object':\n return convertObjectSchema(schema, options);\n\n case 'array':\n return convertArraySchema(schema, options);\n\n case 'union':\n return convertUnionSchema(schema, options);\n\n default:\n return {};\n }\n}\n","import type { EndpointSchemaAggregate, InferredRequestDefinition } from '@luxray/shared';\nimport type {\n MediaTypeObject,\n OpenApiVersion,\n RequestBodyObject,\n} from '../domain/openapi-types.js';\nimport {\n convertSchema,\n type SchemaRefResolver,\n} from './schema-converter.js';\n\nexport interface RequestConverterOptions {\n readonly method?: string;\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\n/**\n * Standardizes raw media types to clean content type keys (e.g. \"application/json; charset=utf-8\" -> \"application/json\").\n */\nexport function normalizeMediaType(rawType?: string): string {\n if (!rawType) return 'application/json';\n const clean = (rawType.split(';')[0] ?? '').trim().toLowerCase();\n return clean || 'application/json';\n}\n\n/**\n * Converts InferredRequestDefinition or EndpointSchemaAggregate requests to OpenAPI RequestBodyObject.\n * Employs defensible contract semantics: request body is only marked required when mutation method,\n * zero empty body observations, and high confidence evidence exist.\n */\nexport function convertRequestBody(\n schemaAggregate: EndpointSchemaAggregate | undefined,\n options: RequestConverterOptions = {},\n): RequestBodyObject | undefined {\n if (!schemaAggregate) return undefined;\n\n const content: Record<string, MediaTypeObject> = {};\n let hasContent = false;\n\n // Primary request or multiple requests by media type\n const requests: InferredRequestDefinition[] = [];\n if (schemaAggregate.requests) {\n requests.push(...Object.values(schemaAggregate.requests));\n } else if (schemaAggregate.request) {\n requests.push(schemaAggregate.request);\n }\n\n if (requests.length === 0) return undefined;\n\n for (const reqDef of requests) {\n if (!reqDef || !reqDef.schema) continue;\n\n const mediaType = normalizeMediaType(reqDef.mediaType || reqDef.contentType);\n const schema = convertSchema(reqDef.schema, {\n openApiVersion: options.openApiVersion,\n includeExamples: options.includeExamples,\n refResolver: options.refResolver,\n });\n\n const mediaTypeObj: MediaTypeObject = {\n schema,\n };\n\n if (\n options.includeExtensions !== false &&\n reqDef.provenance?.confidence\n ) {\n (mediaTypeObj as Record<string, unknown>)['x-luxray-confidence'] =\n reqDef.provenance.confidence.score;\n (mediaTypeObj as Record<string, unknown>)['x-luxray-observations'] =\n reqDef.provenance.totalObservations;\n }\n\n content[mediaType] = mediaTypeObj;\n hasContent = true;\n }\n\n if (!hasContent) return undefined;\n\n // Defensible contract requiredness evaluation\n const upperMethod = (options.method || 'POST').toUpperCase();\n const isMutation = ['POST', 'PUT', 'PATCH'].includes(upperMethod);\n const totalObs = requests.reduce((acc, r) => acc + (r.provenance?.totalObservations ?? 0), 0);\n const emptyObs = requests.reduce((acc, r) => acc + (r.provenance?.emptyBodyObservations ?? 0), 0);\n const minConf = requests.length > 0\n ? Math.min(...requests.map((r) => r.provenance?.confidence?.score ?? 0))\n : 0;\n\n const isDefensiblyRequired = isMutation && totalObs >= 3 && emptyObs === 0 && minConf >= 0.75;\n\n const reqBodyObj: RequestBodyObject = {\n description: 'Request payload',\n required: isDefensiblyRequired,\n content,\n };\n\n if (options.includeExtensions !== false) {\n const ext = reqBodyObj as unknown as Record<string, unknown>;\n ext['x-luxray-empty-body-observations'] = emptyObs;\n ext['x-luxray-observed-presence'] = emptyObs === 0 ? 'always' : 'optional';\n }\n\n return reqBodyObj;\n}\n","import type {\n EndpointAggregate,\n EndpointSchemaAggregate,\n InferredResponseDefinition,\n} from '@luxray/shared';\nimport type {\n MediaTypeObject,\n OpenApiVersion,\n ResponseObject,\n ResponsesObject,\n} from '../domain/openapi-types.js';\nimport {\n convertSchema,\n type SchemaRefResolver,\n} from './schema-converter.js';\nimport { normalizeMediaType } from './request-converter.js';\n\nexport interface ResponseConverterOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\nconst HTTP_STATUS_DESCRIPTIONS: Record<number, string> = {\n 200: 'OK - Successful response',\n 201: 'Created - Resource created successfully',\n 202: 'Accepted - Request accepted for processing',\n 204: 'No Content - Request succeeded with no response body',\n 301: 'Moved Permanently',\n 302: 'Found',\n 304: 'Not Modified',\n 400: 'Bad Request - Client error in request parameters or body',\n 401: 'Unauthorized - Authentication credentials required or invalid',\n 403: 'Forbidden - Insufficient permissions to access resource',\n 404: 'Not Found - The requested resource does not exist',\n 405: 'Method Not Allowed',\n 409: 'Conflict - Request conflict with current state of resource',\n 422: 'Unprocessable Entity - Semantic errors in request payload',\n 429: 'Too Many Requests - Rate limit exceeded',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * Returns a human-friendly description for an HTTP status code.\n */\nexport function getStatusDescription(statusCode: number): string {\n return HTTP_STATUS_DESCRIPTIONS[statusCode] ?? `HTTP ${statusCode} response`;\n}\n\n/**\n * Converts InferredResponseDefinitions and EndpointAggregate status codes into OpenAPI ResponsesObject.\n */\nexport function convertResponses(\n schemaAggregate: EndpointSchemaAggregate | undefined,\n endpointAggregate: EndpointAggregate | undefined,\n options: ResponseConverterOptions = {},\n): ResponsesObject {\n const responses: ResponsesObject = {};\n\n // First, extract schemas from EndpointSchemaAggregate if available\n const responseMap = schemaAggregate?.responses ?? {};\n const statusCodes = new Set<number>();\n\n for (const statusCodeStr of Object.keys(responseMap)) {\n const code = Number(statusCodeStr);\n if (!isNaN(code)) statusCodes.add(code);\n }\n\n // Also include status codes observed in EndpointAggregate\n if (endpointAggregate?.statusCodes) {\n for (const codeStr of Object.keys(endpointAggregate.statusCodes)) {\n const code = Number(codeStr);\n if (!isNaN(code)) statusCodes.add(code);\n }\n }\n\n // Default fallback if no status codes known\n if (statusCodes.size === 0) {\n statusCodes.add(200);\n }\n\n const sortedCodes = Array.from(statusCodes).sort((a, b) => a - b);\n\n for (const statusCode of sortedCodes) {\n const codeStr = statusCode.toString() as `${1 | 2 | 3 | 4 | 5}${number}${number}`;\n const mediaTypeDefinitions = (responseMap as Record<number, Record<string, InferredResponseDefinition>>)[statusCode] ?? {};\n const mediaTypeEntries = Object.entries(mediaTypeDefinitions) as [string, InferredResponseDefinition][];\n\n const description = getStatusDescription(statusCode);\n\n // 204 No Content has no body\n if (statusCode === 204) {\n responses[codeStr] = {\n description,\n };\n continue;\n }\n\n if (mediaTypeEntries.length === 0) {\n // Empty response or un-inferred schema\n responses[codeStr] = {\n description,\n };\n continue;\n }\n\n const content: Record<string, MediaTypeObject> = {};\n\n for (const [rawType, def] of mediaTypeEntries) {\n const mediaType = normalizeMediaType(rawType || def.mediaType || def.contentType);\n const schema = convertSchema(def.schema, {\n openApiVersion: options.openApiVersion,\n includeExamples: options.includeExamples,\n refResolver: options.refResolver,\n });\n\n const mediaTypeObj: MediaTypeObject = {\n schema,\n };\n\n if (\n options.includeExtensions !== false &&\n def.provenance?.confidence\n ) {\n (mediaTypeObj as Record<string, unknown>)['x-luxray-confidence'] =\n def.provenance.confidence.score;\n (mediaTypeObj as Record<string, unknown>)['x-luxray-observations'] =\n def.provenance.totalObservations;\n }\n\n content[mediaType] = mediaTypeObj;\n }\n\n const responseObj: ResponseObject = {\n description,\n content,\n };\n\n responses[codeStr] = responseObj;\n }\n\n return responses;\n}\n","import type { ApiRelationship, InferredSchema } from '@luxray/shared';\nimport type { LinkObject, ParameterObject } from '../domain/openapi-types.js';\n\nexport interface LinkConverterOptions {\n /** Minimum confidence score required to generate Link Object (default: 0.5) */\n readonly minConfidence?: number;\n /** Whether only CONFIRMED relationships can generate Link Objects (default: false) */\n readonly onlyConfirmed?: boolean;\n /** Whether to output Luxray analytical extensions (x-luxray-*) (default: true) */\n readonly includeExtensions?: boolean;\n}\n\nexport interface LinkValidationContext {\n readonly relationship: ApiRelationship;\n readonly targetOperationId?: string;\n readonly targetParameters?: readonly ParameterObject[];\n readonly targetParamName?: string;\n readonly sourceResponseSchema?: InferredSchema;\n readonly options?: LinkConverterOptions;\n}\n\nexport interface ConvertedLinkResult {\n readonly linkName: string;\n readonly link: LinkObject;\n}\n\n/**\n * Builds a deterministic, valid link name for OpenAPI links map.\n */\nexport function generateLinkName(\n targetOperationId: string,\n sourceProperty?: string,\n): string {\n const cleanOp = targetOperationId.replace(/[^a-zA-Z0-9]/g, '');\n const capitalizedOp = cleanOp.charAt(0).toUpperCase() + cleanOp.slice(1);\n if (sourceProperty) {\n const cleanProp = sourceProperty.replace(/[^a-zA-Z0-9]/g, '');\n const capitalizedProp = cleanProp.charAt(0).toUpperCase() + cleanProp.slice(1);\n return `${capitalizedOp}By${capitalizedProp}`;\n }\n return capitalizedOp;\n}\n\n/**\n * Validates and converts an ApiRelationship into an OpenAPI LinkObject.\n * Supports both context object signature and legacy positional parameters.\n */\nexport function convertRelationshipToLink(\n contextOrRel: LinkValidationContext | ApiRelationship,\n targetOperationId?: string,\n targetParamName?: string,\n options?: LinkConverterOptions,\n): ConvertedLinkResult | undefined {\n let ctx: LinkValidationContext;\n\n if ('relationship' in contextOrRel) {\n ctx = contextOrRel;\n } else {\n ctx = {\n relationship: contextOrRel,\n targetOperationId,\n targetParamName,\n options,\n };\n }\n\n const { relationship, sourceResponseSchema } = ctx;\n const targetOpId = ctx.targetOperationId;\n const opts = ctx.options ?? {};\n\n // 1. Target operation must exist\n if (!targetOpId) {\n return undefined;\n }\n\n // 2. Reject explicitly rejected relationships\n if (relationship.status === 'REJECTED') {\n return undefined;\n }\n\n // 3. Check confirmation constraint if enabled\n if (opts.onlyConfirmed && relationship.status !== 'CONFIRMED') {\n return undefined;\n }\n\n // 4. Check confidence threshold and evidence presence\n const minConfidence = opts.minConfidence ?? 0.5;\n if (!relationship.confidence || relationship.confidence.score < minConfidence) {\n return undefined;\n }\n\n const hasEvidence =\n (relationship.evidence && relationship.evidence.length > 0) ||\n (relationship.confidence?.reasons && relationship.confidence.reasons.length > 0);\n\n if (!hasEvidence) {\n return undefined;\n }\n\n // 5. Collection Safety: Collection responses (root array) must NOT generate misleading\n // links to arbitrary collection elements ($response.body#/items/0/id)\n if (sourceResponseSchema && sourceResponseSchema.type === 'array') {\n return undefined;\n }\n\n const sourceProp = relationship.sourceProperty;\n\n // 6. Runtime expression resolution: If source schema is known, verify sourceProperty actually exists\n if (sourceResponseSchema && sourceResponseSchema.type === 'object' && sourceProp) {\n const fields = sourceResponseSchema.fields ?? {};\n if (!fields[sourceProp]) {\n return undefined;\n }\n }\n\n // 7. Target parameter matching: Target parameter must actually exist in the target operation\n let resolvedTargetParam = ctx.targetParamName || relationship.targetProperty;\n\n if (ctx.targetParameters && ctx.targetParameters.length > 0) {\n const paramNames = ctx.targetParameters.map((p) => p.name);\n\n if (resolvedTargetParam && !paramNames.includes(resolvedTargetParam)) {\n const matched = paramNames.find(\n (p) =>\n p === sourceProp ||\n p === 'id' ||\n (sourceProp && p.toLowerCase().includes(sourceProp.toLowerCase())),\n );\n if (matched) {\n resolvedTargetParam = matched;\n } else {\n return undefined;\n }\n } else if (!resolvedTargetParam) {\n const pathParam = ctx.targetParameters.find((p) => p.in === 'path');\n if (pathParam) {\n resolvedTargetParam = pathParam.name;\n }\n }\n }\n\n const parameters: Record<string, string> = {};\n if (sourceProp && resolvedTargetParam) {\n parameters[resolvedTargetParam] = `$response.body#/${sourceProp}`;\n }\n\n const link: LinkObject = {\n operationId: targetOpId,\n description: `Discovered API relationship (${relationship.type}) with ${Math.round(\n (relationship.confidence?.score ?? 0) * 100,\n )}% confidence`,\n };\n\n if (Object.keys(parameters).length > 0) {\n link.parameters = parameters;\n }\n\n if (opts.includeExtensions !== false) {\n const extObj = link as Record<string, unknown>;\n extObj['x-luxray-relationship-id'] = relationship.id;\n extObj['x-luxray-type'] = relationship.type;\n if (relationship.topology) extObj['x-luxray-topology'] = relationship.topology;\n if (relationship.cardinality) extObj['x-luxray-cardinality'] = relationship.cardinality;\n if (relationship.confidence) extObj['x-luxray-confidence'] = relationship.confidence.score;\n }\n\n const linkName = generateLinkName(targetOpId, sourceProp);\n\n return { linkName, link };\n}\n\n/**\n * Groups discovered relationships by source endpoint ID.\n */\nexport function groupRelationshipsBySource(\n relationships: readonly ApiRelationship[] = [],\n): Map<string, ApiRelationship[]> {\n const map = new Map<string, ApiRelationship[]>();\n for (const rel of relationships) {\n if (!rel.sourceEndpointId) continue;\n const list = map.get(rel.sourceEndpointId) ?? [];\n list.push(rel);\n map.set(rel.sourceEndpointId, list);\n }\n return map;\n}\n","import type { InferredObjectSchema, InferredSchema } from '@luxray/shared';\nimport type {\n ComponentsObject,\n OpenApiVersion,\n SchemaObject,\n} from '../domain/openapi-types.js';\nimport {\n convertObjectSchemaDirect,\n type SchemaRefResolver,\n} from '../converters/schema-converter.js';\n\nexport interface ComponentRegistryOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExamples?: boolean;\n}\n\n/**\n * Computes a deterministic structural signature for an InferredSchema to detect identical shapes.\n * Handles recursive and mutually recursive schemas gracefully via visited set.\n */\nexport function computeSchemaFingerprint(\n schema: InferredSchema,\n visited: Set<InferredSchema> = new Set(),\n): string {\n if (!schema) return 'empty';\n if (visited.has(schema)) return '[circular]';\n\n visited.add(schema);\n\n try {\n if (schema.type === 'object') {\n const fieldParts: string[] = [];\n const sortedKeys = Object.keys(schema.fields ?? {}).sort();\n for (const key of sortedKeys) {\n const field = schema.fields[key];\n if (!field) continue;\n const fieldSig = computeSchemaFingerprint(field.schema, visited);\n const opt = field.isOptional ? 'opt' : 'req';\n const nll = field.isNullable ? 'null' : 'notnull';\n fieldParts.push(`${key}:${opt}:${nll}:${fieldSig}`);\n }\n return `object{${fieldParts.join(';')}}`;\n }\n\n if (schema.type === 'array') {\n return `array[${computeSchemaFingerprint(schema.itemSchema, visited)}]`;\n }\n\n if (schema.type === 'union') {\n const varSigs = (schema.variants ?? [])\n .map((v) => computeSchemaFingerprint(v, visited))\n .sort()\n .join('|');\n return `union(${varSigs})`;\n }\n\n return `primitive(${schema.type}:${Boolean(schema.isNullable)})`;\n } finally {\n visited.delete(schema);\n }\n}\n\n/**\n * Manages OpenAPI components.schemas extraction, deduplication, and reference creation.\n * Preserves semantic distinction across entities (e.g. User vs Role with same shape).\n */\nexport class ComponentRegistry implements SchemaRefResolver {\n private readonly schemasByName = new Map<string, SchemaObject>();\n private readonly refBySchema = new Map<InferredSchema, string>();\n private readonly nameByEntityAndFingerprint = new Map<string, string>();\n private readonly options: ComponentRegistryOptions;\n\n constructor(options: ComponentRegistryOptions = {}) {\n this.options = options;\n }\n\n /**\n * Returns a reference path '#/components/schemas/{name}' if this schema has been registered as a component.\n */\n public getRefForSchema(schema: InferredSchema): string | undefined {\n if (!schema || schema.type !== 'object') {\n return undefined;\n }\n\n // Direct reference match\n const directRef = this.refBySchema.get(schema);\n if (directRef) {\n return directRef;\n }\n\n return undefined;\n }\n\n /**\n * Registers an object schema under a suggested base name.\n * Preserves semantic identity: only schemas with both the same suggested entity name\n * AND matching structural fingerprint share a component definition.\n */\n public registerComponent(\n suggestedName: string,\n schema: InferredObjectSchema,\n ): string {\n const fingerprint = computeSchemaFingerprint(schema);\n const entityKey = `${suggestedName}::${fingerprint}`;\n\n const existingName = this.nameByEntityAndFingerprint.get(entityKey);\n if (existingName) {\n this.refBySchema.set(schema, `#/components/schemas/${existingName}`);\n return existingName;\n }\n\n // Determine unique name\n let finalName = suggestedName.replace(/[^a-zA-Z0-9_]/g, '');\n if (!finalName) finalName = 'Schema';\n\n let counter = 1;\n let candidateName = finalName;\n while (this.schemasByName.has(candidateName)) {\n counter++;\n candidateName = `${finalName}_${counter}`;\n }\n finalName = candidateName;\n\n // Record mappings before converting so child recursive fields can find it\n this.nameByEntityAndFingerprint.set(entityKey, finalName);\n this.refBySchema.set(schema, `#/components/schemas/${finalName}`);\n\n // Convert schema properties directly (nested references resolve via this.getRefForSchema)\n const converted = convertObjectSchemaDirect(schema, {\n openApiVersion: this.options.openApiVersion,\n includeExamples: this.options.includeExamples,\n refResolver: this,\n });\n\n this.schemasByName.set(finalName, converted);\n\n return finalName;\n }\n\n /**\n * Returns all registered schema components as a record.\n */\n public getSchemas(): Record<string, SchemaObject> {\n const result: Record<string, SchemaObject> = {};\n for (const [name, schema] of this.schemasByName.entries()) {\n result[name] = schema;\n }\n return result;\n }\n\n /**\n * Total number of extracted schema components.\n */\n public get count(): number {\n return this.schemasByName.size;\n }\n\n /**\n * Builds the ComponentsObject containing schemas.\n */\n public toComponentsObject(): ComponentsObject | undefined {\n if (this.schemasByName.size === 0) {\n return undefined;\n }\n return {\n schemas: this.getSchemas(),\n };\n }\n}\n","import type { OpenApiDocument } from '../domain/openapi-types.js';\n\n/**\n * Serializes an OpenAPI document to formatted JSON.\n */\nexport function serializeToJson(doc: OpenApiDocument, indent = 2): string {\n return JSON.stringify(doc, null, indent);\n}\n\n/**\n * Escapes and quotes a YAML string scalar when necessary.\n */\nfunction formatYamlString(str: string): string {\n if (str === '') return \"''\";\n\n // Check if string needs quotes in YAML plain scalar\n const needsQuotes =\n /(?::\\s|:\\t|:$)/.test(str) ||\n /\\s#/.test(str) ||\n /[{}[\\]&*?|<>=!%@`\\n\\r\\t]/.test(str) ||\n str.startsWith(' ') ||\n str.endsWith(' ') ||\n str.startsWith('- ') ||\n str.startsWith('? ') ||\n str.startsWith(': ') ||\n str.startsWith('#') ||\n /^(true|false|null|yes|no|on|off)$/i.test(str) ||\n /^-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(str) ||\n /^0[xob]/i.test(str);\n\n if (!needsQuotes) {\n return str;\n }\n\n // Handle multiline strings\n if (str.includes('\\n')) {\n // If double quote escaping is safe:\n return JSON.stringify(str);\n }\n\n // Use double quotes and escape backslashes and double quotes\n return JSON.stringify(str);\n}\n\n/**\n * Recursively formats a JavaScript value as YAML.\n */\nfunction dumpYamlValue(value: unknown, depth: number, indentSize: number): string {\n const currentIndent = ' '.repeat(depth * indentSize);\n\n if (value === null || value === undefined) {\n return 'null';\n }\n\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value.toString() : 'null';\n }\n\n if (typeof value === 'string') {\n return formatYamlString(value);\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]';\n }\n\n const lines: string[] = [];\n for (const item of value) {\n if (item === null || item === undefined || typeof item !== 'object') {\n lines.push(`${currentIndent}- ${dumpYamlValue(item, depth + 1, indentSize)}`);\n } else if (Array.isArray(item)) {\n lines.push(`${currentIndent}-`);\n lines.push(dumpYamlValue(item, depth + 1, indentSize));\n } else {\n // Object item in array\n const objLines = dumpYamlObject(item as Record<string, unknown>, depth + 1, indentSize, true);\n lines.push(objLines);\n }\n }\n return lines.join('\\n');\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) {\n return '{}';\n }\n return dumpYamlObject(obj, depth, indentSize, false);\n }\n\n return formatYamlString(String(value));\n}\n\n/**\n * Dumps an object to YAML key-value lines.\n */\nfunction dumpYamlObject(\n obj: Record<string, unknown>,\n depth: number,\n indentSize: number,\n firstLinePrefixedDash: boolean,\n): string {\n const lines: string[] = [];\n const keys = Object.keys(obj);\n const currentIndent = ' '.repeat(depth * indentSize);\n const dashIndent = ' '.repeat(Math.max(0, (depth - 1) * indentSize));\n\n let isFirst = firstLinePrefixedDash;\n\n for (const key of keys) {\n const val = obj[key];\n const formattedKey = /^[a-zA-Z0-9_.-]+$/.test(key) ? key : formatYamlString(key);\n const prefix = isFirst ? `${dashIndent}- ` : currentIndent;\n isFirst = false;\n\n if (val === undefined) {\n continue;\n }\n\n if (val === null || typeof val !== 'object') {\n lines.push(`${prefix}${formattedKey}: ${dumpYamlValue(val, depth + 1, indentSize)}`);\n } else if (Array.isArray(val)) {\n if (val.length === 0) {\n lines.push(`${prefix}${formattedKey}: []`);\n } else {\n lines.push(`${prefix}${formattedKey}:`);\n lines.push(dumpYamlValue(val, depth + 1, indentSize));\n }\n } else {\n // Nested object\n const nestedKeys = Object.keys(val as Record<string, unknown>);\n if (nestedKeys.length === 0) {\n lines.push(`${prefix}${formattedKey}: {}`);\n } else {\n lines.push(`${prefix}${formattedKey}:`);\n lines.push(dumpYamlValue(val, depth + 1, indentSize));\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Standard top-level OpenAPI keys order for clean, conventional documents.\n */\nconst TOP_LEVEL_ORDER: (keyof OpenApiDocument)[] = [\n 'openapi',\n 'info',\n 'jsonSchemaDialect',\n 'servers',\n 'tags',\n 'paths',\n 'components',\n 'security',\n 'externalDocs',\n];\n\n/**\n * Serializes an OpenAPI document to clean YAML without external runtime dependencies.\n */\nexport function serializeToYaml(doc: OpenApiDocument, indent = 2): string {\n // Sort top-level keys canonically\n const orderedDoc: Record<string, unknown> = {};\n\n const docRecord = doc as unknown as Record<string, unknown>;\n\n for (const key of TOP_LEVEL_ORDER) {\n if (key in doc && docRecord[key] !== undefined) {\n orderedDoc[key] = docRecord[key];\n }\n }\n\n // Add any remaining keys (e.g. x-luxray-* extensions)\n for (const [key, value] of Object.entries(doc)) {\n if (!(key in orderedDoc) && value !== undefined) {\n orderedDoc[key] = value;\n }\n }\n\n return dumpYamlObject(orderedDoc, 0, indent, false) + '\\n';\n}\n","import type {\n ApiRelationship,\n EndpointAggregate,\n EndpointSchemaAggregate,\n InferredArraySchema,\n InferredObjectSchema,\n InferredResponseDefinition,\n} from '@luxray/shared';\nimport { singularize } from '@luxray/normalization';\nimport { extractPathHierarchy } from '@luxray/relationship-discovery';\nimport type {\n ComponentsObject,\n InfoObject,\n OpenApiDocument,\n OpenApiVersion,\n OperationObject,\n ParameterObject,\n PathItemObject,\n PathsObject,\n ServerObject,\n TagObject,\n} from '../domain/openapi-types.js';\nimport type {\n GenerationInput,\n GenerationMetrics,\n OpenApiGeneratorOptions,\n} from '../domain/generator-types.js';\nimport {\n deriveOperationSummary,\n deriveResourceTag,\n generateOperationId,\n toOpenApiPath,\n} from '../converters/path-converter.js';\nimport { convertEndpointParameters } from '../converters/parameter-converter.js';\nimport { convertRequestBody } from '../converters/request-converter.js';\nimport { convertResponses } from '../converters/response-converter.js';\nimport {\n convertRelationshipToLink,\n groupRelationshipsBySource,\n} from '../converters/link-converter.js';\nimport { ComponentRegistry } from '../components/component-registry.js';\nimport { serializeToJson, serializeToYaml } from '../serializers/serializer.js';\n\n/**\n * Capitalizes string.\n */\nfunction capitalize(str: string): string {\n if (!str) return '';\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Derives a clean PascalCase component schema name for an entity.\n */\nfunction deriveEntityComponentName(\n pathTemplate: string,\n method: string,\n isRequest = false,\n): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const resource = hierarchy.nestedResource?.name ?? hierarchy.primaryResource?.name ?? 'Entity';\n const singular = capitalize(singularize(resource));\n\n if (isRequest) {\n const action = method.toUpperCase() === 'POST' ? 'Create' : 'Update';\n return `${action}${singular}Request`;\n }\n\n return singular;\n}\n\n/**\n * Core engine for generating OpenAPI 3.1 and 3.0 specification documents.\n */\nexport class OpenApiGenerator {\n private readonly options: OpenApiGeneratorOptions;\n private lastMetrics?: GenerationMetrics;\n\n constructor(options: OpenApiGeneratorOptions = {}) {\n this.options = {\n openApiVersion: options.openApiVersion ?? '3.1.0',\n includeExtensions: options.includeExtensions ?? true,\n generateLinks: options.generateLinks ?? true,\n minRelationshipConfidence: options.minRelationshipConfidence ?? 0.5,\n extractComponents: options.extractComponents ?? true,\n outputFormat: options.outputFormat ?? 'object',\n indent: options.indent ?? 2,\n ...options,\n };\n }\n\n /**\n * Generates a complete OpenAPI document object from endpoint and schema aggregates.\n */\n public generate(input: GenerationInput): OpenApiDocument {\n const startTime = Date.now();\n const version: OpenApiVersion = this.options.openApiVersion ?? '3.1.0';\n const isOpenApi31 = version !== '3.0.3';\n\n // Index schemas by endpointId\n const schemaMap = new Map<string, EndpointSchemaAggregate>();\n for (const schema of input.schemas ?? []) {\n schemaMap.set(schema.endpointId, schema);\n }\n\n // Index endpoint aggregates by identity id\n const endpointMap = new Map<string, EndpointAggregate>();\n for (const ep of input.endpoints) {\n endpointMap.set(ep.identity.id, ep);\n }\n\n // Set up component registry\n const componentRegistry = new ComponentRegistry({\n openApiVersion: version,\n includeExamples: true,\n });\n\n // Step 1: Pre-register components if enabled\n if (this.options.extractComponents !== false) {\n this.preRegisterComponents(input.endpoints, schemaMap, componentRegistry);\n }\n\n // Step 2: Build parameters and guaranteed-unique operation ID lookup\n const operationIdByEndpointId = new Map<string, string>();\n const parametersByEndpointId = new Map<string, ParameterObject[]>();\n const usedOperationIds = new Set<string>();\n\n for (const ep of input.endpoints) {\n const method = (ep.identity.method || 'GET').toUpperCase();\n const pathTemplate = ep.identity.pathname || '/';\n const baseOpId = this.options.operationIdGenerator\n ? this.options.operationIdGenerator(method, pathTemplate)\n : generateOperationId(method, pathTemplate);\n\n // Enforce strict OpenAPI requirement: operationId MUST be unique among all operations\n let opId = baseOpId;\n let counter = 1;\n while (usedOperationIds.has(opId)) {\n counter++;\n opId = `${baseOpId}_${counter}`;\n }\n usedOperationIds.add(opId);\n operationIdByEndpointId.set(ep.identity.id, opId);\n\n const params = convertEndpointParameters(ep, {\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n });\n parametersByEndpointId.set(ep.identity.id, params);\n }\n\n // Step 3: Group relationships by source\n const relationshipsBySource = this.options.generateLinks !== false\n ? groupRelationshipsBySource(input.relationships ?? [])\n : new Map<string, ApiRelationship[]>();\n\n // Step 4: Group endpoints by OpenAPI path\n const endpointsByPath = new Map<string, EndpointAggregate[]>();\n for (const ep of input.endpoints) {\n const openApiPath = toOpenApiPath(ep.identity.pathname || '/');\n const list = endpointsByPath.get(openApiPath) ?? [];\n list.push(ep);\n endpointsByPath.set(openApiPath, list);\n }\n\n // Step 5: Build PathsObject\n const paths: PathsObject = {};\n const tagsSet = new Set<string>();\n let totalOperations = 0;\n let totalParameters = 0;\n let totalLinks = 0;\n\n const sortedPaths = Array.from(endpointsByPath.keys()).sort();\n\n for (const pathKey of sortedPaths) {\n const endpoints = endpointsByPath.get(pathKey)!;\n const pathItem: PathItemObject = {};\n\n for (const ep of endpoints) {\n const method = (ep.identity.method || 'GET').toLowerCase();\n const operationId = operationIdByEndpointId.get(ep.identity.id)!;\n const schemaAggregate = schemaMap.get(ep.identity.id);\n\n const tag = deriveResourceTag(ep.identity.pathname || '/');\n tagsSet.add(tag);\n\n const summary = deriveOperationSummary(method, ep.identity.pathname || '/');\n const parameters = parametersByEndpointId.get(ep.identity.id) ?? [];\n totalParameters += parameters.length;\n\n const requestBody = convertRequestBody(schemaAggregate, {\n method,\n openApiVersion: version,\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n refResolver: this.options.extractComponents !== false ? componentRegistry : undefined,\n });\n\n const responses = convertResponses(schemaAggregate, ep, {\n openApiVersion: version,\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n refResolver: this.options.extractComponents !== false ? componentRegistry : undefined,\n });\n\n // Discovered relationships handling\n const unsupportedRelationships: Record<string, unknown>[] = [];\n\n if (this.options.generateLinks !== false) {\n const outgoingRels = relationshipsBySource.get(ep.identity.id) ?? [];\n\n // Find source response schema for link expression verification\n const successDef =\n schemaAggregate?.responses?.[200]?.['application/json'] ??\n schemaAggregate?.responses?.[201]?.['application/json'] ??\n (schemaAggregate?.responses?.[200] ? Object.values(schemaAggregate.responses[200])[0] : undefined);\n const sourceResponseSchema = successDef?.schema;\n\n for (const rel of outgoingRels) {\n const targetOpId = operationIdByEndpointId.get(rel.targetEndpointId);\n const targetParams = parametersByEndpointId.get(rel.targetEndpointId);\n\n const linkResult = convertRelationshipToLink({\n relationship: rel,\n targetOperationId: targetOpId,\n targetParameters: targetParams,\n sourceResponseSchema,\n options: {\n minConfidence: this.options.minRelationshipConfidence,\n includeExtensions: this.options.includeExtensions,\n },\n });\n\n if (linkResult) {\n const successResponse = responses['200'] ?? responses['201'];\n if (successResponse && !('$ref' in successResponse)) {\n successResponse.links = successResponse.links ?? {};\n successResponse.links[linkResult.linkName] = linkResult.link;\n totalLinks++;\n }\n } else {\n // Retain unsupported relationships in extensions rather than discarding\n unsupportedRelationships.push({\n id: rel.id,\n type: rel.type,\n targetEndpointId: rel.targetEndpointId,\n confidence: rel.confidence?.score,\n status: rel.status,\n sourceProperty: rel.sourceProperty,\n targetProperty: rel.targetProperty,\n });\n }\n }\n }\n\n const operation: OperationObject = {\n tags: [tag],\n summary,\n operationId,\n responses,\n };\n\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n\n if (requestBody) {\n operation.requestBody = requestBody;\n }\n\n if (this.options.includeExtensions !== false) {\n operation['x-luxray-endpoint-id'] = ep.identity.id;\n operation['x-luxray-observations'] = ep.observationCount;\n operation['x-luxray-first-observed'] = ep.firstObservedAt;\n operation['x-luxray-last-observed'] = ep.lastObservedAt;\n if (ep.latency?.avgMs !== undefined) {\n operation['x-luxray-latency-avg-ms'] = Math.round(ep.latency.avgMs * 100) / 100;\n }\n if (unsupportedRelationships.length > 0) {\n operation['x-luxray-relationships'] = unsupportedRelationships;\n }\n }\n\n (pathItem as Record<string, unknown>)[method] = operation;\n totalOperations++;\n }\n\n paths[pathKey] = pathItem;\n }\n\n // Step 6: Derive servers if not explicitly provided\n let servers: ServerObject[] | undefined = this.options.servers;\n if (!servers || servers.length === 0) {\n const origins = new Set<string>();\n for (const ep of input.endpoints) {\n if (ep.identity.origin && ep.identity.origin.startsWith('http')) {\n origins.add(ep.identity.origin);\n }\n }\n if (origins.size > 0) {\n servers = Array.from(origins).map((origin) => ({\n url: origin,\n description: 'Inferred API server origin',\n }));\n }\n }\n\n // Step 7: Build document info\n const info: InfoObject = {\n title: this.options.info?.title ?? 'Luxray Discovered API',\n version: this.options.info?.version ?? '1.0.0',\n description:\n this.options.info?.description ??\n 'Automated OpenAPI specification reverse-engineered by Luxray Traffic Intelligence.',\n ...this.options.info,\n };\n\n // Step 8: Build tags\n const tags: TagObject[] = Array.from(tagsSet)\n .sort()\n .map((tag) => ({ name: tag }));\n\n // Step 9: Build components\n let components: ComponentsObject | undefined;\n if (this.options.extractComponents !== false) {\n components = componentRegistry.toComponentsObject();\n }\n\n // Construct final document\n const document: OpenApiDocument = {\n openapi: version,\n info,\n paths,\n };\n\n if (isOpenApi31) {\n document.jsonSchemaDialect = 'https://json-schema.org/draft/2020-12/schema';\n }\n\n if (servers && servers.length > 0) {\n document.servers = servers;\n }\n\n if (tags.length > 0) {\n document.tags = tags;\n }\n\n if (components) {\n document.components = components;\n }\n\n if (this.options.includeExtensions !== false) {\n document['x-luxray-generated-at'] = Date.now();\n document['x-luxray-generator-version'] = '0.1.0';\n }\n\n const duration = Date.now() - startTime;\n this.lastMetrics = {\n totalPaths: Object.keys(paths).length,\n totalOperations,\n totalParameters,\n totalSchemas: schemaMap.size,\n totalComponents: componentRegistry.count,\n totalLinks,\n generationTimeMs: duration,\n };\n\n return document;\n }\n\n /**\n * Generates document serialized as formatted JSON string.\n */\n public generateJson(input: GenerationInput, indent?: number): string {\n const doc = this.generate(input);\n return serializeToJson(doc, indent ?? this.options.indent ?? 2);\n }\n\n /**\n * Generates document serialized as clean YAML string.\n */\n public generateYaml(input: GenerationInput, indent?: number): string {\n const doc = this.generate(input);\n return serializeToYaml(doc, indent ?? this.options.indent ?? 2);\n }\n\n /**\n * Returns generation metrics from the most recent run.\n */\n public getMetrics(): GenerationMetrics | undefined {\n return this.lastMetrics;\n }\n\n /**\n * Inspects endpoints and schemas to register entity schemas in the component registry.\n */\n private preRegisterComponents(\n endpoints: readonly EndpointAggregate[],\n schemaMap: Map<string, EndpointSchemaAggregate>,\n registry: ComponentRegistry,\n ): void {\n for (const ep of endpoints) {\n const schemaAggregate = schemaMap.get(ep.identity.id);\n if (!schemaAggregate) continue;\n\n const path = ep.identity.pathname || '/';\n const method = (ep.identity.method || 'GET').toUpperCase();\n\n // Check responses (especially 200/201)\n const resDefinitions = (schemaAggregate.responses?.[200] ?? schemaAggregate.responses?.[201]) as\n | Record<string, InferredResponseDefinition>\n | undefined;\n if (resDefinitions) {\n for (const def of Object.values(resDefinitions)) {\n if (!def.schema) continue;\n\n if (def.schema.type === 'object') {\n const componentName = deriveEntityComponentName(path, method, false);\n registry.registerComponent(componentName, def.schema as InferredObjectSchema);\n } else if (def.schema.type === 'array') {\n const itemSchema = (def.schema as InferredArraySchema).itemSchema;\n if (itemSchema && itemSchema.type === 'object') {\n const componentName = deriveEntityComponentName(path, method, false);\n registry.registerComponent(componentName, itemSchema as InferredObjectSchema);\n }\n }\n }\n }\n\n // Check request body for POST/PUT/PATCH\n if (['POST', 'PUT', 'PATCH'].includes(method)) {\n const req = schemaAggregate.request;\n if (req && req.schema && req.schema.type === 'object') {\n const reqName = deriveEntityComponentName(path, method, true);\n registry.registerComponent(reqName, req.schema as InferredObjectSchema);\n }\n }\n }\n }\n}\n","export interface JsonParseResult {\n readonly isValidJson: boolean;\n readonly isEmpty: boolean;\n readonly isNonJsonContentType: boolean;\n readonly isPayloadTooLarge: boolean;\n readonly data?: unknown;\n readonly error?: string;\n readonly rawSnippet?: string;\n}\n\n/**\n * Validates Content-Type headers and safely parses JSON payloads within strict size boundaries.\n */\nexport class ContentDetector {\n /**\n * Checks whether a Content-Type or MIME type header indicates a JSON format.\n */\n public static isJsonMimeType(contentType?: string): boolean {\n if (!contentType) return false;\n const lower = contentType.toLowerCase().split(';')[0]?.trim() ?? '';\n return (\n lower === 'application/json' ||\n lower.endsWith('+json') ||\n lower === 'text/json' ||\n lower === 'text/x-json'\n );\n }\n\n /**\n * Safely attempts to parse raw payload strings with size boundary checks.\n */\n public static parseJson(\n payload?: string | null,\n contentType?: string,\n maxPayloadSizeBytes = 5 * 1024 * 1024 // 5MB\n ): JsonParseResult {\n if (payload === null || payload === undefined || payload.trim() === '') {\n return {\n isValidJson: false,\n isEmpty: true,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n };\n }\n\n // Check payload size boundary\n const byteLength = Buffer.byteLength(payload, 'utf-8');\n if (byteLength > maxPayloadSizeBytes) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: true,\n error: `Payload size (${byteLength} bytes) exceeds limit of ${maxPayloadSizeBytes} bytes`,\n rawSnippet: payload.slice(0, 100),\n };\n }\n\n // If explicit Content-Type is provided and definitely not JSON (e.g. text/html, image/png)\n if (contentType && !this.isJsonMimeType(contentType)) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: true,\n isPayloadTooLarge: false,\n error: `Content-Type '${contentType}' is not a recognized JSON MIME type`,\n rawSnippet: payload.slice(0, 100),\n };\n }\n\n try {\n const parsed = JSON.parse(payload);\n return {\n isValidJson: true,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n data: parsed,\n rawSnippet: payload.slice(0, 100),\n };\n } catch (err) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n error: err instanceof Error ? err.message : String(err),\n rawSnippet: payload.slice(0, 100),\n };\n }\n }\n}\n\n","export interface NormalizedMediaType {\n readonly raw: string;\n readonly canonical: string;\n readonly isJson: boolean;\n readonly isVendorJson: boolean;\n readonly isTextual: boolean;\n readonly charset?: string;\n}\n\n/**\n * Normalizes HTTP Content-Type headers into canonical media types.\n *\n * Rules:\n * 1. Parameters (e.g. charset=utf-8, boundary=...) are stripped for grouping.\n * 2. Missing/empty Content-Type defaults to 'application/octet-stream'.\n * 3. Legacy JSON aliases (text/json, text/x-json) map to canonical 'application/json'.\n * 4. Vendor and profile-specific JSON formats (application/problem+json, application/vnd.api+json)\n * are preserved distinctly to prevent contract cross-contamination.\n * 5. Media types are normalized to lower-case.\n */\nexport class MediaTypeNormalizer {\n public static normalize(contentType?: string | null): string {\n if (!contentType || contentType.trim() === '') {\n return 'application/octet-stream';\n }\n\n const segments = contentType.split(';');\n const primary = segments[0]?.trim().toLowerCase() ?? '';\n\n if (!primary) {\n return 'application/octet-stream';\n }\n\n // Standardize legacy JSON MIME aliases\n if (primary === 'text/json' || primary === 'text/x-json') {\n return 'application/json';\n }\n\n return primary;\n }\n\n /**\n * Checks whether a media type represents standard JSON or vendor-specific structured JSON (+json).\n */\n public static isJson(contentType?: string | null): boolean {\n const canonical = this.normalize(contentType);\n return canonical === 'application/json' || canonical.endsWith('+json');\n }\n\n /**\n * Checks whether a media type is a specialized vendor-specific JSON variant.\n */\n public static isVendorJson(contentType?: string | null): boolean {\n const canonical = this.normalize(contentType);\n return canonical !== 'application/json' && canonical.endsWith('+json');\n }\n\n /**\n * Extracts charset parameter if specified in raw header.\n */\n public static extractCharset(contentType?: string | null): string | undefined {\n if (!contentType) return undefined;\n const match = /charset\\s*=\\s*[\"']?([a-zA-Z0-9_-]+)[\"']?/i.exec(contentType);\n return match ? match[1]?.toLowerCase() : undefined;\n }\n\n /**\n * Returns a structured descriptor of the media type.\n */\n public static parse(contentType?: string | null): NormalizedMediaType {\n const raw = contentType ?? '';\n const canonical = this.normalize(raw);\n const isJson = this.isJson(raw);\n const isVendorJson = this.isVendorJson(raw);\n const isTextual =\n isJson ||\n canonical.startsWith('text/') ||\n canonical === 'application/xml' ||\n canonical.endsWith('+xml');\n const charset = this.extractCharset(raw);\n\n return {\n raw,\n canonical,\n isJson,\n isVendorJson,\n isTextual,\n charset,\n };\n }\n}\n\n","import type { InferredPrimitiveSchema } from '@luxray/shared';\n\nexport interface PrimitiveInferenceResult {\n readonly isPrimitive: boolean;\n readonly type: InferredPrimitiveSchema['type'];\n}\n\n/**\n * Classifies JavaScript scalar values into strict primitive schema types.\n */\nexport class PrimitiveInferencer {\n public static infer(value: unknown): PrimitiveInferenceResult {\n if (value === null) {\n return { isPrimitive: true, type: 'null' };\n }\n\n if (typeof value === 'boolean') {\n return { isPrimitive: true, type: 'boolean' };\n }\n\n if (typeof value === 'string') {\n return { isPrimitive: true, type: 'string' };\n }\n\n if (typeof value === 'number') {\n // Distinguish integer from floating-point\n return {\n isPrimitive: true,\n type: Number.isInteger(value) ? 'integer' : 'number',\n };\n }\n\n return { isPrimitive: false, type: 'any' };\n }\n}\n\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n InferredUnionSchema,\n} from '@luxray/shared';\nimport type { SampleRedactor } from '../redactor/sample-redactor.js';\n\nexport interface MergerOptions {\n maxRetainedSampleValues?: number;\n redactor?: SampleRedactor;\n}\n\n/**\n * Deterministic schema merger combining multiple schema observations.\n * Handles optional fields, nullability, type promotions (integer -> number),\n * empty-array refinement, and union variants without data pollution.\n */\nexport class SchemaMerger {\n private readonly maxSamples: number;\n private readonly redactor?: SampleRedactor;\n\n constructor(options?: MergerOptions) {\n this.maxSamples = options?.maxRetainedSampleValues ?? 5;\n this.redactor = options?.redactor;\n }\n\n /**\n * Merges two InferredSchema trees into a single reconciled InferredSchema.\n */\n public merge(a: InferredSchema, b: InferredSchema): InferredSchema {\n // 0. If either schema is unconstrained 'any', refine to the concrete schema\n if (a.type === 'any' && b.type !== 'any') {\n return {\n ...b,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n if (b.type === 'any' && a.type !== 'any') {\n return {\n ...a,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n if (a.type === 'any' && b.type === 'any') {\n return {\n type: 'any',\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n // 1. If schemas are identical primitives\n if (a.type === b.type && this.isPrimitiveType(a.type)) {\n return this.mergePrimitives(\n a as InferredPrimitiveSchema,\n b as InferredPrimitiveSchema\n );\n }\n\n // 2. Integer and Number promotion: (integer + number -> number)\n if (\n (a.type === 'integer' && b.type === 'number') ||\n (a.type === 'number' && b.type === 'integer')\n ) {\n const samples = this.mergeSamples(\n (a as InferredPrimitiveSchema).sampleValues,\n (b as InferredPrimitiveSchema).sampleValues\n );\n return {\n type: 'number',\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n sampleValues: samples,\n };\n }\n\n // 3. Null handling with non-null types: sets isNullable = true\n if (a.type === 'null' && b.type !== 'null') {\n return { ...b, isNullable: true };\n }\n if (b.type === 'null' && a.type !== 'null') {\n return { ...a, isNullable: true };\n }\n\n // 4. Object + Object merge\n if (a.type === 'object' && b.type === 'object') {\n return this.mergeObjects(a as InferredObjectSchema, b as InferredObjectSchema);\n }\n\n // 5. Array + Array merge\n if (a.type === 'array' && b.type === 'array') {\n return this.mergeArrays(a as InferredArraySchema, b as InferredArraySchema);\n }\n\n // 6. Union handling\n if (a.type === 'union' || b.type === 'union') {\n return this.mergeUnion(a, b);\n }\n\n // 7. Conflicting incompatible types: form a new union\n return {\n type: 'union',\n variants: [a, b],\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergePrimitives(\n a: InferredPrimitiveSchema,\n b: InferredPrimitiveSchema\n ): InferredPrimitiveSchema {\n const samples = this.mergeSamples(a.sampleValues, b.sampleValues);\n return {\n type: a.type,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n sampleValues: samples,\n };\n }\n\n private mergeObjects(\n a: InferredObjectSchema,\n b: InferredObjectSchema\n ): InferredObjectSchema {\n const mergedFields: Record<string, FieldMetadata> = {};\n const allFieldNames = new Set([...Object.keys(a.fields), ...Object.keys(b.fields)]);\n\n for (const name of allFieldNames) {\n const fieldA = a.fields[name];\n const fieldB = b.fields[name];\n\n if (fieldA && fieldB) {\n // Field observed in BOTH objects\n const mergedChildSchema = this.merge(fieldA.schema, fieldB.schema);\n const occurrences = fieldA.occurrences + fieldB.occurrences;\n const totalParent =\n fieldA.totalParentObservations + fieldB.totalParentObservations;\n const isOptional = occurrences < totalParent;\n const isNullable = fieldA.isNullable || fieldB.isNullable;\n const sampleValues = this.mergeSamples(\n fieldA.sampleValues,\n fieldB.sampleValues,\n name\n );\n\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n name,\n schema: mergedChildSchema,\n isOptional,\n isNullable,\n occurrences,\n totalParentObservations: totalParent,\n sampleValues,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n } else if (fieldA) {\n // Field observed ONLY in object A -> missing in B -> marked optional\n const totalParent =\n fieldA.totalParentObservations +\n this.getParentObservationsFromSibling(b.fields);\n\n const occurrences = fieldA.occurrences;\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n ...fieldA,\n isOptional: true,\n totalParentObservations: totalParent,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field missing in sibling observation; observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n } else if (fieldB) {\n // Field observed ONLY in object B -> missing in A -> marked optional\n const totalParent =\n fieldB.totalParentObservations +\n this.getParentObservationsFromSibling(a.fields);\n\n const occurrences = fieldB.occurrences;\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n ...fieldB,\n isOptional: true,\n totalParentObservations: totalParent,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field missing in prior observation; observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n }\n }\n\n return {\n type: 'object',\n fields: mergedFields,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeArrays(\n a: InferredArraySchema,\n b: InferredArraySchema\n ): InferredArraySchema {\n let itemSchema: InferredSchema;\n if (a.itemSchema.type === 'any') {\n itemSchema = b.itemSchema;\n } else if (b.itemSchema.type === 'any') {\n itemSchema = a.itemSchema;\n } else {\n itemSchema = this.merge(a.itemSchema, b.itemSchema);\n }\n\n return {\n type: 'array',\n itemSchema,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeUnion(a: InferredSchema, b: InferredSchema): InferredUnionSchema {\n let existingVariants: InferredSchema[] =\n a.type === 'union' ? [...(a as InferredUnionSchema).variants] : [a];\n\n const toMergeVariants: InferredSchema[] =\n b.type === 'union' ? [...(b as InferredUnionSchema).variants] : [b];\n\n for (const toMerge of toMergeVariants) {\n // If toMerge is uninformative 'any' and we already have concrete variants, do not add 'any'\n if (toMerge.type === 'any' && existingVariants.some((v) => v.type !== 'any')) {\n continue;\n }\n\n // If existingVariants has only 'any' and toMerge is concrete, replace 'any'\n if (\n existingVariants.length === 1 &&\n existingVariants[0]?.type === 'any' &&\n toMerge.type !== 'any'\n ) {\n existingVariants = [toMerge];\n continue;\n }\n\n let mergedIntoExisting = false;\n for (let i = 0; i < existingVariants.length; i++) {\n const variant = existingVariants[i]!;\n if (\n variant.type === toMerge.type ||\n (variant.type === 'integer' && toMerge.type === 'number') ||\n (variant.type === 'number' && toMerge.type === 'integer')\n ) {\n existingVariants[i] = this.merge(variant, toMerge);\n mergedIntoExisting = true;\n break;\n }\n }\n if (!mergedIntoExisting) {\n existingVariants.push(toMerge);\n }\n }\n\n return {\n type: 'union',\n variants: existingVariants,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeSamples(\n a?: readonly unknown[],\n b?: readonly unknown[],\n fieldName?: string\n ): readonly unknown[] {\n const seen = new Set<unknown>();\n const result: unknown[] = [];\n\n const addSamples = (arr?: readonly unknown[]) => {\n if (!arr) return;\n for (const item of arr) {\n if (result.length >= this.maxSamples) return;\n const sanitized = this.redactor\n ? this.redactor.sanitizeSampleValue(fieldName, item)\n : item;\n const serialized =\n typeof sanitized === 'object' ? JSON.stringify(sanitized) : sanitized;\n if (!seen.has(serialized)) {\n seen.add(serialized);\n result.push(sanitized);\n }\n }\n };\n\n addSamples(a);\n addSamples(b);\n\n return result;\n }\n\n private getParentObservationsFromSibling(fields: Record<string, FieldMetadata>): number {\n const values = Object.values(fields);\n if (values.length === 0) return 1;\n let maxParent = 1;\n for (const f of values) {\n if (f.totalParentObservations > maxParent) {\n maxParent = f.totalParentObservations;\n }\n }\n return maxParent;\n }\n\n private isPrimitiveType(type: string): boolean {\n return (\n type === 'string' ||\n type === 'number' ||\n type === 'integer' ||\n type === 'boolean' ||\n type === 'null' ||\n type === 'any'\n );\n }\n}\n","export interface RedactionOptions {\n /**\n * Additional regex patterns or string names indicating sensitive fields.\n */\n readonly sensitiveFieldPatterns?: readonly (RegExp | string)[];\n\n /**\n * Additional regex patterns indicating sensitive string values (e.g. tokens, keys).\n */\n readonly sensitiveValuePatterns?: readonly RegExp[];\n\n /**\n * Placeholder string for redacted values (default: '[REDACTED]').\n */\n readonly redactionMask?: string;\n\n /**\n * Custom hook for redaction decisions.\n */\n readonly customRedactor?: (fieldName: string | undefined, value: unknown) => unknown;\n}\n\nconst DEFAULT_SENSITIVE_FIELD_NAMES: readonly RegExp[] = [\n /password/i,\n /passphrase/i,\n /(?:^|[-_])passwd(?:$|[-_])/i,\n /(?:^|[-_])pwd(?:$|[-_])/i,\n /secret/i,\n /token/i,\n /authorization/i,\n /(?:^|[-_])auth(?:$|[-_])/i,\n /bearer/i,\n /api[-_]?key/i,\n /cookie/i,\n /set[-_]?cookie/i,\n /session/i,\n /session[-_]?id/i,\n /jwt/i,\n /private[-_]?key/i,\n /(?:^|[-_])ssn(?:$|[-_])/i,\n /social[-_]?sec(urity)?/i,\n /credit[-_]?card/i,\n /card[-_]?(?:num(?:ber)?|no)/i,\n /cvv/i,\n /cvc/i,\n /(?:^|[-_])pin(?:$|[-_])/i,\n /access[-_]?key/i,\n /client[-_]?secret/i,\n];\n\nconst DEFAULT_SENSITIVE_VALUE_PATTERNS: readonly RegExp[] = [\n // JWT tokens: 3 base64 segments\n /^ey[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}$/,\n // Bearer authentication tokens\n /^Bearer\\s+[A-Za-z0-9\\-._~+/]+=*$/i,\n // Basic authentication credentials\n /^Basic\\s+[A-Za-z0-9+/=]{8,}$/i,\n // Stripe API keys (sk_live_..., pk_test_...)\n /^(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}$/,\n // GitHub access tokens (ghp_..., gho_..., etc.)\n /^gh[pousr]_[0-9a-zA-Z]{36,}$/,\n // AWS Access Key ID\n /^(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}$/,\n // Private key blocks\n /-----BEGIN\\s+(?:RSA\\s+)?PRIVATE\\s+KEY-----/i,\n // Credit card number pattern (13-19 digits with optional hyphens/spaces)\n /^(?:\\d{4}[-\\s]?){3}\\d{1,4}$/,\n];\n\n/**\n * Defensive heuristic credential and PII redaction for sample values and payload snippets.\n *\n * Design constraints:\n * - Operates under a fail-closed policy: unexpected errors result in redaction rather than raw data emission.\n * - Preserves structural AST schema inference (types, nullability, optionality) while masking retained sample values.\n * - Does not claim absolute zero-leak protection against arbitrary custom obfuscation; provides defense-in-depth.\n */\nexport class SampleRedactor {\n private readonly fieldPatterns: readonly RegExp[];\n private readonly valuePatterns: readonly RegExp[];\n private readonly redactionMask: string;\n private readonly customRedactor?: (fieldName: string | undefined, value: unknown) => unknown;\n\n constructor(options?: RedactionOptions) {\n this.redactionMask = options?.redactionMask ?? '[REDACTED]';\n this.customRedactor = options?.customRedactor;\n\n const extraFields = (options?.sensitiveFieldPatterns ?? []).map((p) =>\n typeof p === 'string' ? new RegExp(p, 'i') : p\n );\n this.fieldPatterns = [...DEFAULT_SENSITIVE_FIELD_NAMES, ...extraFields];\n\n this.valuePatterns = [\n ...DEFAULT_SENSITIVE_VALUE_PATTERNS,\n ...(options?.sensitiveValuePatterns ?? []),\n ];\n }\n\n /**\n * Checks whether a field name denotes sensitive content.\n */\n public isSensitiveFieldName(name?: string): boolean {\n if (!name) return false;\n return this.fieldPatterns.some((regex) => regex.test(name));\n }\n\n /**\n * Checks whether a value matches known credential or token formats.\n */\n public isSensitiveValue(value: unknown): boolean {\n if (typeof value !== 'string') return false;\n const trimmed = value.trim();\n return this.valuePatterns.some((regex) => regex.test(trimmed));\n }\n\n /**\n * Returns a sanitized sample value. If sensitive or on failure, fails closed with redaction mask.\n */\n public sanitizeSampleValue(fieldName: string | undefined, value: unknown): unknown {\n try {\n if (this.customRedactor) {\n const custom = this.customRedactor(fieldName, value);\n if (custom !== value) {\n return custom;\n }\n }\n\n if (this.isSensitiveFieldName(fieldName) || this.isSensitiveValue(value)) {\n return this.redactionMask;\n }\n\n return value;\n } catch {\n // Fail closed on any redaction error\n return this.redactionMask;\n }\n }\n\n /**\n * Redacts sensitive information from raw request/response payloads before storing sample snippets.\n * Fails closed if any parsing or traversal error occurs.\n */\n public sanitizePayloadString(\n rawPayload?: string | null,\n maxSnippetLength = 100\n ): string {\n if (!rawPayload || rawPayload.trim() === '') {\n return '';\n }\n\n try {\n // Attempt JSON parsing and recursive structural redaction\n const parsed = JSON.parse(rawPayload);\n const visited = new Set<unknown>();\n const sanitized = this.redactObjectRecursive(parsed, undefined, visited);\n const stringified = JSON.stringify(sanitized);\n return stringified.length > maxSnippetLength\n ? stringified.slice(0, maxSnippetLength)\n : stringified;\n } catch {\n // Non-JSON or malformed payload: apply regex-based token & credential mask\n try {\n let sanitized = rawPayload\n .replace(/(Bearer\\s+)[A-Za-z0-9\\-._~+/]+=*/gi, `$1${this.redactionMask}`)\n .replace(/(Basic\\s+)[A-Za-z0-9+/=]+/gi, `$1${this.redactionMask}`)\n .replace(\n /([\"']?(?:password|token|secret|apiKey|api_key|access_key)[\"']?\\s*[:=]\\s*[\"']?)[^\"',}\\s]+/gi,\n `$1${this.redactionMask}`\n );\n\n return sanitized.length > maxSnippetLength\n ? sanitized.slice(0, maxSnippetLength)\n : sanitized;\n } catch {\n // Complete fail-closed fallback\n return this.redactionMask;\n }\n }\n }\n\n private redactObjectRecursive(\n val: unknown,\n keyName?: string,\n visited = new Set<unknown>()\n ): unknown {\n if (val === null || val === undefined) return val;\n\n // Check custom redactor\n if (this.customRedactor) {\n try {\n const custom = this.customRedactor(keyName, val);\n if (custom !== val) return custom;\n } catch {\n return this.redactionMask;\n }\n }\n\n // Direct field name or value match\n if (this.isSensitiveFieldName(keyName) || this.isSensitiveValue(val)) {\n return this.redactionMask;\n }\n\n // Circular reference protection\n if (typeof val === 'object') {\n if (visited.has(val)) {\n return '[CIRCULAR]';\n }\n visited.add(val);\n }\n\n if (Array.isArray(val)) {\n return val.map((item) => this.redactObjectRecursive(item, keyName, visited));\n }\n\n if (typeof val === 'object') {\n const obj = val as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n result[k] = this.redactObjectRecursive(v, k, visited);\n }\n return result;\n }\n\n return val;\n }\n}\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n} from '@luxray/shared';\nimport { PrimitiveInferencer } from './primitive-inferencer.js';\nimport { SchemaMerger } from '../merger/schema-merger.js';\nimport { SampleRedactor, type RedactionOptions } from '../redactor/sample-redactor.js';\n\nexport interface ValueInferencerOptions {\n maxNestingDepth?: number;\n maxArraySamples?: number;\n maxRetainedSampleValues?: number;\n redaction?: RedactionOptions;\n redactor?: SampleRedactor;\n}\n\n/**\n * Infers an InferredSchema Intermediate Representation (IR) from any valid JavaScript value.\n * Protects against deep recursion, unbounded arrays, circular structures, and credential leakage.\n */\nexport class ValueInferencer {\n private readonly maxDepth: number;\n private readonly maxArraySamples: number;\n private readonly maxSamples: number;\n private readonly merger: SchemaMerger;\n private readonly redactor: SampleRedactor;\n\n constructor(options?: ValueInferencerOptions) {\n this.maxDepth = options?.maxNestingDepth ?? 20;\n this.maxArraySamples = options?.maxArraySamples ?? 50;\n this.maxSamples = options?.maxRetainedSampleValues ?? 5;\n this.redactor = options?.redactor ?? new SampleRedactor(options?.redaction);\n this.merger = new SchemaMerger({\n maxRetainedSampleValues: this.maxSamples,\n redactor: this.redactor,\n });\n }\n\n /**\n * Recursively infers the schema of any JavaScript value.\n */\n public infer(value: unknown, depth = 0, fieldName?: string): InferredSchema {\n // 1. Guard against unbounded recursion\n if (depth >= this.maxDepth) {\n return { type: 'any' };\n }\n\n // 2. Primitive inference\n const prim = PrimitiveInferencer.infer(value);\n if (prim.isPrimitive) {\n if (prim.type === 'null') {\n return { type: 'null', isNullable: true, sampleValues: [null] };\n }\n\n const sanitizedSample = this.redactor.sanitizeSampleValue(fieldName, value);\n return {\n type: prim.type,\n sampleValues: [sanitizedSample],\n } as InferredPrimitiveSchema;\n }\n\n // 3. Array inference\n if (Array.isArray(value)) {\n return this.inferArray(value, depth, fieldName);\n }\n\n // 4. Object inference\n if (typeof value === 'object' && value !== null) {\n return this.inferObject(value as Record<string, unknown>, depth);\n }\n\n return { type: 'any' };\n }\n\n private inferArray(arr: unknown[], depth: number, fieldName?: string): InferredArraySchema {\n if (arr.length === 0) {\n return {\n type: 'array',\n itemSchema: { type: 'any' },\n };\n }\n\n // Bound array sample size to avoid O(N) traversal on huge lists\n const sampleLimit = Math.min(arr.length, this.maxArraySamples);\n let unifiedItemSchema: InferredSchema = this.infer(arr[0], depth + 1, fieldName);\n\n for (let i = 1; i < sampleLimit; i++) {\n const currentItemSchema = this.infer(arr[i], depth + 1, fieldName);\n unifiedItemSchema = this.merger.merge(unifiedItemSchema, currentItemSchema);\n }\n\n return {\n type: 'array',\n itemSchema: unifiedItemSchema,\n };\n }\n\n private inferObject(\n obj: Record<string, unknown>,\n depth: number\n ): InferredObjectSchema {\n const fields: Record<string, FieldMetadata> = {};\n\n for (const [key, val] of Object.entries(obj)) {\n const childSchema = this.infer(val, depth + 1, key);\n const isNull = val === null;\n\n fields[key] = {\n name: key,\n schema: childSchema,\n isOptional: false,\n isNullable: isNull || Boolean(childSchema.isNullable),\n occurrences: 1,\n totalParentObservations: 1,\n sampleValues: this.extractSampleValue(val, key),\n confidence: {\n score: 0.7,\n level: 'medium',\n volumeFactor: 0.1,\n parsingValidityRatio: 1.0,\n structuralStabilityRatio: 1.0,\n rationale: ['Field observed in 1 of 1 parent object(s) (100% presence).'],\n },\n };\n }\n\n return {\n type: 'object',\n fields,\n };\n }\n\n private extractSampleValue(val: unknown, fieldName?: string): readonly unknown[] {\n if (val === null || val === undefined) return [null];\n\n const sanitized = this.redactor.sanitizeSampleValue(fieldName, val);\n if (sanitized !== val) {\n return [sanitized];\n }\n\n if (typeof val === 'object') {\n const snippet = JSON.stringify(val);\n return [snippet.length > 80 ? snippet.slice(0, 80) + '...' : snippet];\n }\n return [val];\n }\n}\n","import type {\n InferredArraySchema,\n InferredObjectSchema,\n InferredSchema,\n InferredUnionSchema,\n SchemaConfidence,\n} from '@luxray/shared';\n\nexport interface ConfidenceInput {\n readonly totalObservations: number;\n readonly validJsonObservations: number;\n readonly emptyBodyObservations: number;\n readonly nonJsonObservations: number;\n readonly truncatedObservations?: number;\n readonly schema?: InferredSchema;\n readonly hasInferredItemSchema?: boolean;\n}\n\n/**\n * Calculates deterministic evidentiary confidence ratings separating parsing validity from structural stability.\n *\n * Mathematical Model:\n * 1. Volume Factor (S in [0, 1]):\n * S = min(1.0, N_valid / 10). Reaches saturation at 10 or more valid observations.\n * 2. Parsing Validity Ratio (V in [0, 1]):\n * V = N_valid / N_total. Measures the proportion of successfully parsed JSON observations vs noise/truncation.\n * 3. Structural Stability Ratio (H in [0.1, 1.0]):\n * Measures contract convergence and absence of conflicting polymorphic variants.\n * - Single type / uniform object: H = 1.0 (or 0.5 + 0.5 * requiredFieldRatio)\n * - Union with K variants: H = max(0.2, 1.0 - (K - 1) * 0.25)\n * - Unconstrained any: H = 0.1\n * 4. Composite Score:\n * Score = round(0.40 * S + 0.30 * V + 0.30 * H, 2)\n *\n * Tier Boundaries:\n * - 'high': Score >= 0.80 AND N_valid >= 10 AND V >= 0.85 AND H >= 0.70.\n * (Heterogeneous schemas with H < 0.70 are strictly capped at 'medium' or 'low').\n * - 'medium': Score >= 0.45 AND N_valid >= 3.\n * - 'low': Score < 0.45 OR N_valid < 3.\n */\nexport class ConfidenceEvaluator {\n public static evaluate(input: ConfidenceInput): SchemaConfidence {\n const {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations = 0,\n schema,\n } = input;\n\n if (totalObservations === 0) {\n return {\n score: 0.0,\n level: 'low',\n volumeFactor: 0.0,\n parsingValidityRatio: 0.0,\n structuralStabilityRatio: 0.0,\n rationale: ['No observations recorded yet.'],\n };\n }\n\n const rationale: string[] = [];\n\n // Special clean empty responses (e.g. HTTP 204 No Content)\n if (validJsonObservations === 0 && emptyBodyObservations > 0) {\n const emptyRatio = emptyBodyObservations / totalObservations;\n const sEmpty = Math.min(1.0, emptyBodyObservations / 5);\n const score = Math.round(sEmpty * emptyRatio * 100) / 100;\n const level =\n score >= 0.75 && emptyBodyObservations >= 5 && emptyRatio >= 0.85\n ? 'high'\n : score >= 0.35 && emptyBodyObservations >= 2\n ? 'medium'\n : 'low';\n\n rationale.push(\n `Consistently empty body: ${emptyBodyObservations} empty observation(s) across ${totalObservations} transaction(s).`\n );\n if (emptyRatio === 1.0) {\n rationale.push('Payload is 100% consistently empty.');\n }\n return {\n score,\n level,\n volumeFactor: Math.round(sEmpty * 100) / 100,\n parsingValidityRatio: Math.round(emptyRatio * 100) / 100,\n structuralStabilityRatio: 1.0,\n rationale,\n };\n }\n\n const volumeFactor = Math.min(1.0, validJsonObservations / 10);\n const parsingValidityRatio = validJsonObservations / totalObservations;\n const structuralStabilityRatio = this.calculateStructuralStability(schema);\n\n // Multiplicative evidentiary model: volumeFactor gates structural & parsing validity\n const score =\n Math.round(\n volumeFactor *\n (0.50 * parsingValidityRatio + 0.50 * structuralStabilityRatio) *\n 100\n ) / 100;\n\n rationale.push(\n `Observation volume: ${validJsonObservations} valid payload(s) across ${totalObservations} transaction(s) (volume factor: ${volumeFactor.toFixed(2)}).`\n );\n\n if (validJsonObservations >= 10) {\n rationale.push('Sufficient sample size (>= 10) observed.');\n } else if (validJsonObservations < 3) {\n rationale.push('Low sample size (< 3); schema optionality and variants may be incomplete.');\n }\n\n if (nonJsonObservations > 0 || truncatedObservations > 0) {\n const noise = nonJsonObservations + truncatedObservations;\n const noisePercent = Math.round((noise / totalObservations) * 100);\n rationale.push(\n `${noise} unparseable, truncated, or non-JSON observation(s) recorded (${noisePercent}% noise ratio).`\n );\n }\n\n if (structuralStabilityRatio >= 0.85) {\n rationale.push('High structural stability: schema demonstrates consistent field and type structures.');\n } else if (structuralStabilityRatio < 0.6) {\n rationale.push(\n `Low structural stability (${structuralStabilityRatio.toFixed(2)}): schema contains polymorphic variants or high field variance.`\n );\n }\n\n // Determine Tier with strict evidentiary constraints\n let level: 'low' | 'medium' | 'high';\n if (\n score >= 0.75 &&\n validJsonObservations >= 10 &&\n parsingValidityRatio >= 0.85 &&\n structuralStabilityRatio >= 0.7\n ) {\n level = 'high';\n } else if (score >= 0.35 && validJsonObservations >= 3) {\n level = 'medium';\n } else {\n level = 'low';\n }\n\n return {\n score,\n level,\n volumeFactor: Math.round(volumeFactor * 100) / 100,\n parsingValidityRatio: Math.round(parsingValidityRatio * 100) / 100,\n structuralStabilityRatio: Math.round(structuralStabilityRatio * 100) / 100,\n rationale,\n };\n }\n\n private static calculateStructuralStability(schema?: InferredSchema): number {\n if (!schema) return 0.5;\n\n switch (schema.type) {\n case 'any':\n return 0.1;\n\n case 'union': {\n const variants = (schema as InferredUnionSchema).variants;\n const count = variants.length;\n if (count <= 1) return 1.0;\n // Each additional conflicting variant penalizes stability by 0.25\n return Math.max(0.2, 1.0 - (count - 1) * 0.25);\n }\n\n case 'object': {\n const fields = Object.values((schema as InferredObjectSchema).fields);\n if (fields.length === 0) return 0.8;\n const requiredCount = fields.filter((f) => !f.isOptional).length;\n const requiredRatio = requiredCount / fields.length;\n return Math.round((0.5 + 0.5 * requiredRatio) * 100) / 100;\n }\n\n case 'array': {\n const itemSchema = (schema as InferredArraySchema).itemSchema;\n if (itemSchema.type === 'any') return 0.5;\n if (itemSchema.type === 'union') {\n return this.calculateStructuralStability(itemSchema);\n }\n return 1.0;\n }\n\n case 'string':\n case 'number':\n case 'integer':\n case 'boolean':\n case 'null':\n return 1.0;\n\n default:\n return 0.5;\n }\n }\n}\n","import type {\n CapturedTransaction,\n EndpointSchemaAggregate,\n InferredRequestDefinition,\n InferredResponseDefinition,\n InferredSchema,\n} from '@luxray/shared';\nimport type { EndpointNormalizer } from '@luxray/normalization';\nimport { ContentDetector } from '../parser/content-detector.js';\nimport { MediaTypeNormalizer } from '../parser/media-type-normalizer.js';\nimport { ValueInferencer } from '../inferencer/value-inferencer.js';\nimport { SchemaMerger } from '../merger/schema-merger.js';\nimport { SampleRedactor, type RedactionOptions } from '../redactor/sample-redactor.js';\nimport { ConfidenceEvaluator } from '../provenance/confidence-evaluator.js';\n\nexport interface SchemaInferenceEngineOptions {\n normalizer?: EndpointNormalizer;\n maxPayloadSizeBytes?: number;\n maxNestingDepth?: number;\n maxArraySamples?: number;\n maxRetainedSampleValues?: number;\n maxRetainedTransactions?: number;\n redaction?: RedactionOptions;\n redactor?: SampleRedactor;\n}\n\nexport function normalizeMediaType(contentType?: string | null): string {\n return MediaTypeNormalizer.normalize(contentType);\n}\n\nfunction getHeader(headers: Record<string, string> | undefined, name: string): string | undefined {\n if (!headers) return undefined;\n const target = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === target) {\n return v;\n }\n }\n return undefined;\n}\n\n/**\n * Hardened engine that ingests captured HTTP transactions, infers request and response schemas,\n * groups responses by status code and normalized media type, redacts credentials, handles body truncation,\n * and derives evidentiary confidence ratings.\n */\nexport class SchemaInferenceEngine {\n private readonly normalizer?: EndpointNormalizer;\n private readonly maxPayloadSizeBytes: number;\n private readonly maxRetainedSamples: number;\n private readonly maxRetainedTransactions: number;\n private readonly redactor: SampleRedactor;\n private readonly inferencer: ValueInferencer;\n private readonly merger: SchemaMerger;\n private readonly aggregates = new Map<string, EndpointSchemaAggregate>();\n\n constructor(options?: SchemaInferenceEngineOptions) {\n this.normalizer = options?.normalizer;\n this.maxPayloadSizeBytes = options?.maxPayloadSizeBytes ?? 5 * 1024 * 1024;\n this.maxRetainedSamples = options?.maxRetainedSampleValues ?? 5;\n this.maxRetainedTransactions = options?.maxRetainedTransactions ?? 100;\n this.redactor = options?.redactor ?? new SampleRedactor(options?.redaction);\n this.inferencer = new ValueInferencer({\n maxNestingDepth: options?.maxNestingDepth,\n maxArraySamples: options?.maxArraySamples,\n maxRetainedSampleValues: options?.maxRetainedSampleValues,\n redactor: this.redactor,\n });\n this.merger = new SchemaMerger({\n maxRetainedSampleValues: options?.maxRetainedSampleValues,\n redactor: this.redactor,\n });\n }\n\n /**\n * Infers schema IR from any in-memory JavaScript data value.\n */\n public inferFromValue(value: unknown, fieldName?: string): InferredSchema {\n return this.inferencer.infer(value, 0, fieldName);\n }\n\n /**\n * Parses and infers schema IR from raw JSON string content.\n */\n public inferFromJson(rawJson: string, contentType?: string): InferredSchema | null {\n const parseResult = ContentDetector.parseJson(\n rawJson,\n contentType,\n this.maxPayloadSizeBytes\n );\n if (!parseResult.isValidJson) {\n return null;\n }\n return this.inferencer.infer(parseResult.data);\n }\n\n /**\n * Reconciles two schemas into a unified, backward-compatible schema.\n */\n public mergeSchemas(a: InferredSchema, b: InferredSchema): InferredSchema {\n return this.merger.merge(a, b);\n }\n\n /**\n * Ingests a CapturedTransaction and updates request/response schemas for the corresponding endpoint.\n */\n public ingestTransaction(\n transaction: CapturedTransaction,\n explicitEndpointId?: string\n ): EndpointSchemaAggregate {\n const endpointId = this.resolveEndpointId(transaction, explicitEndpointId);\n const txTime = transaction.timing?.startTime ?? Date.now();\n\n let aggregate = this.aggregates.get(endpointId);\n if (!aggregate) {\n aggregate = {\n endpointId,\n requests: {},\n responses: {},\n lastUpdatedAt: txTime,\n };\n }\n\n // 1. Process Request Payload\n const updatedRequests = { ...(aggregate.requests ?? {}) };\n const rawReqBody = transaction.request.postData;\n const rawReqContentType =\n getHeader(transaction.request.headers, 'content-type') ?? 'application/json';\n const reqMediaType = MediaTypeNormalizer.normalize(rawReqContentType);\n\n const existingReq = updatedRequests[reqMediaType] ?? aggregate.request;\n const updatedReq = this.processRequest(\n transaction,\n existingReq,\n rawReqContentType,\n reqMediaType,\n txTime\n );\n\n if (updatedReq) {\n updatedRequests[reqMediaType] = updatedReq;\n }\n\n // Primary request: prefer application/json if present, otherwise updatedReq\n const primaryRequest =\n updatedRequests['application/json'] ??\n updatedReq ??\n aggregate.request;\n\n // 2. Process Response Payload\n // Deep clone response structure: Record<number, Record<string, InferredResponseDefinition>>\n const updatedResponses: Record<number, Record<string, InferredResponseDefinition>> = {};\n for (const [codeStr, mediaMap] of Object.entries(aggregate.responses)) {\n updatedResponses[Number(codeStr)] = { ...mediaMap };\n }\n\n if (transaction.response) {\n const statusCode = transaction.response.status;\n const rawRespContentType =\n transaction.response.mimeType ??\n getHeader(transaction.response.headers, 'content-type') ??\n 'application/json';\n const respMediaType = MediaTypeNormalizer.normalize(rawRespContentType);\n\n if (!updatedResponses[statusCode]) {\n updatedResponses[statusCode] = {};\n }\n\n const existingResponse = updatedResponses[statusCode]![respMediaType];\n const updatedResp = this.processResponse(\n transaction,\n existingResponse,\n rawRespContentType,\n respMediaType,\n txTime\n );\n\n if (updatedResp) {\n updatedResponses[statusCode]![respMediaType] = updatedResp;\n }\n }\n\n const updatedAggregate: EndpointSchemaAggregate = {\n endpointId,\n request: primaryRequest,\n requests: updatedRequests,\n responses: updatedResponses,\n lastUpdatedAt: Math.max(aggregate.lastUpdatedAt, txTime),\n };\n\n this.aggregates.set(endpointId, updatedAggregate);\n return updatedAggregate;\n }\n\n /**\n * Retrieves an endpoint schema aggregate by ID.\n */\n public getAggregate(endpointId: string): EndpointSchemaAggregate | undefined {\n return this.aggregates.get(endpointId);\n }\n\n /**\n * Convenience helper to retrieve a response definition by status code and optional media type.\n * If mediaType is omitted, returns 'application/json' if present, or the first available representation.\n */\n public getResponse(\n endpointId: string,\n statusCode: number,\n contentType?: string\n ): InferredResponseDefinition | undefined {\n const agg = this.getAggregate(endpointId);\n if (!agg) return undefined;\n const statusMap = agg.responses[statusCode];\n if (!statusMap) return undefined;\n\n if (contentType) {\n const norm = MediaTypeNormalizer.normalize(contentType);\n return statusMap[norm];\n }\n\n return statusMap['application/json'] ?? Object.values(statusMap)[0];\n }\n\n /**\n * Returns all stored endpoint schema aggregates.\n */\n public getAllAggregates(): readonly EndpointSchemaAggregate[] {\n return Array.from(this.aggregates.values());\n }\n\n /**\n * Clears all in-memory aggregates.\n */\n public clear(): void {\n this.aggregates.clear();\n }\n\n private resolveEndpointId(\n transaction: CapturedTransaction,\n explicitEndpointId?: string\n ): string {\n if (explicitEndpointId) {\n return explicitEndpointId;\n }\n\n if (this.normalizer) {\n return this.normalizer.normalize(\n transaction.request.url,\n transaction.request.method\n ).identity.id;\n }\n\n try {\n const parsed = new URL(transaction.request.url);\n return `${transaction.request.method.toUpperCase()} ${parsed.pathname}`;\n } catch {\n // Strip query parameters to avoid retaining query credentials\n const pathOnly = transaction.request.url.split('?')[0] ?? transaction.request.url;\n return `${transaction.request.method.toUpperCase()} ${pathOnly}`;\n }\n }\n\n private processRequest(\n transaction: CapturedTransaction,\n existing: InferredRequestDefinition | undefined,\n contentType: string,\n mediaType: string,\n txTime: number\n ): InferredRequestDefinition | undefined {\n const rawBody = transaction.request.postData;\n const txId = transaction.id;\n\n if (rawBody === undefined || rawBody === null || rawBody.trim() === '') {\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const emptyBodyObservations = existing.provenance.emptyBodyObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n emptyBodyObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n return undefined;\n }\n\n const parseResult = ContentDetector.parseJson(\n rawBody,\n contentType,\n this.maxPayloadSizeBytes\n );\n\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n\n if (parseResult.isValidJson) {\n const inferred = this.inferencer.infer(parseResult.data);\n\n if (existing) {\n const mergedSchema = this.merger.merge(existing.schema, inferred);\n const samplePayloads = existing.provenance.samplePayloads.includes(sanitizedSnippet)\n ? existing.provenance.samplePayloads\n : [...existing.provenance.samplePayloads, sanitizedSnippet].slice(-this.maxRetainedSamples);\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n\n const totalObservations = existing.provenance.totalObservations + 1;\n const validJsonObservations = existing.provenance.validJsonObservations + 1;\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: mergedSchema,\n });\n\n return {\n contentType: existing.contentType || contentType,\n mediaType: existing.mediaType || mediaType,\n schema: mergedSchema,\n provenance: {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n firstObservedAt: Math.min(existing.provenance.firstObservedAt, txTime),\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n transactionIds,\n samplePayloads,\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n schema: inferred,\n });\n\n return {\n contentType,\n mediaType,\n schema: inferred,\n provenance: {\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n // Invalid JSON, payload too large, or non-JSON content type\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n private processResponse(\n transaction: CapturedTransaction,\n existing: InferredResponseDefinition | undefined,\n contentType: string,\n mediaType: string,\n txTime: number\n ): InferredResponseDefinition | undefined {\n if (!transaction.response) return undefined;\n\n const statusCode = transaction.response.status;\n const rawBody = transaction.response.body;\n const isTruncated = Boolean(transaction.response.bodyTruncated);\n const txId = transaction.id;\n\n // 1. Guard against truncated bodies: Never infer partial bodies as complete schemas\n if (isTruncated) {\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const truncatedObservations = (existing.provenance.truncatedObservations ?? 0) + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n truncatedObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n truncatedObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n truncatedObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: sanitizedSnippet ? [sanitizedSnippet] : [],\n confidence,\n },\n };\n }\n\n // 2. Empty response body (e.g. 204 No Content, 304 Not Modified)\n if (rawBody === undefined || rawBody === null || rawBody.trim() === '') {\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const emptyBodyObservations = existing.provenance.emptyBodyObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n emptyBodyObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 1,\n nonJsonObservations: 0,\n schema: { type: 'null', isNullable: true },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'null', isNullable: true },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 1,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [],\n confidence,\n },\n };\n }\n\n // 3. Normal Non-Empty Response Body\n const parseResult = ContentDetector.parseJson(\n rawBody,\n contentType,\n this.maxPayloadSizeBytes\n );\n\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n\n if (parseResult.isValidJson) {\n const inferred = this.inferencer.infer(parseResult.data);\n\n if (existing) {\n const mergedSchema = this.merger.merge(existing.schema, inferred);\n const samplePayloads = existing.provenance.samplePayloads.includes(sanitizedSnippet)\n ? existing.provenance.samplePayloads\n : [...existing.provenance.samplePayloads, sanitizedSnippet].slice(-this.maxRetainedSamples);\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n\n const totalObservations = existing.provenance.totalObservations + 1;\n const validJsonObservations = existing.provenance.validJsonObservations + 1;\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: mergedSchema,\n });\n\n return {\n statusCode,\n contentType: existing.contentType || contentType,\n mediaType: existing.mediaType || mediaType,\n schema: mergedSchema,\n provenance: {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n firstObservedAt: Math.min(existing.provenance.firstObservedAt, txTime),\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n transactionIds,\n samplePayloads,\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n schema: inferred,\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: inferred,\n provenance: {\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n // 4. Invalid JSON, payload too large, or non-JSON content type (e.g. text/html)\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n private appendTransactionId(list: readonly string[], newId: string): readonly string[] {\n if (list.includes(newId)) return list;\n const updated = [...list, newId];\n if (updated.length > this.maxRetainedTransactions) {\n return updated.slice(-this.maxRetainedTransactions);\n }\n return updated;\n }\n}\n","import type {\n AgentArchitecture,\n AgentPlatform,\n ExplorationJobType,\n ExplorationTask,\n ExplorationTaskScope,\n LoginResponse,\n RegisterAgentResponse,\n} from '@luxray/shared';\n\n/**\n * Minimal HTTP client for the Luxray API.\n *\n * Kept separate from the CLI entry point so the authentication and\n * registration flows can be tested without spawning a process or a server.\n * `fetch` is injected for exactly that reason.\n */\n\nexport interface HttpResponseLike {\n readonly ok: boolean;\n readonly status: number;\n text(): Promise<string>;\n json(): Promise<unknown>;\n}\n\nexport interface RequestOptionsLike {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n}\n\nexport type FetchLike = (url: string, init: RequestOptionsLike) => Promise<HttpResponseLike>;\n\nexport class LuxrayApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = 'LuxrayApiError';\n }\n}\n\nexport interface RegisterAgentPayload {\n readonly name: string;\n readonly platform: AgentPlatform | string;\n readonly arch: AgentArchitecture | string;\n readonly version: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nfunction normalizeBaseUrl(apiUrl: string): string {\n return apiUrl.replace(/\\/+$/, '');\n}\n\nasync function postJson<T>(\n fetchImpl: FetchLike,\n url: string,\n body: unknown,\n accessToken?: string,\n): Promise<T> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (accessToken) {\n headers['Authorization'] = `Bearer ${accessToken}`;\n }\n\n let response: HttpResponseLike;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new LuxrayApiError(0, `Could not reach ${url}: ${(err as Error).message}`);\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = (await response.text()).trim();\n } catch {\n // A failure to read the error body must not hide the status code.\n }\n throw new LuxrayApiError(\n response.status,\n `HTTP ${response.status}${detail ? `: ${detail}` : ''}`,\n );\n }\n\n return (await response.json()) as T;\n}\n\n/**\n * Exchanges user credentials for a short-lived access token.\n * This is the only way the CLI obtains authority to act on a workspace.\n */\nexport function login(\n fetchImpl: FetchLike,\n apiUrl: string,\n email: string,\n password: string,\n): Promise<LoginResponse> {\n return postJson<LoginResponse>(fetchImpl, `${normalizeBaseUrl(apiUrl)}/v1/auth/login`, {\n email,\n password,\n });\n}\n\n/**\n * Registers a local agent. The workspace is part of the URL and is authorized\n * by the bearer token; it is deliberately NOT sent in the body (the API\n * rejects unknown body properties).\n */\nexport function registerAgent(\n fetchImpl: FetchLike,\n apiUrl: string,\n workspaceId: string,\n accessToken: string,\n payload: RegisterAgentPayload,\n): Promise<RegisterAgentResponse> {\n return postJson<RegisterAgentResponse>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/v1/workspaces/${encodeURIComponent(workspaceId)}/agents/register`,\n payload,\n accessToken,\n );\n}\n\nexport interface CreateAgentTaskPayload {\n readonly startUrl: string;\n readonly jobType?: ExplorationJobType;\n readonly name?: string;\n readonly scope?: ExplorationTaskScope;\n readonly maxAttempts?: number;\n}\n\n/**\n * Asks the control plane to run a URL the operator typed in the terminal.\n *\n * Authenticated with the agent token rather than a user session: the machine\n * issuing the command may not have one, and the task it creates is leased to\n * that same agent in the same request.\n */\nexport function createAgentExplorationTask(\n fetchImpl: FetchLike,\n apiUrl: string,\n agentToken: string,\n payload: CreateAgentTaskPayload,\n): Promise<{ task: ExplorationTask }> {\n return postJson<{ task: ExplorationTask }>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/v1/agent/tasks/explore`,\n payload,\n agentToken,\n );\n}\n"],"mappings":";;;AACA,YAAYA,SAAQ;AACpB,YAAY,cAAc;AAC1B,SAAS,YAAY,oBAAoB;AACzC,SAAS,SAAAC,cAAa;AACtB,SAAS,WAAAC,UAAS,QAAAC,aAAY;;;ACL9B,YAAY,QAAQ;AACpB,YAAY,UAAU;AACtB,YAAY,QAAQ;AACpB,SAAS,gBAAgB;AACzB,SAAS,iBAAiB;AAE1B,IAAM,gBAAgB,UAAU,QAAQ;AAYjC,IAAM,kBAAN,MAAsB;AAAA,EAC3B,OAAc,iBAAyB;AACrC,UAAM,WAAW,QAAQ,IAAI;AAC7B,QAAI,YAAY,SAAS,KAAK,EAAE,SAAS,GAAG;AAC1C,aAAY,aAAQ,QAAQ;AAAA,IAC9B;AACA,UAAM,UAAa,WAAQ;AAC3B,WAAY,UAAK,SAAS,WAAW,kBAAkB;AAAA,EACzD;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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O,YAAY,IAAI,UAAU,QAAQ,KAAK,MAAM,CAAC,CAAC;AAEvE,UAAQ,SAAS;AAAA,IACf,KAAK;AACH,YAAM,eAAe,KAAK;AAC1B;AAAA,IACF,KAAK;AACH,YAAM,YAAY,KAAK;AACvB;AAAA,IACF,KAAK;AACH,YAAM,YAAY,KAAK;AACvB;AAAA,IACF,KAAK;AACH,YAAM,cAAc,aAAa,KAAK;AACtC;AAAA,IACF,KAAK;AACH,YAAM,aAAa,KAAK;AACxB;AAAA,IACF,KAAK;AACH,YAAM,aAAa,KAAK;AACxB;AAAA,IACF,KAAK;AAAA,IACL,KAAK;AAAA,IACL,KAAK;AACH,gBAAU;AACV;AAAA,IACF;AACE,gBAAU;AAEV,cAAQ,WAAW;AACnB;AAAA,EACJ;AACF;AAEA,KAAK,EAAE,MAAM,CAAC,QAAQ;AACpB,UAAQ,MAAM,sBAAsB,GAAG;AACvC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["os","mkdir","dirname","join","os","resolve","resolve","result","createHash","join","join","mkdir","writeFile","join","result","path","resolve","chromium","result","errorMessage","resolve","clampInt","writeFile","join","hostname","result","isSuccess","statusCodes","primarySingular","URL","UUID_REGEX","URL","UUID_REGEX","result","result","capitalize","document","path","result","result","score","level","confidence","sanitizedSnippet","document","join","writeFile","join","createHash","resolve","path","mkdir","dirname","platform","arch","join","hostname","result"]}
|
|
1
|
+
{"version":3,"sources":["../../src/bin/luxray-agent.ts","../../src/vault/credential-vault.ts","../../src/client/agent-client.ts","../../../streaming/src/config.ts","../../../streaming/src/errors.ts","../../../streaming/src/envelope.ts","../../../streaming/src/kafka.ts","../../../streaming/src/topics.ts","../../src/client/task-stream.ts","../../src/execution/test-job.ts","../../src/execution/task-executor.ts","../../src/execution/exploration-job.ts","../../../../apps/exploration-worker/src/exploration-worker.ts","../../../../apps/exploration-worker/src/artifacts/run-artifacts.ts","../../../../apps/exploration-worker/src/browser/task-browser.ts","../../../../apps/exploration-worker/src/errors.ts","../../../../apps/exploration-worker/src/auth/login.ts","../../../../apps/exploration-worker/src/browser/page-snapshot.ts","../../../../apps/capture-worker/src/index.ts","../../../../apps/capture-worker/src/browser/browser-manager.ts","../../../../apps/capture-worker/src/interceptor/network-interceptor.ts","../../../../apps/capture-worker/src/interceptor/body-resolver.ts","../../../../apps/capture-worker/src/transaction/transaction-correlator.ts","../../../../apps/capture-worker/src/storage/memory-storage.ts","../../../../apps/capture-worker/src/capture-engine.ts","../../../../apps/capture-worker/src/lifecycle/process-lifecycle.ts","../../../../apps/exploration-worker/src/browser/task-capture.ts","../../../../apps/exploration-worker/src/crawl/frontier.ts","../../../../apps/exploration-worker/src/crawl/url-canonicalizer.ts","../../../../apps/exploration-worker/src/crawl/url-policy.ts","../../../../apps/exploration-worker/src/crawl/crawler.ts","../../../../apps/exploration-worker/src/crawl/types.ts","../../src/execution/openapi-spec.ts","../../../normalization/src/url/url-parser.ts","../../../normalization/src/heuristics/patterns.ts","../../../normalization/src/heuristics/static-words.ts","../../../normalization/src/heuristics/segment-classifier.ts","../../../normalization/src/naming/singularize.ts","../../../normalization/src/naming/parameter-namer.ts","../../../normalization/src/query/query-analyzer.ts","../../../normalization/src/engine/endpoint-normalizer.ts","../../../normalization/src/engine/endpoint-aggregator.ts","../../../relationship-discovery/src/resources/resource-identifier.ts","../../../relationship-discovery/src/resources/endpoint-classifier.ts","../../../relationship-discovery/src/identifiers/identifier-extractor.ts","../../../relationship-discovery/src/identifiers/identifier-matcher.ts","../../../relationship-discovery/src/scoring/relationship-scorer.ts","../../../relationship-discovery/src/discovery/relationship-discovery-engine.ts","../../../openapi-generator/src/converters/path-converter.ts","../../../openapi-generator/src/converters/parameter-converter.ts","../../../openapi-generator/src/converters/schema-converter.ts","../../../openapi-generator/src/converters/request-converter.ts","../../../openapi-generator/src/converters/response-converter.ts","../../../openapi-generator/src/converters/link-converter.ts","../../../openapi-generator/src/components/component-registry.ts","../../../openapi-generator/src/serializers/serializer.ts","../../../openapi-generator/src/generator/openapi-generator.ts","../../../schema-inference/src/parser/content-detector.ts","../../../schema-inference/src/parser/media-type-normalizer.ts","../../../schema-inference/src/inferencer/primitive-inferencer.ts","../../../schema-inference/src/merger/schema-merger.ts","../../../schema-inference/src/redactor/sample-redactor.ts","../../../schema-inference/src/inferencer/value-inferencer.ts","../../../schema-inference/src/provenance/confidence-evaluator.ts","../../../schema-inference/src/engine/schema-inference-engine.ts","../../src/client/luxray-api-client.ts"],"sourcesContent":["#!/usr/bin/env node\nimport * as os from 'node:os';\nimport * as readline from 'node:readline/promises';\nimport { existsSync, readFileSync } from 'node:fs';\nimport { mkdir } from 'node:fs/promises';\nimport { dirname, join } from 'node:path';\nimport { CredentialVault, type StoredAgentCredentials } from '../vault/credential-vault.js';\nimport { AgentClient } from '../client/agent-client.js';\nimport { TaskStream } from '../client/task-stream.js';\nimport { streamConfigFromEnv } from '@luxray/streaming';\nimport { TaskExecutor, type JobFinishedInfo } from '../execution/task-executor.js';\nimport {\n createExplorationRunner,\n type ExploreAuthOptions,\n} from '../execution/exploration-job.js';\nimport {\n DEFAULT_EXPLORATION_LIMITS,\n ExplorationWorker,\n type ExplorationOutcome,\n} from '@luxray/exploration-worker';\nimport {\n LuxrayApiError,\n createAgentExplorationTask,\n login,\n registerAgent,\n type FetchLike,\n} from '../client/luxray-api-client.js';\nimport type { LoginResponse, AgentPlatform, AgentArchitecture } from '@luxray/shared';\n\nconst DEFAULT_API_URL = 'http://localhost:4000';\nconst DEFAULT_WS_URL = 'ws://127.0.0.1:4001/v1/agent/socket';\nconst DEFAULT_EXPLORE_MAX_PAGES = DEFAULT_EXPLORATION_LIMITS.maxPages;\nconst DEFAULT_EXPLORE_MAX_DEPTH = DEFAULT_EXPLORATION_LIMITS.maxDepth;\nconst DEFAULT_EXPLORE_JOB_MS = 10 * 60_000;\n/** How long to wait for the server to hand over a task we just created. */\nconst OFFER_WAIT_MS = 90_000;\n\nconst httpFetch: FetchLike = (url, init) => fetch(url, init);\n\nfunction parseArgs(args: string[]): {\n command: string;\n flags: Record<string, string>;\n positionals: string[];\n} {\n const flags: Record<string, string> = {};\n const positionals: string[] = [];\n let command = 'help';\n let commandSet = false;\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (!arg) continue;\n\n if (!arg.startsWith('-')) {\n if (!commandSet) {\n command = arg;\n commandSet = true;\n } else {\n positionals.push(arg);\n }\n continue;\n }\n\n if (arg.startsWith('--')) {\n const key = arg.slice(2);\n const nextArg = args[i + 1];\n if (nextArg && !nextArg.startsWith('-')) {\n flags[key] = nextArg;\n i++;\n } else {\n flags[key] = 'true';\n }\n } else {\n const key = arg.slice(1);\n const nextArg = args[i + 1];\n if (nextArg && !nextArg.startsWith('-')) {\n flags[key] = nextArg;\n i++;\n } else {\n flags[key] = 'true';\n }\n }\n }\n\n return { command, flags, positionals };\n}\n\nfunction parsePositiveIntFlag(raw: string | undefined, fallback: number, max: number): number {\n if (raw === undefined || raw === '') return fallback;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 1 || parsed > max) {\n throw new Error(`Invalid numeric flag value \"${raw}\"; expected an integer between 1 and ${max}.`);\n }\n return parsed;\n}\n\nfunction parseNonNegativeIntFlag(\n raw: string | undefined,\n fallback: number,\n max: number,\n): number {\n if (raw === undefined || raw === '') return fallback;\n const parsed = Number(raw);\n if (!Number.isInteger(parsed) || parsed < 0 || parsed > max) {\n throw new Error(`Invalid numeric flag value \"${raw}\"; expected an integer between 0 and ${max}.`);\n }\n return parsed;\n}\n\nasync function readStdin(): Promise<string> {\n return new Promise((resolve, reject) => {\n let content = '';\n process.stdin.setEncoding('utf8');\n process.stdin.on('data', (chunk) => {\n content += chunk;\n });\n process.stdin.on('end', () => {\n resolve(content.trim());\n });\n process.stdin.on('error', reject);\n });\n}\n\n/**\n * Reads a secret from an interactive terminal with echo disabled.\n * Used for passwords and agent tokens so they never land in scrollback.\n */\nfunction readSecret(promptText: string): Promise<string> {\n return new Promise((resolve, reject) => {\n const stdin = process.stdin;\n const stdout = process.stdout;\n\n if (!stdin.isTTY) {\n reject(new Error('Cannot read a secret without a TTY. Use --password-stdin or --token-stdin.'));\n return;\n }\n\n stdout.write(promptText);\n stdin.setRawMode(true);\n stdin.resume();\n stdin.setEncoding('utf8');\n\n let value = '';\n let settled = false;\n\n const finish = (action: () => void): void => {\n if (settled) return;\n settled = true;\n stdin.setRawMode(false);\n stdin.pause();\n stdin.removeListener('data', onData);\n stdout.write('\\n');\n action();\n };\n\n const onData = (chunk: string): void => {\n for (const ch of chunk) {\n if (ch === '\\r' || ch === '\\n') {\n finish(() => resolve(value));\n return;\n }\n if (ch === '\\u0003') {\n finish(() => reject(new Error('Cancelled.')));\n return;\n }\n if (ch === '\\u007f' || ch === '\\b') {\n value = value.slice(0, -1);\n continue;\n }\n if (ch >= ' ') {\n value += ch;\n }\n }\n };\n\n stdin.on('data', onData);\n });\n}\n\nfunction printHelp(): void {\n console.log(`\nLuxray Local Exploration Agent CLI\n\nUsage:\n luxray-agent <command> [options]\n\nCommands:\n register Authenticate and register this machine with Luxray\n login Store agent credentials issued elsewhere (dashboard or admin)\n explore Crawl a URL now from the terminal (also records it in Luxray)\n start Start the agent worker and connect to Luxray Cloud\n status Inspect local registration and connectivity status\n logout Clear stored credentials from this machine\n help Show this help message\n\nOptions for 'explore':\n <url> Absolute http(s) URL to crawl (required)\n --max-pages <n> Page limit for this run (default ${DEFAULT_EXPLORE_MAX_PAGES}, max 1000)\n --max-depth <n> Link depth limit (default ${DEFAULT_EXPLORE_MAX_DEPTH}, max 10)\n --allowed-domains <a,b> In-scope hostnames (default: the start URL host)\n --include-subdomains Allow subdomains of the allowed domains\n --out <dir> Artifact root (default ~/.luxray/runs)\n --headed Show the browser window\n --include-secrets Keep auth/cookie headers in artifacts (off by default)\n --max-job-ms <ms> Hard run limit (default ${DEFAULT_EXPLORE_JOB_MS})\n --login-url <url> Sign-in page (default: the start URL)\n --username <name> Site username/email (prompts if omitted)\n --password-stdin Read the site password from stdin\n --auth-timeout-ms <ms> Time allowed for the site to accept the form (default 30000)\n --auth-header <h> Send one request header, e.g. \"Authorization: Bearer ...\"\n --auth-headers-json <json> Add several headers as a JSON object (or @path to a file)\n --auth-cookie <c> Install cookies, e.g. \"session=abc; csrftoken=xyz\"\n --auth-state <file> Reuse a saved session instead of signing in\n --save-auth-state <file> Write the session to a file after signing in\n --no-auth Never send auth; crawl public pages and skip sign-in walls\n --api <url> API base URL (defaults to the stored one)\n --name <name> Task name shown in the dashboard\n --config <path> Path to credentials file\n\nOptions for 'register':\n --workspace <id> Target Workspace ID (defaults to your only workspace)\n --name <name> Agent device name (defaults to hostname)\n --url <url> API base URL (defaults to ${DEFAULT_API_URL})\n --ws <url> WebSocket URL (defaults to ${DEFAULT_WS_URL})\n --email <email> Account email (prompts if omitted)\n --password-stdin Read the account password from stdin\n --token <jwt> Use an existing access token instead of logging in\n (exposes the token in shell history; prefer prompting)\n\nOptions for 'login' (agent credentials issued by the dashboard):\n --agent-id <id> Agent ID (prompts if omitted)\n --workspace <id> Workspace ID (prompts if omitted)\n --token-stdin Read the agent token securely from stdin\n (e.g. echo $TOKEN | luxray-agent login --token-stdin)\n --allow-insecure Allow saving credentials if OS ACLs cannot be applied\n\nOptions for 'start':\n --ws <url> Override WebSocket URL\n --config <path> Path to credentials file\n --max-jobs <n> Concurrent jobs this agent runs (default 1, max 16)\n --max-job-ms <ms> Local execution limit per TEST job (default 120000)\n --max-exploration-ms <ms> Local execution limit per exploration (default ${DEFAULT_EXPLORE_JOB_MS})\n --progress-interval-ms <ms> Minimum gap between progress frames (default 1000)\n --lease-renew-ms <ms> Lease renewal interval (default: one third of the lease)\n --out <dir> Artifact root for dashboard-assigned crawls\n --headed Show the browser window while crawling\n --test-steps <n> Steps in the M3 TEST job (default 5)\n --test-step-delay-ms <ms> Delay per TEST step (default 200)\n\nEnvironment Variables:\n LUXRAY_AGENT_TOKEN Agent authentication token\n LUXRAY_AGENT_ID Agent unique ID\n LUXRAY_WORKSPACE_ID Workspace ID\n LUXRAY_WS_URL WebSocket gateway URL\n LUXRAY_API_URL API base URL\n LUXRAY_EMAIL Account email (non-interactive registration)\n LUXRAY_PASSWORD Account password (discouraged; prefer --password-stdin)\n LUXRAY_SITE_USERNAME Target-site username for --login-url crawls\n LUXRAY_SITE_PASSWORD Target-site password (discouraged; prefer --password-stdin)\n LUXRAY_AUTH_HEADER Request header for protected pages (\"Name: value\")\n LUXRAY_AUTH_COOKIE Cookie header for protected pages (\"name=value; ...\")\n LUXRAY_CREDENTIALS_PATH Custom credentials file location\n`);\n}\n\nasync function resolveLoginCredentials(\n flags: Record<string, string>,\n): Promise<{ email: string; password: string }> {\n let email = flags.email || process.env.LUXRAY_EMAIL || '';\n let password = '';\n\n if (flags['password-stdin'] === 'true' || flags['password-stdin'] === '') {\n password = await readStdin();\n } else if (process.env.LUXRAY_PASSWORD) {\n password = process.env.LUXRAY_PASSWORD;\n }\n\n if ((!email || !password) && process.stdin.isTTY) {\n if (!email) {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n email = (await rl.question('Email: ')).trim();\n rl.close();\n }\n if (!password) {\n password = await readSecret('Password: ');\n }\n }\n\n if (!email || !password) {\n throw new Error(\n 'Email and password are required. Use --email/--password-stdin or LUXRAY_EMAIL/LUXRAY_PASSWORD.',\n );\n }\n\n return { email, password };\n}\n\n/** Reads one line from the terminal; used for usernames and confirmations. */\nasync function askLine(question: string): Promise<string> {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n try {\n return (await rl.question(question)).trim();\n } finally {\n rl.close();\n }\n}\n\n/** `--flag value` omits the value, so `--flag` alone must not read as a path. */\nfunction flagValue(flags: Record<string, string>, name: string): string | undefined {\n const value = flags[name];\n if (value === undefined || value === '' || value === 'true') return undefined;\n return value;\n}\n\n/** Parses one `Name: value` header. The value is never echoed back in errors. */\nfunction parseAuthHeader(raw: string): { name: string; value: string } {\n const index = raw.indexOf(':');\n if (index <= 0) {\n throw new Error('Auth headers must look like \"Name: value\".');\n }\n const name = raw.slice(0, index).trim();\n const value = raw.slice(index + 1).trim();\n\n if (!/^[!#$%&'*+\\-.^_`|~0-9A-Za-z]+$/.test(name)) {\n throw new Error(`\"${name}\" is not a valid HTTP header name.`);\n }\n if (value.length === 0) {\n throw new Error(`Header \"${name}\" has an empty value.`);\n }\n return { name, value };\n}\n\n/** Parses a `name=value; name2=value2` cookie header into context cookies. */\nfunction parseAuthCookies(raw: string): Array<{ name: string; value: string }> {\n const cookies: Array<{ name: string; value: string }> = [];\n for (const part of raw.split(';')) {\n const trimmed = part.trim();\n if (trimmed.length === 0) continue;\n const index = trimmed.indexOf('=');\n if (index <= 0) {\n throw new Error('Auth cookies must look like \"name=value; name2=value2\".');\n }\n const name = trimmed.slice(0, index).trim();\n const value = trimmed.slice(index + 1).trim();\n if (name.length === 0 || value.length === 0) {\n throw new Error(`Cookie \"${name || '(unnamed)'}\" has an empty name or value.`);\n }\n cookies.push({ name, value });\n }\n return cookies;\n}\n\n/** `--auth-headers-json` accepts an inline object or `@path` to a JSON file. */\nfunction parseAuthHeadersJson(raw: string): Record<string, string> {\n let text = raw;\n if (raw.startsWith('@')) {\n const path = raw.slice(1);\n if (!existsSync(path)) throw new Error(`Auth headers file not found: ${path}`);\n text = readFileSync(path, 'utf8');\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(text);\n } catch (error) {\n throw new Error(`--auth-headers-json is not valid JSON: ${(error as Error).message}`);\n }\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new Error('--auth-headers-json must be a JSON object of header names to values.');\n }\n\n const headers: Record<string, string> = {};\n for (const [name, value] of Object.entries(parsed as Record<string, unknown>)) {\n if (typeof value !== 'string' || value.trim().length === 0) {\n throw new Error(`Header \"${name}\" must have a non-empty string value.`);\n }\n // Round-trip through the single-header parser so validation is identical.\n const validated = parseAuthHeader(`${name}: ${value}`);\n headers[validated.name] = validated.value;\n }\n return headers;\n}\n\n/**\n * Collects the auth material for a terminal-initiated crawl.\n *\n * Nothing here reaches Postgres: a password is typed into the page, a header or\n * cookie is sent with each request, and every value is scrubbed from the\n * artifacts. The only durable trace is the fact that the run was authenticated.\n *\n * An empty answer means an anonymous crawl: public pages only, with sign-in\n * walls marked instead of recorded as content.\n */\nasync function resolveExploreAuth(\n flags: Record<string, string>,\n startUrl: URL,\n options: { readonly headless: boolean },\n): Promise<ExploreAuthOptions | null> {\n const saveStorageStatePath = flagValue(flags, 'save-auth-state');\n const authStatePath = flagValue(flags, 'auth-state');\n\n if (authStatePath) {\n if (!existsSync(authStatePath)) {\n throw new Error(`--auth-state file not found: ${authStatePath}`);\n }\n return {\n storageStatePath: authStatePath,\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n };\n }\n\n const loginUrlFlag = flagValue(flags, 'login-url');\n let username = flagValue(flags, 'username') ?? process.env.LUXRAY_SITE_USERNAME ?? '';\n const passwordFromStdin = flags['password-stdin'] === 'true' || flags['password-stdin'] === '';\n const noAuth = flags['no-auth'] === 'true';\n const explicitForm = Boolean(loginUrlFlag || username || passwordFromStdin);\n\n const headerFlag = flagValue(flags, 'auth-header') ?? process.env.LUXRAY_AUTH_HEADER;\n const headersJsonFlag = flagValue(flags, 'auth-headers-json');\n const cookieFlag = flagValue(flags, 'auth-cookie') ?? process.env.LUXRAY_AUTH_COOKIE;\n const explicitKeys = Boolean(headerFlag || headersJsonFlag || cookieFlag);\n\n if (explicitForm && explicitKeys) {\n throw new Error(\n 'Pass either a form sign-in (--login-url/--username/--password-stdin) or auth keys ' +\n '(--auth-header/--auth-headers-json/--auth-cookie), not both.',\n );\n }\n\n if (explicitKeys) {\n return buildKeyAuth(headerFlag, headersJsonFlag, cookieFlag, saveStorageStatePath);\n }\n\n if (!explicitForm) {\n if (noAuth || !process.stdin.isTTY) {\n // Non-interactive with no keys is an anonymous crawl by definition. It is\n // not an error: crawling a public site is the common case.\n return saveStorageStatePath ? { saveStorageStatePath } : null;\n }\n\n console.log(`\nAuthentication for ${startUrl.hostname}\n Press Enter to crawl public pages only; pages behind a sign-in wall are skipped.\n Credentials are held by this agent process and never reach the control plane.`);\n const headerLine = await readSecret('Auth header (Name: value, blank = anonymous): ');\n const cookieLine = await readSecret('Auth cookie (name=value; ..., blank = none): ');\n\n if (headerLine.trim().length === 0 && cookieLine.trim().length === 0) {\n return saveStorageStatePath ? { saveStorageStatePath } : null;\n }\n return buildKeyAuth(\n headerLine.trim() || undefined,\n undefined,\n cookieLine.trim() || undefined,\n saveStorageStatePath,\n );\n }\n\n let password = '';\n if (passwordFromStdin) {\n password = await readStdin();\n } else if (process.env.LUXRAY_SITE_PASSWORD) {\n password = process.env.LUXRAY_SITE_PASSWORD;\n }\n\n if (!username) {\n if (!process.stdin.isTTY) {\n throw new Error(\n 'A sign-in was requested without a username. Pass --username (or LUXRAY_SITE_USERNAME).',\n );\n }\n username = await askLine('Username or email: ');\n }\n\n if (!password) {\n if (!process.stdin.isTTY) {\n throw new Error(\n 'A sign-in was requested without a password. Use --password-stdin or LUXRAY_SITE_PASSWORD.',\n );\n }\n password = await readSecret('Site password: ');\n }\n\n if (!username || !password) {\n throw new Error('A username and password are required to sign in.');\n }\n\n const loginUrl = loginUrlFlag ?? startUrl.toString();\n let parsedLoginUrl: URL;\n try {\n parsedLoginUrl = new URL(loginUrl);\n } catch {\n throw new Error(`--login-url \"${loginUrl}\" is not an absolute URL.`);\n }\n if (parsedLoginUrl.protocol !== 'http:' && parsedLoginUrl.protocol !== 'https:') {\n throw new Error(`--login-url must be http(s) (got ${parsedLoginUrl.protocol}).`);\n }\n\n if (saveStorageStatePath) {\n await mkdir(dirname(saveStorageStatePath), { recursive: true });\n }\n\n return {\n credentials: { username, password },\n loginUrl: parsedLoginUrl.toString(),\n submitTimeoutMs: parsePositiveIntFlag(flags['auth-timeout-ms'], 30_000, 600_000),\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n // A captcha or 2FA prompt cannot be solved by a form fill. When the window\n // is visible the operator finishes it; otherwise the run fails with a clear\n // message instead of crawling the login wall.\n ...(options.headless\n ? {}\n : {\n manualAssist: async (): Promise<void> => {\n console.log(\n '\\nFinish the sign-in in the browser window (captcha, two-factor, device approval).',\n );\n await askLine('Press Enter once you are signed in: ');\n },\n }),\n };\n}\n\n/**\n * Builds the auth-key answer from flags or prompt lines.\n *\n * A key that was supplied but cannot be parsed is an error, never silently\n * dropped: crawling anonymously after an operator handed over a token would\n * look like the token simply did not work.\n */\nfunction buildKeyAuth(\n header: string | undefined,\n headersJson: string | undefined,\n cookies: string | undefined,\n saveStorageStatePath: string | undefined,\n): ExploreAuthOptions {\n const headers: Record<string, string> = {};\n\n if (headersJson) Object.assign(headers, parseAuthHeadersJson(headersJson));\n if (header) {\n const parsed = parseAuthHeader(header);\n headers[parsed.name] = parsed.value;\n }\n\n const parsedCookies = cookies ? parseAuthCookies(cookies) : [];\n if (Object.keys(headers).length === 0 && parsedCookies.length === 0) {\n throw new Error('Auth keys were requested but no header or cookie was supplied.');\n }\n\n return {\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n ...(parsedCookies.length > 0 ? { cookies: parsedCookies } : {}),\n ...(saveStorageStatePath ? { saveStorageStatePath } : {}),\n };\n}\n\nasync function resolveWorkspaceId(\n flags: Record<string, string>,\n session: LoginResponse,\n): Promise<string> {\n const requested = flags.workspace || process.env.LUXRAY_WORKSPACE_ID;\n const available = session.workspaces;\n\n if (requested) {\n if (available.length > 0 && !available.some((workspace) => workspace.id === requested)) {\n throw new Error(`You are not a member of workspace \"${requested}\".`);\n }\n return requested;\n }\n\n if (available.length === 0) {\n throw new Error(\n 'Your account does not belong to any workspace. Create one in the dashboard first.',\n );\n }\n\n const only = available[0];\n if (available.length === 1 && only) {\n return only.id;\n }\n\n if (!process.stdin.isTTY) {\n throw new Error(\n `Multiple workspaces available; pass --workspace. Options: ${available\n .map((workspace) => `${workspace.id} (${workspace.name})`)\n .join(', ')}`,\n );\n }\n\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n console.log('Available workspaces:');\n for (const workspace of available) {\n console.log(` ${workspace.id} ${workspace.name} [${workspace.role}]`);\n }\n const answer = (await rl.question('Enter Workspace ID: ')).trim();\n rl.close();\n\n if (!available.some((workspace) => workspace.id === answer)) {\n throw new Error(`You are not a member of workspace \"${answer}\".`);\n }\n return answer;\n}\n\nasync function handleRegister(flags: Record<string, string>): Promise<void> {\n const apiUrl = (flags.url || process.env.LUXRAY_API_URL || DEFAULT_API_URL).replace(/\\/$/, '');\n const wsUrl = flags.ws || process.env.LUXRAY_WS_URL || DEFAULT_WS_URL;\n const name = flags.name || process.env.LUXRAY_AGENT_NAME || os.hostname();\n const platform = os.platform() as AgentPlatform;\n const arch = os.arch() as AgentArchitecture;\n const version = '0.1.0';\n\n let session: LoginResponse | null = null;\n let accessToken: string;\n\n try {\n if (flags.token) {\n console.warn(\n '[SECURITY WARNING] Passing an access token via --token exposes it in your shell history and process list.',\n );\n accessToken = flags.token;\n } else {\n const { email, password } = await resolveLoginCredentials(flags);\n console.log(`Authenticating as ${email}...`);\n session = await login(httpFetch, apiUrl, email, password);\n accessToken = session.accessToken;\n console.log(`Authenticated as ${session.user.email}.`);\n }\n\n let workspaceId = flags.workspace || process.env.LUXRAY_WORKSPACE_ID;\n if (session) {\n workspaceId = await resolveWorkspaceId(flags, session);\n }\n if (!workspaceId) {\n throw new Error('Workspace ID is required. Use --workspace or LUXRAY_WORKSPACE_ID.');\n }\n\n console.log(`Registering agent \"${name}\" with workspace ${workspaceId} at ${apiUrl}...`);\n\n const data = await registerAgent(httpFetch, apiUrl, workspaceId, accessToken, {\n name,\n platform,\n arch,\n version,\n });\n\n const creds: StoredAgentCredentials = {\n apiUrl,\n wsUrl,\n workspaceId,\n agentId: data.agent.id,\n token: data.token,\n name,\n savedAt: new Date().toISOString(),\n };\n\n const savedPath = await CredentialVault.saveCredentials(\n creds,\n flags.config,\n flags['allow-insecure'] === 'true',\n );\n\n console.log(`\nAgent successfully registered!\n Agent ID: ${data.agent.id}\n Device Name: ${data.agent.name}\n Workspace: ${workspaceId}\n Credentials: ${savedPath}\n\nTo start your agent, run:\n npx luxray-agent start\n`);\n } catch (err) {\n if (err instanceof LuxrayApiError) {\n console.error(`Registration failed: ${err.message}`);\n } else {\n console.error(`Registration failed: ${(err as Error).message}`);\n }\n process.exit(1);\n }\n}\n\nasync function handleLogin(flags: Record<string, string>): Promise<void> {\n let agentId = flags['agent-id'] || flags.agentId;\n let workspaceId = flags.workspace;\n let token = flags.token;\n\n if (flags['token-stdin'] === 'true' || flags['token-stdin'] === '') {\n token = await readStdin();\n }\n\n // If token is provided in command line arguments, warn user about shell history leakage\n if (flags.token && !flags['token-stdin']) {\n console.warn(`\n[SECURITY WARNING] Passing credentials via '--token' exposes secrets in your shell history and process list.\nPrefer the interactive prompt or '--token-stdin' in automation scripts.\n`);\n }\n\n // Interactive prompts if fields are missing and stdin is a TTY\n if (process.stdin.isTTY && (!agentId || !workspaceId || !token)) {\n const rl = readline.createInterface({ input: process.stdin, output: process.stdout });\n if (!workspaceId) {\n workspaceId = (await rl.question('Enter Workspace ID: ')).trim();\n }\n if (!agentId) {\n agentId = (await rl.question('Enter Agent ID: ')).trim();\n }\n rl.close();\n if (!token) {\n // Masked: the agent token must never be echoed to the terminal.\n token = await readSecret('Enter Agent Token (hidden): ');\n }\n }\n\n if (!agentId || !token || !workspaceId) {\n console.error('Error: Agent ID, Workspace ID, and Token are required.');\n process.exit(1);\n }\n\n const wsUrl = flags.ws || process.env.LUXRAY_WS_URL || DEFAULT_WS_URL;\n const apiUrl = (flags.url || process.env.LUXRAY_API_URL || DEFAULT_API_URL).replace(/\\/$/, '');\n const name = flags.name || os.hostname();\n\n const creds: StoredAgentCredentials = {\n apiUrl,\n wsUrl,\n workspaceId,\n agentId,\n token,\n name,\n savedAt: new Date().toISOString(),\n };\n\n const savedPath = await CredentialVault.saveCredentials(\n creds,\n flags.config,\n flags['allow-insecure'] === 'true',\n );\n console.log(`Credentials saved securely to ${savedPath}`);\n}\n\nasync function handleStart(flags: Record<string, string>): Promise<void> {\n const creds = await CredentialVault.loadCredentials(flags.config);\n if (!creds) {\n console.error(`\nNo valid agent credentials found.\nPlease register this agent first:\n npx luxray-agent register\nOr login interactively:\n npx luxray-agent login\nOr configure environment variables (LUXRAY_AGENT_ID, LUXRAY_AGENT_TOKEN, LUXRAY_WORKSPACE_ID).\n`);\n process.exit(1);\n }\n\n const wsUrl = flags.ws || creds.wsUrl;\n const headless = flags.headed !== 'true';\n const artifactRoot = flags.out ? flags.out : join(os.homedir(), '.luxray', 'runs');\n\n console.log(`\nStarting Luxray Agent:\n Agent ID: ${creds.agentId}\n Name: ${creds.name}\n Workspace: ${creds.workspaceId}\n Gateway: ${wsUrl}\n Artifacts: ${artifactRoot}\n`);\n\n const streamConfig = streamConfigFromEnv(process.env, {\n clientId: `luxray-agent-${creds.agentId}`,\n });\n console.log(` Kafka: ${streamConfig.brokers.join(', ')}`);\n\n const worker = new ExplorationWorker({ headless });\n const explorationLogger = {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n\n let client: AgentClient;\n let stream: TaskStream | null = null;\n const executor = new TaskExecutor({\n agentId: creds.agentId,\n // Reports leave over Kafka. The socket cannot carry them any more: the\n // server nacks task frames with WRONG_TRANSPORT.\n send: (message) => stream?.report(message) ?? false,\n maxConcurrentJobs: parsePositiveIntFlag(flags['max-jobs'], 1, 16),\n maxJobDurationMs: parsePositiveIntFlag(flags['max-job-ms'], 120_000, 86_400_000),\n explorationMaxDurationMs: parsePositiveIntFlag(\n flags['max-exploration-ms'],\n DEFAULT_EXPLORE_JOB_MS,\n 86_400_000,\n ),\n progressIntervalMs: parsePositiveIntFlag(flags['progress-interval-ms'], 1_000, 60_000),\n leaseRenewIntervalMs: flags['lease-renew-ms']\n ? parsePositiveIntFlag(flags['lease-renew-ms'], 30_000, 86_400_000)\n : undefined,\n // Dashboard-assigned EXPLORATION tasks run in the same isolated browser\n // worker the terminal `explore` command uses.\n explorationRunner: createExplorationRunner(worker, {\n artifactRoot,\n headless,\n logger: explorationLogger,\n onPage: (page) => {\n // A dashboard sees the crawl while it runs instead of after it ends.\n stream?.publishPage(page);\n },\n }),\n // The TEST job exists so dispatch, cancellation and timeouts can be\n // exercised without a browser.\n testSteps: flags['test-steps']\n ? parsePositiveIntFlag(flags['test-steps'], 5, 10_000)\n : undefined,\n testStepDelayMs: flags['test-step-delay-ms']\n ? parseNonNegativeIntFlag(flags['test-step-delay-ms'], 200, 60_000)\n : undefined,\n });\n\n stream = new TaskStream({\n config: streamConfig,\n agentId: creds.agentId,\n workspaceId: creds.workspaceId,\n handlers: {\n onOffer: (msg) => executor.handleOffer(msg),\n onCancel: (msg) => executor.handleCancel(msg),\n onPause: (msg) => executor.handlePause(msg),\n onRenewed: (msg) => executor.handleRenewed(msg),\n onNack: (msg) => executor.handleNack(msg),\n },\n logger: explorationLogger,\n });\n\n client = new AgentClient({\n wsUrl,\n agentId: creds.agentId,\n token: creds.token,\n onRevoked: (msg) => {\n console.error(`\\nAgent credentials revoked: ${msg.reason}. Exiting.`);\n void executor.shutdown().finally(() => process.exit(1));\n },\n onDisconnect: (code, reason) => {\n if (code === 4401) {\n console.error('\\nAuthentication failed: credentials invalid or revoked. Exiting.');\n void executor.shutdown().finally(() => process.exit(1));\n }\n },\n });\n\n let stopping = false;\n const shutdown = (): void => {\n if (stopping) return;\n stopping = true;\n console.log('\\nShutting down agent gracefully...');\n void (async () => {\n // Abort in-flight jobs first so the server sees the lease abandoned\n // rather than a completion that races the disconnect.\n await executor.shutdown().catch(() => {});\n // Flush the terminal report before the process disappears; the socket\n // only needs to close after that.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n process.exit(0);\n })();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n await stream.connect();\n } catch (err) {\n // No silent fallback to the socket: the socket no longer carries tasks, so\n // an agent that \"connected\" without Kafka would accept work and be unable\n // to report a byte of it.\n console.error(`Cannot start execution: ${(err as Error).message}`);\n await worker.dispose().catch(() => {});\n process.exitCode = 1;\n return;\n }\n\n try {\n await client.connect();\n console.log('Agent is online and waiting for exploration tasks.\\nPress Ctrl+C to stop.');\n } catch (err: any) {\n console.error(`Failed to connect to gateway: ${err.message}`);\n await stream.close().catch(() => {});\n await executor.shutdown();\n await worker.dispose().catch(() => {});\n process.exitCode = 1;\n }\n}\n\nasync function handleExplore(\n positionals: readonly string[],\n flags: Record<string, string>,\n): Promise<void> {\n const rawUrl = positionals[0];\n if (!rawUrl) {\n console.error('Usage: luxray-agent explore <url> [options]');\n console.error('Example: luxray-agent explore https://example.com --max-pages 20');\n process.exit(1);\n }\n\n let startUrl: URL;\n try {\n startUrl = new URL(rawUrl);\n } catch {\n console.error(`Error: \"${rawUrl}\" is not an absolute URL.`);\n process.exit(1);\n }\n if (startUrl.protocol !== 'http:' && startUrl.protocol !== 'https:') {\n console.error(`Error: only http(s) URLs can be explored (got ${startUrl.protocol}).`);\n process.exit(1);\n }\n\n const creds = await CredentialVault.loadCredentials(flags.config);\n if (!creds) {\n console.error(`\nNo valid agent credentials found.\nRegister or import this agent first:\n npx luxray-agent register\n npx luxray-agent login\n`);\n process.exit(1);\n }\n\n const hostname = startUrl.hostname.toLowerCase();\n const allowedDomains = flags['allowed-domains']\n ? flags['allowed-domains']\n .split(',')\n .map((domain) => domain.trim().toLowerCase())\n .filter((domain) => domain.length > 0)\n : [hostname];\n if (allowedDomains.length === 0) {\n console.error('Error: --allowed-domains did not contain a single hostname.');\n process.exit(1);\n }\n\n const maxPages = parsePositiveIntFlag(flags['max-pages'], DEFAULT_EXPLORE_MAX_PAGES, 1_000);\n const maxDepth = parsePositiveIntFlag(flags['max-depth'], DEFAULT_EXPLORE_MAX_DEPTH, 10);\n const maxJobMs = parsePositiveIntFlag(flags['max-job-ms'], DEFAULT_EXPLORE_JOB_MS, 3_600_000);\n const includeSubdomains = flags['include-subdomains'] === 'true';\n const includeSecrets = flags['include-secrets'] === 'true';\n const headless = flags.headed !== 'true';\n const artifactRoot = flags.out\n ? flags.out\n : join(os.homedir(), '.luxray', 'runs');\n const apiUrl = (flags.api || flags.url || creds.apiUrl).replace(/\\/$/, '');\n const wsUrl = flags.ws || creds.wsUrl;\n const streamConfig = streamConfigFromEnv(process.env, {\n clientId: `luxray-agent-${creds.agentId}`,\n });\n\n // Ask before touching the network or the control plane: a crawl that needs a\n // session should fail here, at the prompt, not 13 pages into a login wall.\n const auth = await resolveExploreAuth(flags, startUrl, { headless });\n\n // Warn before touching credentials: this changes what lands on disk.\n if (includeSecrets) {\n console.warn(\n '[SECURITY WARNING] --include-secrets keeps Authorization/Cookie headers in the run artifacts.',\n );\n }\n if (auth?.saveStorageStatePath) {\n console.warn(\n `[SECURITY WARNING] --save-auth-state writes live session cookies to ${auth.saveStorageStatePath}.`,\n );\n }\n\n const signInLine = auth?.credentials\n ? `${auth.loginUrl} (credentials used once, not stored)`\n : auth?.headers || auth?.cookies\n ? [\n auth.headers ? `${Object.keys(auth.headers).length} header(s)` : null,\n auth.cookies ? `${auth.cookies.length} cookie(s)` : null,\n ]\n .filter((part): part is string => part !== null)\n .join(' + ') + ' (used for this run, not stored)'\n : auth?.storageStatePath\n ? `saved session from ${auth.storageStatePath}`\n : 'none (public crawl)';\n\n console.log(`\nLuxray exploration\n Start URL: ${startUrl.toString()}\n Scope: ${allowedDomains.join(', ')}${includeSubdomains ? ' (including subdomains)' : ''}\n Limits: ${maxPages} pages, depth ${maxDepth}, ${Math.round(maxJobMs / 1000)}s\n Artifacts: ${artifactRoot}\n Browser: ${headless ? 'headless' : 'visible'}\n Sign-in: ${signInLine}\n Kafka: ${streamConfig.brokers.join(', ')}\n Agent: ${creds.agentId}\n`);\n\n const worker = new ExplorationWorker({ headless });\n const logger = {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n\n let targetTaskId: string | null = null;\n let settleTargetTask: (taskId: string | null) => void = () => {};\n // The offer can beat the HTTP response that carries the task id. The sign-in\n // binding waits on this instead of reading a variable that may still be null.\n const targetTask = new Promise<string | null>((resolve) => {\n settleTargetTask = resolve;\n });\n let lastOutcome: ExplorationOutcome | null = null;\n let jobSettled = false;\n let resolveFinished: (info: JobFinishedInfo) => void = () => {};\n const finished = new Promise<JobFinishedInfo>((resolve) => {\n resolveFinished = resolve;\n });\n\n let client: AgentClient;\n let stream: TaskStream | null = null;\n const executor = new TaskExecutor({\n agentId: creds.agentId,\n send: (message) => stream?.report(message) ?? false,\n maxConcurrentJobs: 1,\n maxJobDurationMs: maxJobMs,\n explorationMaxDurationMs: maxJobMs,\n explorationRunner: createExplorationRunner(worker, {\n artifactRoot,\n headless,\n includeSecrets,\n // Only the task this command created may use the operator's session; a\n // stale queued task assigned to this agent must not inherit it.\n auth: auth\n ? {\n ...auth,\n appliesTo: async (taskId) => taskId === (await targetTask),\n }\n : undefined,\n logger,\n onPage: (page) => {\n stream?.publishPage(page);\n },\n onFinished: (result) => {\n lastOutcome = result.outcome;\n },\n }),\n onJobFinished: (info) => {\n // Unrelated tasks assigned to this agent may also come through; only the\n // one this command created decides when the command ends.\n if (targetTaskId !== null && info.taskId === targetTaskId) {\n jobSettled = true;\n resolveFinished(info);\n }\n },\n logger: {\n info: (...args: unknown[]) => console.log(...args),\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n },\n });\n\n stream = new TaskStream({\n config: streamConfig,\n agentId: creds.agentId,\n workspaceId: creds.workspaceId,\n handlers: {\n onOffer: (msg) => executor.handleOffer(msg),\n onCancel: (msg) => executor.handleCancel(msg),\n onPause: (msg) => executor.handlePause(msg),\n onRenewed: (msg) => executor.handleRenewed(msg),\n onNack: (msg) => executor.handleNack(msg),\n },\n logger,\n });\n\n client = new AgentClient({\n wsUrl,\n agentId: creds.agentId,\n token: creds.token,\n onRevoked: (msg) => {\n console.error(`\\nAgent credentials revoked: ${msg.reason}. Exiting.`);\n executor.failActiveJobs('Agent credentials were revoked during the run.');\n void executor.shutdown().finally(() => process.exit(1));\n },\n onDisconnect: (code) => {\n if (code === 4401) {\n console.error('\\nAuthentication failed: credentials invalid or revoked. Exiting.');\n void executor.shutdown().finally(() => process.exit(1));\n }\n },\n });\n\n let stopping = false;\n const interrupt = (): void => {\n if (stopping) return;\n stopping = true;\n console.error('\\nStopped by the operator; reporting the failure to the control plane...');\n void (async () => {\n executor.failActiveJobs('Stopped by the operator (Ctrl+C).');\n await executor.shutdown().catch(() => {});\n // Flush the failure frame before the process disappears.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n process.exit(130);\n })();\n };\n process.on('SIGINT', interrupt);\n process.on('SIGTERM', interrupt);\n\n let exitCode = 0;\n try {\n await stream.connect();\n } catch (err) {\n console.error(`Cannot start the Kafka transport: ${(err as Error).message}`);\n await worker.dispose().catch(() => {});\n process.exit(1);\n }\n\n try {\n await client.connect();\n console.log(`Connected as agent ${creds.agentId}. Creating the exploration task...`);\n\n const { task } = await createAgentExplorationTask(httpFetch, apiUrl, creds.token, {\n startUrl: startUrl.toString(),\n jobType: 'EXPLORATION',\n name: flags.name,\n scope: {\n allowedDomains,\n includeSubdomains,\n maxPages,\n maxDepth,\n },\n });\n targetTaskId = task.id;\n settleTargetTask(task.id);\n console.log(`Task ${task.id} created and assigned. Watching the crawl:\\n`);\n\n // Only the handoff is time-boxed. A crawl's duration is bounded by\n // --max-job-ms, so a slow site is allowed to finish instead of being\n // killed by a watchdog that was only meant to catch a missing offer.\n const start = await executor.waitForJobStarted(task.id, OFFER_WAIT_MS);\n if (start === 'timeout') {\n console.error(\n `The API did not hand task ${task.id} to this agent within ` +\n `${Math.round(OFFER_WAIT_MS / 1000)}s. It keeps its lease, which will expire and ` +\n 'return the task to the queue; check that the gateway is reachable.',\n );\n exitCode = 1;\n } else {\n const result = await finished;\n\n if (result.outcome === 'completed') {\n printExplorationSummary(lastOutcome);\n exitCode = 0;\n } else if (result.outcome === 'stopped') {\n console.error(`\\nExploration stopped (${result.stopReason ?? 'unknown reason'}).`);\n exitCode = 130;\n } else {\n console.error(`\\nExploration failed: ${result.error ?? 'unknown error'}`);\n exitCode = 1;\n }\n }\n } catch (err) {\n if (err instanceof LuxrayApiError) {\n console.error(`Could not create the exploration task: ${err.message}`);\n } else {\n console.error(`Exploration aborted: ${(err as Error).message}`);\n }\n exitCode = 1;\n } finally {\n process.removeListener('SIGINT', interrupt);\n process.removeListener('SIGTERM', interrupt);\n // A job that started before the task was created must not wait forever.\n settleTargetTask(targetTaskId);\n\n // Walking away from a task the server still believes is running must be\n // reported: otherwise the dashboard shows a phantom RUNNING job until the\n // lease expires and the queue silently retries it.\n if (targetTaskId !== null && !jobSettled && executor.getRunningJobCount() > 0) {\n executor.failActiveJobs('The agent stopped before the crawl finished.');\n }\n\n await executor.shutdown().catch(() => {});\n // Flushes the terminal frame; without this the DB can keep saying RUNNING\n // while the command exits successfully.\n await stream?.close().catch(() => {});\n await client.disconnect();\n await worker.dispose().catch(() => {});\n }\n\n process.exit(exitCode);\n}\n\nfunction printExplorationSummary(outcome: ExplorationOutcome | null): void {\n if (!outcome) {\n console.log('\\nExploration completed.');\n return;\n }\n\n const summary = outcome.run.summary;\n console.log(`\nExploration completed.\n Pages visited: ${summary.pagesVisited}\n Pages failed: ${summary.pagesFailed}\n Duplicate templates: ${summary.duplicatePages}\n Requests captured: ${outcome.transactionsCaptured}\n Links discovered: ${summary.linksDiscovered}\n Frontier remaining: ${summary.frontierRemaining}\n Duration: ${(summary.durationMs / 1000).toFixed(1)}s\n Artifacts: ${outcome.paths.dir}\n`);\n if (summary.truncatedByLimit) {\n console.log(\n ` Note: stopped by a limit with ${summary.frontierRemaining} URL(s) still queued. ` +\n 'Raise --max-pages/--max-depth or --max-job-ms to go further.',\n );\n }\n\n const authentication = summary.authentication;\n if (authentication) {\n const parts: string[] = [authentication.strategy];\n if (authentication.loginUrl) parts.push(`at ${authentication.loginUrl}`);\n if (authentication.headers > 0) parts.push(`${authentication.headers} header(s)`);\n if (authentication.cookies !== null) parts.push(`${authentication.cookies} cookie(s)`);\n console.log(` Auth: ${parts.join(', ')}`);\n }\n}\n\nasync function handleStatus(flags: Record<string, string>): Promise<void> {\n const creds = await CredentialVault.loadCredentials(flags.config);\n const defaultPath = CredentialVault.getDefaultPath();\n\n console.log('Luxray Local Agent Status:');\n console.log(` Credentials path: ${defaultPath}`);\n\n if (!creds) {\n console.log(' Status: NOT CONFIGURED (No credentials found)');\n return;\n }\n\n console.log(' Status: CONFIGURED');\n console.log(` Agent ID: ${creds.agentId}`);\n console.log(` Device Name: ${creds.name}`);\n console.log(` Workspace ID: ${creds.workspaceId}`);\n console.log(` Gateway WS: ${creds.wsUrl}`);\n console.log(` Registered: ${creds.savedAt}`);\n}\n\nasync function handleLogout(flags: Record<string, string>): Promise<void> {\n const cleared = await CredentialVault.clearCredentials(flags.config);\n if (cleared) {\n console.log('Credentials cleared successfully.');\n } else {\n console.log('No credentials found to clear.');\n }\n}\n\nasync function main(): Promise<void> {\n const { command, flags, positionals } = parseArgs(process.argv.slice(2));\n\n switch (command) {\n case 'register':\n await handleRegister(flags);\n break;\n case 'login':\n await handleLogin(flags);\n break;\n case 'start':\n await handleStart(flags);\n break;\n case 'explore':\n await handleExplore(positionals, flags);\n break;\n case 'status':\n await handleStatus(flags);\n break;\n case 'logout':\n await handleLogout(flags);\n break;\n case 'help':\n case '--help':\n case '-h':\n printHelp();\n break;\n default:\n printHelp();\n // An unknown command is an operator mistake, so it is not a success.\n process.exitCode = 1;\n break;\n }\n}\n\nmain().catch((err) => {\n console.error('Fatal agent error:', err);\n process.exit(1);\n});\n","import * as fs from 'node:fs/promises';\nimport * as path from 'node:path';\nimport * as os from 'node:os';\nimport { execFile } from 'node:child_process';\nimport { promisify } from 'node:util';\n\nconst execFileAsync = promisify(execFile);\n\nexport interface StoredAgentCredentials {\n apiUrl: string;\n wsUrl: string;\n workspaceId: string;\n agentId: string;\n token: string;\n name: string;\n savedAt: string;\n}\n\nexport class CredentialVault {\n public static getDefaultPath(): string {\n const override = process.env.LUXRAY_CREDENTIALS_PATH;\n if (override && override.trim().length > 0) {\n return path.resolve(override);\n }\n const homeDir = os.homedir();\n return path.join(homeDir, '.luxray', 'credentials.json');\n }\n\n /**\n * Securely saves credentials to the file system with platform-specific ACL/permission restrictions.\n * - POSIX: Mode 0600 on file, 0700 on directory (readable/writable only by UID).\n * - Windows: Applies icacls to restrict file ACL to the active %USERNAME%.\n */\n public static async saveCredentials(\n credentials: StoredAgentCredentials,\n filePath?: string,\n allowInsecureFallback = false,\n ): Promise<string> {\n const targetPath = filePath ?? this.getDefaultPath();\n const targetDir = path.dirname(targetPath);\n\n // Ensure parent directory exists with 0700 mode permissions\n await fs.mkdir(targetDir, { recursive: true, mode: 0o700 });\n\n const content = JSON.stringify(credentials, null, 2);\n\n // Write file directly with 0600 permissions\n await fs.writeFile(targetPath, content, { encoding: 'utf8', mode: 0o600 });\n\n // Apply platform-specific ACL enforcement\n if (os.platform() === 'win32') {\n try {\n const username = process.env.USERNAME;\n if (username) {\n // Remove inherited ACLs and grant exclusive read/write to current user\n await execFileAsync('icacls', [\n targetPath,\n '/inheritance:r',\n '/grant:r',\n `${username}:(R,W)`,\n ]);\n }\n } catch (err: any) {\n if (!allowInsecureFallback && process.env.LUXRAY_ALLOW_INSECURE_STORAGE !== 'true') {\n console.warn(\n `[CredentialVault:WARN] Could not apply strict Windows NTFS ACLs to credentials file: ${err.message}.`,\n );\n }\n }\n } else {\n try {\n await fs.chmod(targetPath, 0o600);\n } catch (err: any) {\n if (!allowInsecureFallback && process.env.LUXRAY_ALLOW_INSECURE_STORAGE !== 'true') {\n console.warn(\n `[CredentialVault:WARN] Could not apply chmod 0600 to credentials file: ${err.message}.`,\n );\n }\n }\n }\n\n return targetPath;\n }\n\n /**\n * Loads credentials from the file system or environment variables.\n * Environment variables take precedence if LUXRAY_AGENT_TOKEN and LUXRAY_AGENT_ID are provided.\n */\n public static async loadCredentials(filePath?: string): Promise<StoredAgentCredentials | null> {\n // Check environment variable overrides first\n const envToken = process.env.LUXRAY_AGENT_TOKEN;\n const envAgentId = process.env.LUXRAY_AGENT_ID;\n const envWorkspaceId = process.env.LUXRAY_WORKSPACE_ID;\n const envApiUrl = process.env.LUXRAY_API_URL || 'http://localhost:4000';\n const envWsUrl = process.env.LUXRAY_WS_URL || 'ws://127.0.0.1:4001/v1/agent/socket';\n\n if (envToken && envAgentId && envWorkspaceId) {\n return {\n apiUrl: envApiUrl,\n wsUrl: envWsUrl,\n workspaceId: envWorkspaceId,\n agentId: envAgentId,\n token: envToken,\n name: process.env.LUXRAY_AGENT_NAME || os.hostname(),\n savedAt: new Date().toISOString(),\n };\n }\n\n const targetPath = filePath ?? this.getDefaultPath();\n\n try {\n const data = await fs.readFile(targetPath, 'utf8');\n const parsed = JSON.parse(data) as Partial<StoredAgentCredentials>;\n\n if (\n !parsed.agentId ||\n !parsed.token ||\n !parsed.workspaceId ||\n !parsed.wsUrl\n ) {\n return null;\n }\n\n return {\n apiUrl: parsed.apiUrl || 'http://localhost:4000',\n wsUrl: parsed.wsUrl,\n workspaceId: parsed.workspaceId,\n agentId: parsed.agentId,\n token: parsed.token,\n name: parsed.name || 'Unnamed Agent',\n savedAt: parsed.savedAt || new Date().toISOString(),\n };\n } catch {\n return null;\n }\n }\n\n /**\n * Deletes the stored credentials file.\n */\n public static async clearCredentials(filePath?: string): Promise<boolean> {\n const targetPath = filePath ?? this.getDefaultPath();\n try {\n await fs.unlink(targetPath);\n return true;\n } catch {\n return false;\n }\n }\n}\n","import { WebSocket } from 'ws';\nimport * as os from 'node:os';\nimport type {\n AgentPlatform,\n AgentArchitecture,\n AgentProtocolMessage,\n AgentConnectedMessage,\n AgentHeartbeatAckMessage,\n AgentErrorMessage,\n AgentRevokedMessage,\n AgentStatusMessage,\n} from '@luxray/shared';\n\nexport type AgentClientState =\n | 'idle'\n | 'connecting'\n | 'connected'\n | 'reconnecting'\n | 'stopped'\n | 'revoked';\n\nexport interface AgentClientOptions {\n wsUrl: string;\n agentId: string;\n token: string;\n version?: string;\n platform?: AgentPlatform;\n arch?: AgentArchitecture;\n heartbeatIntervalMs?: number;\n autoReconnect?: boolean;\n initialBackoffMs?: number;\n maxBackoffMs?: number;\n onConnected?: (msg: AgentConnectedMessage) => void;\n onHeartbeatAck?: (msg: AgentHeartbeatAckMessage) => void;\n onRevoked?: (msg: AgentRevokedMessage) => void;\n onError?: (err: Error) => void;\n onDisconnect?: (code: number, reason: string) => void;\n logger?: {\n info: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n debug: (...args: any[]) => void;\n };\n}\n\nexport class AgentClient {\n private ws: WebSocket | null = null;\n private state: AgentClientState = 'idle';\n private heartbeatTimer: NodeJS.Timeout | null = null;\n private reconnectTimer: NodeJS.Timeout | null = null;\n private reconnectAttempt = 0;\n private isIntentionallyClosed = false;\n private activeHeartbeatIntervalMs = 10000;\n private connectionId: string | null = null;\n\n private readonly wsUrl: string;\n private readonly agentId: string;\n private readonly token: string;\n private readonly version: string;\n private readonly platform: AgentPlatform;\n private readonly arch: AgentArchitecture;\n private readonly autoReconnect: boolean;\n private readonly initialBackoffMs: number;\n private readonly maxBackoffMs: number;\n private readonly logger: NonNullable<AgentClientOptions['logger']>;\n\n constructor(private readonly options: AgentClientOptions) {\n this.wsUrl = options.wsUrl;\n this.agentId = options.agentId;\n this.token = options.token;\n this.version = options.version || '0.1.0';\n this.platform = options.platform || (os.platform() as AgentPlatform);\n this.arch = options.arch || (os.arch() as AgentArchitecture);\n this.autoReconnect = options.autoReconnect ?? true;\n this.initialBackoffMs = options.initialBackoffMs ?? 1000;\n this.maxBackoffMs = options.maxBackoffMs ?? 30000;\n this.activeHeartbeatIntervalMs = options.heartbeatIntervalMs ?? 10000;\n this.logger = options.logger ?? {\n info: (...args) => console.log('[LuxrayAgent]', ...args),\n warn: (...args) => console.warn('[LuxrayAgent:WARN]', ...args),\n error: (...args) => console.error('[LuxrayAgent:ERROR]', ...args),\n debug: (...args) => {},\n };\n }\n\n public getState(): AgentClientState {\n return this.state;\n }\n\n public getConnectionId(): string | null {\n return this.connectionId;\n }\n\n public isConnected(): boolean {\n return this.state === 'connected' && this.ws?.readyState === WebSocket.OPEN;\n }\n\n /**\n * Connects to the Luxray Cloud WebSocket server and completes the hello handshake.\n */\n public connect(): Promise<AgentConnectedMessage> {\n if (this.state === 'revoked') {\n return Promise.reject(new Error('Agent credentials have been revoked. Cannot connect.'));\n }\n\n this.isIntentionallyClosed = false;\n this.state = 'connecting';\n\n return new Promise((resolve, reject) => {\n let isResolved = false;\n\n try {\n this.ws = new WebSocket(this.wsUrl);\n } catch (err: any) {\n this.state = 'idle';\n return reject(err);\n }\n\n const connectionTimeout = setTimeout(() => {\n if (!isResolved) {\n isResolved = true;\n this.logger.error('Connection timed out waiting for server response.');\n this.ws?.terminate();\n reject(new Error('Connection timed out.'));\n }\n }, 15000);\n\n this.ws.on('open', () => {\n this.logger.info(`WebSocket transport opened to ${this.wsUrl}. Sending agent.hello...`);\n this.sendHello();\n });\n\n this.ws.on('message', (raw: Buffer | string) => {\n try {\n const msg = JSON.parse(raw.toString()) as AgentProtocolMessage;\n this.handleIncomingMessage(msg, (connected) => {\n if (!isResolved) {\n isResolved = true;\n clearTimeout(connectionTimeout);\n resolve(connected);\n }\n });\n } catch (err: any) {\n this.logger.error('Failed to parse incoming WebSocket message:', err.message);\n }\n });\n\n this.ws.on('close', (code, reasonBuf) => {\n clearTimeout(connectionTimeout);\n const reason = reasonBuf.toString();\n this.handleClose(code, reason);\n if (!isResolved) {\n isResolved = true;\n reject(new Error(`WebSocket closed during handshake (code: ${code}, reason: ${reason})`));\n }\n });\n\n this.ws.on('error', (err) => {\n this.logger.error('WebSocket transport error:', err.message);\n if (this.options.onError) {\n this.options.onError(err);\n }\n });\n });\n }\n\n /**\n * Sends the agent.hello greeting to identify and authenticate this agent.\n */\n private sendHello(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const helloPayload = {\n type: 'agent.hello' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n token: this.token,\n agentVersion: this.version,\n platform: this.platform,\n arch: this.arch,\n timestamp: Date.now(),\n };\n\n this.ws.send(JSON.stringify(helloPayload));\n }\n\n /**\n * Handles incoming protocol messages.\n */\n private handleIncomingMessage(\n msg: AgentProtocolMessage,\n onConnectedFirstTime: (connected: AgentConnectedMessage) => void,\n ): void {\n switch (msg.type) {\n case 'agent.connected': {\n const connectedMsg = msg as AgentConnectedMessage;\n this.state = 'connected';\n this.reconnectAttempt = 0;\n this.connectionId = connectedMsg.connectionId;\n this.activeHeartbeatIntervalMs = connectedMsg.heartbeatIntervalMs || 10000;\n this.logger.info(\n `Successfully connected & authenticated with Luxray Cloud! Connection ID: ${connectedMsg.connectionId}`,\n );\n\n this.startHeartbeatLoop();\n onConnectedFirstTime(connectedMsg);\n\n if (this.options.onConnected) {\n this.options.onConnected(connectedMsg);\n }\n break;\n }\n\n case 'agent.heartbeat.ack': {\n const ackMsg = msg as AgentHeartbeatAckMessage;\n this.logger.debug(`Heartbeat acknowledged by server (ack: ${ackMsg.timestamp})`);\n if (this.options.onHeartbeatAck) {\n this.options.onHeartbeatAck(ackMsg);\n }\n break;\n }\n\n case 'agent.revoked': {\n const revokedMsg = msg as AgentRevokedMessage;\n this.state = 'revoked';\n this.isIntentionallyClosed = true;\n this.logger.error(`CRITICAL: Agent credentials have been revoked. Reason: ${revokedMsg.reason}`);\n this.stopHeartbeatLoop();\n if (this.options.onRevoked) {\n this.options.onRevoked(revokedMsg);\n }\n this.ws?.close(4401, 'Agent Revoked');\n break;\n }\n\n case 'agent.error': {\n const errMsg = msg as AgentErrorMessage;\n this.logger.error(`Server error [${errMsg.code}]: ${errMsg.message}`);\n if (errMsg.fatal) {\n this.logger.error('Fatal server error encountered. Closing connection.');\n this.ws?.close(4000, errMsg.message);\n }\n break;\n }\n\n default:\n // Task frames do not travel over this socket any more. One arriving\n // here is either a stale server or a bug worth noticing.\n this.logger.debug('Unhandled message type:', (msg as any).type);\n }\n }\n\n /**\n * Starts periodic heartbeat transmission.\n */\n private startHeartbeatLoop(): void {\n this.stopHeartbeatLoop();\n this.heartbeatTimer = setInterval(() => {\n this.sendHeartbeat();\n }, this.activeHeartbeatIntervalMs);\n }\n\n private stopHeartbeatLoop(): void {\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n }\n\n /**\n * Transmits heartbeat metrics to the cloud.\n */\n private sendHeartbeat(): void {\n if (!this.ws || this.ws.readyState !== WebSocket.OPEN) return;\n\n const memoryMb = Math.round(process.memoryUsage().rss / (1024 * 1024));\n const uptime = Math.round(process.uptime());\n\n const heartbeatPayload = {\n type: 'agent.heartbeat' as const,\n version: '1.0' as const,\n agentId: this.agentId,\n memoryUsageMb: memoryMb,\n uptimeSeconds: uptime,\n timestamp: Date.now(),\n };\n\n try {\n this.ws.send(JSON.stringify(heartbeatPayload));\n this.logger.debug(`Heartbeat sent: memory=${memoryMb}MB, uptime=${uptime}s`);\n } catch (err: any) {\n this.logger.warn('Failed to transmit heartbeat:', err.message);\n }\n }\n\n /**\n * Handles WebSocket closure and schedules reconnection if appropriate.\n */\n private handleClose(code: number, reason: string): void {\n this.stopHeartbeatLoop();\n this.connectionId = null;\n\n if (this.options.onDisconnect) {\n this.options.onDisconnect(code, reason);\n }\n\n if (code === 4401 || this.state === 'revoked') {\n this.state = 'revoked';\n this.logger.error('Connection closed: Agent credentials revoked. Will NOT reconnect.');\n return;\n }\n\n if (this.isIntentionallyClosed) {\n this.state = 'stopped';\n this.logger.info('Agent stopped gracefully.');\n return;\n }\n\n if (code === 4009) {\n this.logger.warn('Another instance of this agent connected elsewhere. Backing off.');\n }\n\n if (!this.autoReconnect) {\n this.state = 'idle';\n this.logger.info(`Connection closed (code: ${code}, reason: ${reason}). Auto-reconnect is disabled.`);\n return;\n }\n\n this.scheduleReconnect();\n }\n\n /**\n * Exponential backoff with random jitter for reconnects.\n */\n private scheduleReconnect(): void {\n this.state = 'reconnecting';\n this.reconnectAttempt++;\n\n // Backoff formula: initialBackoffMs * 1.5^(attempt - 1) + jitter (0 - 1000ms)\n const exponential = this.initialBackoffMs * Math.pow(1.5, Math.min(this.reconnectAttempt, 10));\n const jitter = Math.floor(Math.random() * 1000);\n const delay = Math.min(exponential + jitter, this.maxBackoffMs);\n\n this.logger.warn(\n `Connection lost. Reconnecting in ${(delay / 1000).toFixed(1)}s (attempt ${this.reconnectAttempt})...`,\n );\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n }\n\n this.reconnectTimer = setTimeout(async () => {\n try {\n await this.connect();\n } catch (err: any) {\n this.logger.warn('Reconnect attempt failed:', err.message);\n // The close event will trigger the next reconnect attempt\n }\n }, delay);\n }\n\n /**\n * Gracefully stops the agent connection and notifies cloud.\n *\n * Resolves once the socket has actually closed, not when closing was\n * requested. A job's terminal frame (a completion or a failure) may still be\n * in the send buffer, and the peer processes frames in order: waiting for the\n * close handshake means the report was delivered before this process exits\n * and claims the run ended.\n */\n public async disconnect(timeoutMs = 1_000): Promise<void> {\n this.isIntentionallyClosed = true;\n this.state = 'stopped';\n\n if (this.reconnectTimer) {\n clearTimeout(this.reconnectTimer);\n this.reconnectTimer = null;\n }\n\n this.stopHeartbeatLoop();\n\n const ws = this.ws;\n this.ws = null;\n if (!ws) return;\n\n // Send a graceful goodbye status before closing if socket is open\n if (ws.readyState === WebSocket.OPEN) {\n const goodbyePayload: AgentStatusMessage = {\n type: 'agent.status',\n version: '1.0',\n agentId: this.agentId,\n status: 'DISCONNECTED',\n timestamp: Date.now(),\n };\n try {\n ws.send(JSON.stringify(goodbyePayload));\n } catch {}\n }\n\n if (ws.readyState === WebSocket.CLOSED) return;\n\n await new Promise<void>((resolve) => {\n const timer = setTimeout(resolve, timeoutMs);\n timer.unref?.();\n\n ws.once('close', () => {\n clearTimeout(timer);\n resolve();\n });\n\n try {\n ws.close(1000, 'Agent Stopped Manually');\n } catch {\n clearTimeout(timer);\n resolve();\n }\n });\n }\n}\n","import { existsSync, readFileSync, readdirSync } from 'node:fs';\nimport { join } from 'node:path';\nimport type { ConnectionOptions } from 'node:tls';\nimport { StreamUnavailableError } from './errors.js';\n\nexport interface StreamSaslConfig {\n readonly mechanism: 'plain' | 'scram-sha-256' | 'scram-sha-512';\n readonly username: string;\n readonly password: string;\n}\n\nexport interface StreamConfig {\n readonly brokers: readonly string[];\n readonly clientId: string;\n readonly ssl: boolean | ConnectionOptions;\n readonly sasl: StreamSaslConfig | null;\n /** How long a broker connection may take before it counts as unavailable. */\n readonly connectionTimeoutMs: number;\n /** Retries per connect attempt; kept small so a missing broker fails fast. */\n readonly retryCount: number;\n /** Partitions used when a stream topic has to be created. Default 3. */\n readonly topicPartitions?: number;\n /** Replication factor used when a stream topic has to be created. Default 1. */\n readonly replicationFactor?: number;\n}\n\nconst DEFAULT_BROKERS = '127.0.0.1:9092';\n\nfunction findRootCert(): string | undefined {\n try {\n const cwd = process.cwd();\n const commonNames = [\n 'cl.pem',\n 'cl.cert',\n 'cl.crt',\n 'ca.pem',\n 'ca.cert',\n 'ca.crt',\n 'certificate.pem',\n 'certificate.crt',\n ];\n for (const name of commonNames) {\n const fullPath = join(cwd, name);\n if (existsSync(fullPath)) {\n return readFileSync(fullPath, 'utf-8');\n }\n }\n const files = readdirSync(cwd);\n for (const file of files) {\n const lower = file.toLowerCase();\n if (\n (lower.includes('cl') || lower.includes('ca') || lower.includes('cert')) &&\n (lower.endsWith('.pem') || lower.endsWith('.crt') || lower.endsWith('.cert'))\n ) {\n return readFileSync(join(cwd, file), 'utf-8');\n }\n }\n } catch {\n // Ignore filesystem read errors\n }\n return undefined;\n}\n\nfunction resolveSsl(\n env: NodeJS.ProcessEnv,\n brokers: readonly string[],\n hasSasl: boolean,\n): boolean | ConnectionOptions {\n if (env['KAFKA_SSL']?.toLowerCase() === 'false') {\n return false;\n }\n\n const cert = findRootCert();\n const explicitSsl = env['KAFKA_SSL']?.toLowerCase() === 'true';\n const isRemote = brokers.some(\n (b) => !b.startsWith('127.0.0.1') && !b.startsWith('localhost'),\n );\n\n const shouldEnable = explicitSsl || hasSasl || !!cert || isRemote;\n if (!shouldEnable) {\n return false;\n }\n\n if (cert) {\n return {\n ca: [cert],\n rejectUnauthorized: true,\n };\n }\n\n return true;\n}\n\nexport function streamConfigFromEnv(\n env: NodeJS.ProcessEnv = process.env,\n overrides: Partial<StreamConfig> = {},\n): StreamConfig {\n const rawBrokers = env['KAFKA_BROKERS'] ?? env['KAFKA_HOST'] ?? DEFAULT_BROKERS;\n const brokers = rawBrokers\n .split(',')\n .map((broker) => broker.trim())\n .filter((broker) => broker.length > 0);\n\n if (brokers.length === 0) {\n throw new Error('KAFKA_BROKERS is set but lists no broker address.');\n }\n\n const sasl = saslFromEnv(env);\n const ssl = overrides.ssl !== undefined ? overrides.ssl : resolveSsl(env, brokers, sasl !== null);\n\n const merged: StreamConfig = {\n brokers,\n clientId: env['KAFKA_CLIENT_ID'] ?? 'luxray',\n ssl,\n sasl,\n connectionTimeoutMs: 5_000,\n retryCount: 2,\n topicPartitions: positiveInt(env['KAFKA_TOPIC_PARTITIONS'], 3, 'KAFKA_TOPIC_PARTITIONS'),\n replicationFactor: positiveInt(\n env['KAFKA_REPLICATION_FACTOR'],\n 1,\n 'KAFKA_REPLICATION_FACTOR',\n ),\n ...overrides,\n };\n\n // A retry count of zero is rejected by kafkajs whenever the producer is\n // idempotent, which it always is here.\n return { ...merged, retryCount: Math.max(1, merged.retryCount) };\n}\n\nfunction saslFromEnv(env: NodeJS.ProcessEnv): StreamSaslConfig | null {\n const username = env['KAFKA_SASL_USERNAME'] ?? env['KAFKA_USER'] ?? env['KAFKA_USERNAME'];\n const password = env['KAFKA_SASL_PASSWORD'] ?? env['KAFKA_PASS'] ?? env['KAFKA_PASSWORD'];\n if (!username || !password) return null;\n\n const raw = (env['KAFKA_SASL_MECHANISM'] ?? 'scram-sha-512').toLowerCase();\n if (raw !== 'plain' && raw !== 'scram-sha-256' && raw !== 'scram-sha-512') {\n throw new Error(\n `KAFKA_SASL_MECHANISM must be plain, scram-sha-256 or scram-sha-512 (got ${raw}).`,\n );\n }\n return { mechanism: raw, username, password };\n}\n\n/** Parses a positive integer setting, naming the variable in the error. */\nfunction positiveInt(raw: string | undefined, fallback: number, name: string): number {\n if (raw === undefined || raw.trim() === '') return fallback;\n const value = Number(raw);\n if (!Number.isInteger(value) || value < 1) {\n throw new Error(`${name} must be a positive integer (got \"${raw}\").`);\n }\n return value;\n}\n\n/** One error message for both processes, naming the thing to fix. */\nexport function unavailableError(config: StreamConfig, cause: unknown): StreamUnavailableError {\n const detail = cause instanceof Error ? cause.message : String(cause);\n return new StreamUnavailableError(\n `Kafka is not reachable at ${config.brokers.join(', ')} (${detail}). ` +\n 'Start it with `docker compose up -d kafka`, or point KAFKA_BROKERS at a broker.',\n config.brokers,\n cause,\n );\n}\n","/** Raised when the broker cannot be reached or refuses the connection. */\nexport class StreamUnavailableError extends Error {\n public override readonly name = 'StreamUnavailableError';\n\n constructor(\n message: string,\n public readonly brokers: readonly string[],\n public override readonly cause?: unknown,\n ) {\n super(message);\n }\n}\n\n/** Raised when a record is not a valid envelope. Never inferred as meaning. */\nexport class StreamProtocolError extends Error {\n public override readonly name = 'StreamProtocolError';\n}\n","import type { StreamEnvelope, StreamKind } from '@luxray/shared';\nimport { StreamProtocolError } from './errors.js';\n\nconst KINDS: readonly StreamKind[] = ['task', 'report', 'event', 'result'];\n\nexport function encodeEnvelope<T>(envelope: StreamEnvelope<T>): string {\n return JSON.stringify(envelope);\n}\n\n/**\n * Parses one record.\n *\n * A malformed record is a protocol error, never a partially usable message:\n * acting on half an offer would be worse than dropping it, because the durable\n * offer stays in the task row and is replayed on the next connection.\n *\n * `expected` may name several kinds when a topic deliberately carries more than\n * one. Page results share the report topic so a task's pages and its completion\n * stay in one partition order; the caller dispatches on the returned kind.\n */\nexport function decodeEnvelope<T>(\n raw: string,\n expected?: StreamKind | readonly StreamKind[],\n): StreamEnvelope<T> {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (error) {\n throw new StreamProtocolError(`Record is not JSON: ${(error as Error).message}`);\n }\n\n if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {\n throw new StreamProtocolError('Record is not an object.');\n }\n\n const record = parsed as Record<string, unknown>;\n if (record['envelope'] !== 1) {\n throw new StreamProtocolError(`Unsupported envelope version: ${String(record['envelope'])}.`);\n }\n\n const kind = record['kind'];\n if (typeof kind !== 'string' || !KINDS.includes(kind as StreamKind)) {\n throw new StreamProtocolError(`Unknown stream kind: ${String(kind)}.`);\n }\n if (expected !== undefined) {\n const allowed = typeof expected === 'string' ? [expected] : expected;\n if (!allowed.includes(kind as StreamKind)) {\n throw new StreamProtocolError(\n `Expected a ${allowed.join(' or ')} record, got ${kind}.`,\n );\n }\n }\n\n const agentId = record['agentId'];\n // Results and lifecycle events may concern an unassigned task, so only the\n // two directional streams require a producer identity.\n if (typeof agentId !== 'string') {\n throw new StreamProtocolError('Envelope has no agentId.');\n }\n if ((kind === 'task' || kind === 'report') && agentId.length === 0) {\n throw new StreamProtocolError('Envelope has no agentId.');\n }\n\n const workspaceId = record['workspaceId'];\n if (typeof workspaceId !== 'string' || workspaceId.length === 0) {\n throw new StreamProtocolError('Envelope has no workspaceId.');\n }\n\n const sentAt = record['sentAt'];\n if (typeof sentAt !== 'number' || !Number.isFinite(sentAt)) {\n throw new StreamProtocolError('Envelope has no sentAt.');\n }\n\n const payload = record['payload'];\n if (payload === null || typeof payload !== 'object') {\n throw new StreamProtocolError('Envelope has no payload.');\n }\n\n return {\n envelope: 1,\n kind: kind as StreamKind,\n agentId,\n workspaceId,\n sentAt,\n payload: payload as T,\n };\n}\n","import { Kafka, logLevel, type Consumer, type Producer, type SASLOptions } from 'kafkajs';\nimport type { StreamConfig } from './config.js';\nimport { unavailableError } from './config.js';\nimport { StreamProtocolError, StreamUnavailableError } from './errors.js';\nexport interface StreamLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/** One record as consumers receive it. */\nexport interface StreamMessage {\n readonly key: string | null;\n readonly value: string;\n}\n\nexport interface StreamPublisher {\n connect(): Promise<void>;\n publish(topic: string, key: string, value: string): Promise<void>;\n /** Resolves once every accepted record has been acknowledged by the broker. */\n flush(): Promise<void>;\n disconnect(): Promise<void>;\n readonly publishedCount: number;\n readonly failedCount: number;\n}\n\nexport interface StreamSubscriber {\n connect(): Promise<void>;\n /**\n * Subscribes to `topics` and starts consuming. The handler is awaited, so a\n * throw leaves the offset uncommitted and the record is redelivered: every\n * handler must therefore be idempotent (the task service already is).\n */\n subscribe(\n topics: readonly string[],\n handler: (message: StreamMessage) => Promise<void>,\n ): Promise<void>;\n disconnect(): Promise<void>;\n readonly handledCount: number;\n readonly skippedCount: number;\n}\n\nfunction saslOptions(config: StreamConfig): SASLOptions | undefined {\n if (!config.sasl) return undefined;\n return {\n mechanism: config.sasl.mechanism,\n username: config.sasl.username,\n password: config.sasl.password,\n };\n}\n\nfunction createKafka(config: StreamConfig): Kafka {\n return new Kafka({\n clientId: config.clientId,\n brokers: [...config.brokers],\n ssl: config.ssl || undefined,\n sasl: saslOptions(config),\n connectionTimeout: config.connectionTimeoutMs,\n retry: { retries: config.retryCount, initialRetryTime: 300 },\n logLevel: logLevel.ERROR,\n });\n}\n\n/**\n * Creates the stream topics if the broker does not have them yet.\n *\n * Subscribing to a missing topic would make metadata refresh race the broker's\n * auto-creation, which surfaces as a transient `REPLICA_NOT_AVAILABLE` and\n * aborts startup. Creating the topics first, and waiting for their leaders, makes\n * the first subscribe deterministic on a fresh broker. Existing topics are left\n * untouched, including their partition count.\n *\n * Existing topics are filtered out before the create call: asking the broker to\n * create a topic that already exists is answered with a per-topic error, which\n * kafkajs reports at ERROR level. That noise on every restart trains operators\n * to ignore the stream logs, so the check is done here instead.\n */\nexport async function ensureTopics(\n config: StreamConfig,\n topics: readonly string[],\n logger?: StreamLogger,\n): Promise<void> {\n const admin = createKafka(config).admin();\n try {\n await admin.connect();\n } catch (error) {\n await admin.disconnect().catch(() => {});\n throw unavailableError(config, error);\n }\n\n try {\n const existing = new Set(await admin.listTopics());\n const missing = topics.filter((topic) => !existing.has(topic));\n if (missing.length === 0) return;\n\n const partitions = config.topicPartitions ?? 3;\n const replicationFactor = config.replicationFactor ?? 1;\n await admin.createTopics({\n topics: missing.map((topic) => ({\n topic,\n numPartitions: partitions,\n replicationFactor,\n })),\n waitForLeaders: true,\n });\n logger?.info(\n `Created stream topics: ${missing.join(', ')} ` +\n `(${partitions} partition(s), replication ${replicationFactor}).`,\n );\n } catch (error) {\n throw new StreamUnavailableError(\n `Could not create the stream topics (${topics.join(', ')}): ${(error as Error).message}`,\n config.brokers,\n error,\n );\n } finally {\n await admin.disconnect().catch(() => {});\n }\n}\n\n/**\n * Ordered, at-least-once producer.\n *\n * Sends are chained rather than fired in parallel so the broker sees one\n * agent's frames in the order they were produced. `acks: -1` means the promise\n * resolves only after every in-sync replica has the record, which is what makes\n * `flush()` a real guarantee before the process exits.\n */\nexport class KafkaPublisher implements StreamPublisher {\n private producer: Producer | null = null;\n private tail: Promise<void> = Promise.resolve();\n private sent = 0;\n private failed = 0;\n\n constructor(\n private readonly config: StreamConfig,\n private readonly logger?: StreamLogger,\n ) {}\n\n public get publishedCount(): number {\n return this.sent;\n }\n\n public get failedCount(): number {\n return this.failed;\n }\n\n public async connect(): Promise<void> {\n if (this.producer) return;\n const kafka = createKafka(this.config);\n try {\n const producer = kafka.producer({ allowAutoTopicCreation: true, idempotent: true });\n await producer.connect();\n this.producer = producer;\n } catch (error) {\n throw unavailableError(this.config, error);\n }\n this.logger?.debug(`Kafka producer connected to ${this.config.brokers.join(', ')}.`);\n }\n\n public publish(topic: string, key: string, value: string): Promise<void> {\n const producer = this.producer;\n if (!producer) {\n return Promise.reject(\n new StreamUnavailableError(\n 'The Kafka producer is not connected.',\n this.config.brokers,\n ),\n );\n }\n\n const send = this.tail.then(() =>\n producer.send({ topic, acks: -1, messages: [{ key, value }] }),\n );\n const settled = send.then(\n () => {\n this.sent += 1;\n },\n (error: unknown) => {\n this.failed += 1;\n this.logger?.error(\n `Could not publish to ${topic}: ${(error as Error).message}`,\n );\n throw error;\n },\n );\n // The chain must survive a failed send, or one broker hiccup would stall\n // every later record.\n this.tail = settled.catch(() => {});\n return settled;\n }\n\n public async flush(): Promise<void> {\n await this.tail;\n }\n\n public async disconnect(): Promise<void> {\n const producer = this.producer;\n this.producer = null;\n if (!producer) return;\n await this.tail.catch(() => {});\n await producer.disconnect().catch(() => {});\n }\n}\n\n/**\n * Consumer for one group.\n *\n * A poison record (bad envelope) is logged and skipped; anything else throws, so\n * the offset stays put and the record is retried. That is the only split where\n * at-least-once is safe: malformed input can never become authority, and valid\n * input is idempotent downstream.\n */\nexport class KafkaSubscriber implements StreamSubscriber {\n private consumer: Consumer | null = null;\n private started = false;\n private handled = 0;\n private skipped = 0;\n\n constructor(\n private readonly config: StreamConfig,\n private readonly groupId: string,\n private readonly options?: {\n readonly fromBeginning?: boolean;\n readonly logger?: StreamLogger;\n },\n ) {}\n\n public get handledCount(): number {\n return this.handled;\n }\n\n public get skippedCount(): number {\n return this.skipped;\n }\n\n public async connect(): Promise<void> {\n if (this.consumer) return;\n const kafka = createKafka(this.config);\n const consumer = kafka.consumer({\n groupId: this.groupId,\n sessionTimeout: 30_000,\n heartbeatInterval: 3_000,\n });\n try {\n await consumer.connect();\n } catch (error) {\n await consumer.disconnect().catch(() => {});\n throw unavailableError(this.config, error);\n }\n this.consumer = consumer;\n this.options?.logger?.debug(\n `Kafka consumer ${this.groupId} connected to ${this.config.brokers.join(', ')}.`,\n );\n }\n\n public async subscribe(\n topics: readonly string[],\n handler: (message: StreamMessage) => Promise<void>,\n ): Promise<void> {\n const consumer = this.consumer;\n if (!consumer) {\n throw new StreamUnavailableError(\n `Kafka consumer ${this.groupId} is not connected.`,\n this.config.brokers,\n );\n }\n if (this.started) {\n throw new Error(`Kafka consumer ${this.groupId} is already running.`);\n }\n\n const fromBeginning = this.options?.fromBeginning ?? false;\n for (const topic of topics) {\n await consumer.subscribe({ topic, fromBeginning });\n }\n\n await consumer.run({\n autoCommit: true,\n partitionsConsumedConcurrently: 1,\n eachMessage: async ({ topic, message }) => {\n if (!message.value) return;\n try {\n await handler({\n key: message.key ? message.key.toString() : null,\n value: message.value.toString(),\n });\n this.handled += 1;\n } catch (error) {\n if (error instanceof StreamProtocolError) {\n this.skipped += 1;\n this.options?.logger?.warn(\n `Skipping a malformed record on ${topic}: ${error.message}`,\n );\n return;\n }\n throw error;\n }\n },\n });\n this.started = true;\n }\n\n public async disconnect(): Promise<void> {\n const consumer = this.consumer;\n this.consumer = null;\n this.started = false;\n if (!consumer) return;\n await consumer.disconnect().catch(() => {});\n }\n}\n","/**\n * Topic names and partition keys.\n *\n * One topic per direction rather than one per agent: a topic per agent is\n * unbounded topic creation on a broker that is supposed to be boring. Ordering\n * is preserved per key instead, which is all the protocol needs:\n *\n * - commands are keyed by agent, so one agent's offers arrive in order;\n * - reports are keyed by task, so one task's pages, ack, progress and completion\n * arrive in order even when several agents report concurrently;\n * - results are keyed by task, for the same reason.\n */\nexport const STREAM_TOPICS = {\n /** Server to agent: offers, control frames, lease renewals, nacks. */\n commands: 'luxray.agent.commands',\n /**\n * Agent to server: page observations and acks/progress/checkpoints/completion.\n *\n * Pages share this topic with commands on purpose. Keyed by task, they land in\n * one partition, so the control plane applies every page before the report\n * that closes the same attempt. A `report` record always follows this order.\n */\n reports: 'luxray.agent.reports',\n /** Server to subscribers: durable lifecycle events, mirrored for consumers. */\n events: 'luxray.tasks.events',\n /** Server to subscribers: page observations, mirrored after they persist. */\n results: 'luxray.crawl.results',\n} as const;\n\nexport type StreamTopic = (typeof STREAM_TOPICS)[keyof typeof STREAM_TOPICS];\n\n/**\n * Every stream topic, in the order a fresh broker should be given them.\n *\n * Consumers create topics explicitly before subscribing: subscribing to a topic\n * that does not exist yet makes metadata refresh race topic creation, and a\n * control plane must not fail to start on that transient.\n */\nexport const STREAM_TOPIC_LIST: readonly StreamTopic[] = [\n STREAM_TOPICS.commands,\n STREAM_TOPICS.reports,\n STREAM_TOPICS.results,\n STREAM_TOPICS.events,\n];\n\n/** Each agent is its own consumer group, so it sees only its own commands. */\nexport function agentConsumerGroup(agentId: string): string {\n return `luxray-agent-${agentId}`;\n}\n\n/** All API instances share a group: a report is applied exactly once. */\nexport const API_REPORTS_GROUP = 'luxray-api-reports';\nexport const API_RESULTS_GROUP = 'luxray-api-results';\n","import type {\n AgentTaskCancelMessage,\n AgentTaskClientMessage,\n AgentTaskNackMessage,\n AgentTaskOfferMessage,\n AgentTaskPauseMessage,\n AgentTaskRenewedMessage,\n AgentTaskServerMessage,\n CrawlPageResult,\n StreamEnvelope,\n} from '@luxray/shared';\nimport {\n KafkaPublisher,\n KafkaSubscriber,\n STREAM_TOPICS,\n agentConsumerGroup,\n decodeEnvelope,\n encodeEnvelope,\n ensureTopics,\n type StreamConfig,\n type StreamMessage,\n type StreamPublisher,\n type StreamSubscriber,\n} from '@luxray/streaming';\n\nexport interface TaskStreamLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/**\n * Receives the commands addressed to this agent.\n *\n * Handlers are synchronous by design: the executor's decisions (ack, run, stop)\n * are decisions about local state, and a Kafka handler that awaits a long job\n * would stall the partition behind it.\n */\nexport interface TaskStreamHandlers {\n readonly onOffer: (message: AgentTaskOfferMessage) => void;\n readonly onCancel: (message: AgentTaskCancelMessage) => void;\n readonly onPause: (message: AgentTaskPauseMessage) => void;\n readonly onRenewed: (message: AgentTaskRenewedMessage) => void;\n readonly onNack: (message: AgentTaskNackMessage) => void;\n}\n\nexport interface TaskStreamOptions {\n readonly config: StreamConfig;\n readonly agentId: string;\n readonly workspaceId: string;\n readonly handlers: TaskStreamHandlers;\n readonly logger?: TaskStreamLogger;\n /** Injected in tests so the stream can be exercised without a broker. */\n readonly publisher?: StreamPublisher;\n readonly subscriber?: StreamSubscriber;\n /** Injected in tests; the default creates the topics on the real broker. */\n readonly ensureTopics?: (config: StreamConfig) => Promise<void>;\n}\n\n/**\n * The agent's side of the Kafka transport.\n *\n * Reports and page results leave through the publisher; commands arrive on a\n * consumer group private to this agent. The group is what makes an offer\n * durable: a command produced while the agent is offline is still there when it\n * reconnects, whereas the old socket could only replay what the control plane\n * remembered to resend.\n */\nexport class TaskStream {\n private readonly publisher: StreamPublisher;\n private readonly subscriber: StreamSubscriber;\n private readonly handlers: TaskStreamHandlers;\n private readonly logger: TaskStreamLogger;\n private readonly prepareTopics: (config: StreamConfig) => Promise<void>;\n private connected = false;\n\n constructor(private readonly options: TaskStreamOptions) {\n this.publisher =\n options.publisher ?? new KafkaPublisher(options.config, options.logger);\n this.subscriber =\n options.subscriber ??\n new KafkaSubscriber(options.config, agentConsumerGroup(options.agentId), {\n fromBeginning: true,\n logger: options.logger,\n });\n this.handlers = options.handlers;\n this.prepareTopics =\n options.ensureTopics ??\n ((config) =>\n ensureTopics(config, [\n STREAM_TOPICS.commands,\n STREAM_TOPICS.reports,\n STREAM_TOPICS.results,\n ]));\n this.logger = options.logger ?? {\n info: () => {},\n warn: (...args: unknown[]) => console.warn(...args),\n error: (...args: unknown[]) => console.error(...args),\n debug: () => {},\n };\n }\n\n public get isConnected(): boolean {\n return this.connected;\n }\n\n public get publishedCount(): number {\n return this.publisher.publishedCount;\n }\n\n /**\n * Connects both sides before anything is produced.\n *\n * The subscriber connects first in spirit as well as in order: a command\n * published between \"agent is online\" and \"agent is consuming\" would still be\n * delivered later, but a producer that is not connected silently rejects\n * every report it is handed.\n */\n public async connect(): Promise<void> {\n if (this.connected) return;\n await this.subscriber.connect();\n try {\n await this.publisher.connect();\n // A fresh broker has no topics; creating them before subscribing avoids\n // the metadata race that would otherwise look like an unavailable broker.\n await this.prepareTopics(this.options.config);\n await this.subscriber.subscribe([STREAM_TOPICS.commands], (message) =>\n this.receive(message),\n );\n } catch (error) {\n await this.subscriber.disconnect().catch(() => {});\n await this.publisher.disconnect().catch(() => {});\n throw error;\n }\n this.connected = true;\n }\n\n /**\n * Publishes one execution report.\n *\n * Returns false when the stream is not connected, which the executor already\n * treats as a transient gap. A publish failure after acceptance is logged,\n * not thrown: the lease will expire and the control plane will reclaim the\n * task, which is the same outcome as a socket write that never arrived.\n */\n public report(message: AgentTaskClientMessage): boolean {\n if (!this.connected) return false;\n\n const envelope: StreamEnvelope<AgentTaskClientMessage> = {\n envelope: 1,\n kind: 'report',\n agentId: this.options.agentId,\n workspaceId: this.options.workspaceId,\n sentAt: Date.now(),\n payload: message,\n };\n\n // Keyed by task: one task's ack/progress/complete stay in order even when\n // several jobs on this agent publish at once.\n void this.publisher\n .publish(STREAM_TOPICS.reports, message.taskId, encodeEnvelope(envelope))\n .catch((error: unknown) => {\n this.logger.error(\n `Could not publish ${message.type} for task ${message.taskId}: ${(error as Error).message}`,\n );\n });\n return true;\n }\n\n /**\n * Streams one observed page while the crawl is still running.\n *\n * Pages share the topic with reports and are keyed by task, so the completion\n * that follows them lands in the same partition and can never overtake them.\n */\n public publishPage(page: CrawlPageResult): boolean {\n if (!this.connected) return false;\n\n const envelope: StreamEnvelope<CrawlPageResult> = {\n envelope: 1,\n kind: 'result',\n agentId: this.options.agentId,\n workspaceId: this.options.workspaceId,\n sentAt: Date.now(),\n payload: page,\n };\n\n void this.publisher\n .publish(STREAM_TOPICS.reports, page.taskId, encodeEnvelope(envelope))\n .catch((error: unknown) => {\n this.logger.warn(\n `Could not publish page ${page.sequence} of task ${page.taskId}: ${(error as Error).message}`,\n );\n });\n return true;\n }\n\n /** Waits until every accepted record was acknowledged by the broker. */\n public async flush(): Promise<void> {\n await this.publisher.flush();\n }\n\n public async close(): Promise<void> {\n if (!this.connected) {\n await this.publisher.disconnect().catch(() => {});\n await this.subscriber.disconnect().catch(() => {});\n return;\n }\n this.connected = false;\n // Flush before disconnecting, or a completion queued during shutdown is\n // dropped and the task sits RUNNING until its lease expires.\n await this.flush().catch((error: unknown) => {\n this.logger.error(`Could not flush the task stream: ${(error as Error).message}`);\n });\n await this.subscriber.disconnect();\n await this.publisher.disconnect();\n }\n\n private async receive(message: StreamMessage): Promise<void> {\n const envelope = decodeEnvelope<AgentTaskServerMessage>(message.value, 'task');\n\n // The group is private to this agent, so a foreign envelope means a\n // misconfigured producer, not a message for us. Ignoring it is safer than\n // executing a task this agent was never assigned.\n if (envelope.agentId !== this.options.agentId) {\n this.logger.warn(\n `Ignoring a ${envelope.payload.type} record addressed to agent ${envelope.agentId}.`,\n );\n return;\n }\n\n const payload = envelope.payload;\n switch (payload.type) {\n case 'task.offer':\n this.handlers.onOffer(payload);\n return;\n case 'task.cancel':\n this.handlers.onCancel(payload);\n return;\n case 'task.pause':\n this.handlers.onPause(payload);\n return;\n case 'task.renewed':\n this.handlers.onRenewed(payload);\n return;\n case 'task.nack':\n this.handlers.onNack(payload);\n return;\n default: {\n // A newer server may send a command this build does not know. Retrying\n // it would block every later command on this agent's partition, and it\n // can never succeed, so it is logged and dropped. The durable task row\n // is unaffected; the lease sweep is the backstop.\n const unknown = payload as { type?: unknown };\n this.logger.warn(`Ignoring an unknown task command: ${String(unknown.type)}.`);\n return;\n }\n }\n }\n}\n","/**\n * Deterministic test job executed by the M3 agent.\n *\n * It intentionally touches no network and no browser. Its purpose is to prove\n * the execution pipeline end-to-end: lease acknowledgement, progress, durable\n * checkpoints, cancellation, timeout and completion reporting. Real browser\n * exploration arrives with the isolated worker in M4.\n */\n\nexport interface TestJobContext {\n readonly signal: AbortSignal;\n readonly reportProgress: (percent: number, message: string) => void;\n readonly checkpoint: (label: string, state: Record<string, unknown>) => void;\n readonly sleep: (ms: number) => Promise<void>;\n}\n\nexport interface TestJobResult {\n readonly steps: number;\n readonly completedSteps: number;\n readonly durationMs: number;\n}\n\nexport interface TestJobOptions {\n readonly steps?: number;\n readonly stepDelayMs?: number;\n}\n\nexport const DEFAULT_TEST_JOB_STEPS = 5;\nexport const DEFAULT_TEST_STEP_DELAY_MS = 200;\n\nfunction throwIfAborted(signal: AbortSignal): void {\n if (!signal.aborted) return;\n const error = new Error('Job aborted.');\n error.name = 'AbortError';\n throw error;\n}\n\n/**\n * Runs a fixed number of steps with deterministic progress. The checkpoint is\n * written once, in the middle, so recovery has a meaningful recovery point\n * without pretending the job has real state to restore.\n */\nexport async function runTestJob(\n context: TestJobContext,\n options: TestJobOptions = {},\n): Promise<TestJobResult> {\n const steps = Math.max(1, options.steps ?? DEFAULT_TEST_JOB_STEPS);\n const stepDelayMs = Math.max(0, options.stepDelayMs ?? DEFAULT_TEST_STEP_DELAY_MS);\n const startedAt = Date.now();\n let completedSteps = 0;\n\n for (let step = 1; step <= steps; step++) {\n throwIfAborted(context.signal);\n\n await context.sleep(stepDelayMs);\n throwIfAborted(context.signal);\n\n completedSteps = step;\n const percent = Math.min(95, Math.round((step / steps) * 90));\n context.reportProgress(percent, `step ${step}/${steps}`);\n\n if (step === Math.ceil(steps / 2)) {\n context.checkpoint('test-job-halfway', {\n step,\n totalSteps: steps,\n completedSteps,\n });\n }\n }\n\n context.reportProgress(99, 'finalizing');\n return {\n steps,\n completedSteps,\n durationMs: Date.now() - startedAt,\n };\n}\n","import type {\n AgentTaskCancelMessage,\n AgentTaskCheckpointMessage,\n AgentTaskClientMessage,\n AgentTaskCompleteMessage,\n AgentTaskFailMessage,\n AgentTaskNackMessage,\n AgentTaskOfferMessage,\n AgentTaskPauseMessage,\n AgentTaskProgressMessage,\n AgentTaskRenewMessage,\n AgentTaskRenewedMessage,\n ExplorationOpenApiSpec,\n ExplorationReport,\n ExplorationTask,\n} from '@luxray/shared';\nimport { runTestJob } from './test-job.js';\n\nexport interface TaskExecutorLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/** What a job implementation may use while it runs. */\nexport interface JobExecutionContext {\n readonly signal: AbortSignal;\n readonly reportProgress: (percent: number, message: string) => void;\n readonly checkpoint: (label: string, state: Record<string, unknown>) => void;\n readonly sleep: (ms: number) => Promise<void>;\n}\n\n/**\n * What an exploration run hands back.\n *\n * The summary is free-form and lands in the task history; the report is the\n * typed outcome and rides in the completion frame, so the control plane stores\n * it atomically with the COMPLETED status.\n */\nexport interface ExplorationJobResult {\n readonly summary: Record<string, unknown>;\n readonly report: ExplorationReport;\n /**\n * Specifications generated from captured traffic, omitted when the crawl saw\n * no API traffic or the documents exceeded the transport budget.\n */\n readonly openApi?: ExplorationOpenApiSpec;\n}\n\n/**\n * Executes one `EXPLORATION` job. Injected rather than imported so the executor\n * keeps no browser dependency: the CLI supplies the isolated browser worker.\n */\nexport type ExplorationJobRunner = (\n execution: JobExecutionContext,\n task: ExplorationTask,\n) => Promise<ExplorationJobResult>;\n\nexport type JobOutcome = 'completed' | 'failed' | 'stopped';\n\n/** Result of waiting for a specific task to start executing locally. */\nexport type JobStartOutcome = 'started' | 'timeout';\n\n/** How a job ended, for callers that drive one task at a time. */\nexport interface JobFinishedInfo {\n readonly taskId: string;\n readonly leaseId: string;\n readonly jobType: string;\n readonly outcome: JobOutcome;\n readonly stopReason: StopReason | null;\n readonly error: string | null;\n}\n\nexport interface TaskExecutorOptions {\n readonly agentId: string;\n /** Transport sink. Returns false when the socket is not currently usable. */\n readonly send: (message: AgentTaskClientMessage) => boolean;\n /** Jobs this process will run at once. M3 defaults to a single job. */\n readonly maxConcurrentJobs?: number;\n /** Hard limit for one job; exceeding it fails the task. */\n readonly maxJobDurationMs?: number;\n /** Hard limit for one exploration job; browsers are slower than test jobs. */\n readonly explorationMaxDurationMs?: number;\n /** Minimum gap between progress frames. */\n readonly progressIntervalMs?: number;\n /** Overrides lease-based renewal interval. */\n readonly leaseRenewIntervalMs?: number;\n /** Largest checkpoint payload the transport will carry. */\n readonly checkpointMaxBytes?: number;\n /** Runs `EXPLORATION` offers. Without it, exploration fails honestly. */\n readonly explorationRunner?: ExplorationJobRunner;\n /** Fires exactly once per job, whatever the ending was. */\n readonly onJobFinished?: (info: JobFinishedInfo) => void;\n readonly testSteps?: number;\n readonly testStepDelayMs?: number;\n readonly now?: () => number;\n readonly logger?: TaskExecutorLogger;\n}\n\ntype StopReason = 'cancel' | 'pause' | 'superseded' | 'fenced' | 'timeout' | 'shutdown';\n\ninterface StartWaiter {\n readonly resolve: (outcome: JobStartOutcome) => void;\n timer: NodeJS.Timeout | null;\n}\n\ninterface ActiveJob {\n readonly key: string;\n readonly leaseId: string;\n readonly taskId: string;\n readonly offer: AgentTaskOfferMessage;\n readonly controller: AbortController;\n leaseExpiresAt: number;\n stopReason: StopReason | null;\n settled: boolean;\n outcome: JobOutcome | null;\n outcomeError: string | null;\n lastProgressAt: number;\n lastPercentSent: number;\n pendingProgress: { percent: number; message: string } | null;\n progressTimer: NodeJS.Timeout | null;\n renewTimer: NodeJS.Timeout | null;\n timeoutTimer: NodeJS.Timeout | null;\n}\n\nconst DEFAULT_MAX_CONCURRENT_JOBS = 1;\nconst DEFAULT_MAX_JOB_DURATION_MS = 120_000;\nconst DEFAULT_EXPLORATION_MAX_DURATION_MS = 10 * 60_000;\nconst DEFAULT_PROGRESS_INTERVAL_MS = 1_000;\nconst DEFAULT_CHECKPOINT_MAX_BYTES = 16 * 1024;\nconst MIN_RENEW_INTERVAL_MS = 1_000;\nconst MAX_RENEW_INTERVAL_MS = 60_000;\nconst MAX_ERROR_LENGTH = 2_000;\n\n/**\n * Owns local execution state for assigned jobs.\n *\n * The server is authoritative for leases and lifecycle. This class keeps only\n * what it needs to run work safely: a per-lease dedupe key, an abort signal,\n * throttled progress, and a renewal timer. It deliberately performs no\n * autonomous exploration.\n */\nexport class TaskExecutor {\n private readonly maxConcurrentJobs: number;\n private readonly maxJobDurationMs: number;\n private readonly explorationMaxDurationMs: number;\n private readonly progressIntervalMs: number;\n private readonly leaseRenewIntervalMs: number | null;\n private readonly checkpointMaxBytes: number;\n private readonly explorationRunner: ExplorationJobRunner | null;\n private readonly testSteps: number | undefined;\n private readonly testStepDelayMs: number | undefined;\n private readonly now: () => number;\n private readonly logger: TaskExecutorLogger;\n\n private readonly running = new Map<string, ActiveJob>();\n private readonly runs = new Map<string, Promise<void>>();\n private readonly queued: AgentTaskOfferMessage[] = [];\n /** Tasks this process has accepted a lease for, used by `waitForJobStarted`. */\n private readonly startedTaskIds = new Set<string>();\n private readonly startWaiters = new Map<string, StartWaiter[]>();\n private shuttingDown = false;\n\n constructor(private readonly options: TaskExecutorOptions) {\n this.maxConcurrentJobs = clampInt(options.maxConcurrentJobs ?? DEFAULT_MAX_CONCURRENT_JOBS, 1, 16);\n this.maxJobDurationMs = Math.max(1, options.maxJobDurationMs ?? DEFAULT_MAX_JOB_DURATION_MS);\n this.explorationMaxDurationMs = Math.max(\n 1,\n options.explorationMaxDurationMs ?? DEFAULT_EXPLORATION_MAX_DURATION_MS,\n );\n this.progressIntervalMs = Math.max(0, options.progressIntervalMs ?? DEFAULT_PROGRESS_INTERVAL_MS);\n this.leaseRenewIntervalMs = options.leaseRenewIntervalMs ?? null;\n this.checkpointMaxBytes = Math.max(\n 256,\n options.checkpointMaxBytes ?? DEFAULT_CHECKPOINT_MAX_BYTES,\n );\n this.explorationRunner = options.explorationRunner ?? null;\n this.testSteps = options.testSteps;\n this.testStepDelayMs = options.testStepDelayMs;\n this.now = options.now ?? Date.now;\n this.logger = options.logger ?? {\n info: (...args) => console.log('[TaskExecutor]', ...args),\n warn: (...args) => console.warn('[TaskExecutor:WARN]', ...args),\n error: (...args) => console.error('[TaskExecutor:ERROR]', ...args),\n debug: () => {},\n };\n }\n\n public getRunningJobCount(): number {\n return this.running.size;\n }\n\n public getQueuedJobCount(): number {\n return this.queued.length;\n }\n\n /**\n * Resolves once this process has begun executing `taskId`, or with\n * `'timeout'` when no offer arrives within `timeoutMs`.\n *\n * This bounds the handoff only, never the work: a crawl of a heavy site\n * legitimately takes minutes, and its own limits decide when to give up. The\n * already-started set is checked first because an offer can be acknowledged\n * before the caller learns the task id, so a bare timer would race.\n */\n public waitForJobStarted(taskId: string, timeoutMs: number): Promise<JobStartOutcome> {\n if (this.startedTaskIds.has(taskId)) return Promise.resolve('started');\n\n return new Promise<JobStartOutcome>((resolve) => {\n const waiter: StartWaiter = { resolve, timer: null };\n waiter.timer = setTimeout(\n () => this.settleStartWaiter(taskId, waiter, 'timeout'),\n Math.max(0, timeoutMs),\n );\n waiter.timer.unref?.();\n\n const waiters = this.startWaiters.get(taskId) ?? [];\n waiters.push(waiter);\n this.startWaiters.set(taskId, waiters);\n });\n }\n\n /** Accepts an offer. Duplicate offers for the same lease are acknowledged twice. */\n public handleOffer(offer: AgentTaskOfferMessage): void {\n if (this.shuttingDown) return;\n\n if (offer.leaseExpiresAt <= this.now()) {\n this.logger.warn(\n `Ignoring expired offer for task ${offer.task.id} (lease ${offer.leaseId}).`,\n );\n return;\n }\n\n const key = this.jobKey(offer.task.id, offer.leaseId);\n const existing = this.running.get(key);\n if (existing) {\n // At-least-once delivery after a reconnect: acknowledge again, never run\n // the same lease twice in this process.\n this.sendAck(offer);\n return;\n }\n\n if (this.queued.some((entry) => this.jobKey(entry.task.id, entry.leaseId) === key)) {\n return;\n }\n\n if (this.running.size >= this.maxConcurrentJobs) {\n this.queued.push(offer);\n this.logger.info(\n `Queued task ${offer.task.id}; ${this.running.size}/${this.maxConcurrentJobs} jobs active.`,\n );\n return;\n }\n\n this.start(offer);\n }\n\n public handleCancel(message: AgentTaskCancelMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId !== message.taskId) continue;\n if (message.leaseId !== null && message.leaseId !== job.leaseId) continue;\n this.stop(job, 'cancel');\n }\n }\n\n public handlePause(message: AgentTaskPauseMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId === message.taskId) this.stop(job, 'pause');\n }\n }\n\n public handleNack(message: AgentTaskNackMessage): void {\n // A retryable rejection is a transient action failure; keep executing and\n // let the next progress frame or renewal retry. Fencing is final.\n if (message.retryable) {\n this.logger.debug(\n `Task ${message.taskId}: ${message.code} — ${message.message} (retryable, still running).`,\n );\n return;\n }\n\n this.logger.warn(\n `Task ${message.taskId} rejected by the control plane: ${message.code} — ${message.message}`,\n );\n\n for (const job of this.running.values()) {\n if (job.taskId !== message.taskId) continue;\n if (message.leaseId !== null && message.leaseId !== job.leaseId) continue;\n this.stop(job, 'fenced');\n }\n }\n\n public handleRenewed(message: AgentTaskRenewedMessage): void {\n for (const job of this.running.values()) {\n if (job.taskId === message.taskId && job.leaseId === message.leaseId) {\n job.leaseExpiresAt = message.leaseExpiresAt;\n }\n }\n }\n\n /**\n * Fails every in-flight job with an operator-supplied reason, then stops it.\n *\n * `shutdown()` alone leaves the server to reclaim the task when the lease\n * expires, which is right for an abrupt exit but wrong for Ctrl+C: the\n * operator deliberately stopped the run, and the task history should say so\n * immediately instead of waiting out the lease.\n */\n public failActiveJobs(reason: string): void {\n for (const job of [...this.running.values()]) {\n if (job.settled) continue;\n this.sendFailure(job, reason);\n this.stop(job, 'shutdown');\n }\n }\n\n /** Stops everything and waits for in-flight jobs to unwind. */\n public async shutdown(): Promise<void> {\n this.shuttingDown = true;\n this.queued.length = 0;\n\n for (const job of [...this.running.values()]) {\n this.stop(job, 'shutdown');\n }\n\n await Promise.allSettled([...this.runs.values()]);\n }\n\n /** Records a start and wakes anyone watching for this task. */\n private noteJobStarted(taskId: string): void {\n this.startedTaskIds.add(taskId);\n\n const waiters = this.startWaiters.get(taskId);\n if (!waiters) return;\n this.startWaiters.delete(taskId);\n\n for (const waiter of waiters) {\n if (waiter.timer) {\n clearTimeout(waiter.timer);\n waiter.timer = null;\n }\n waiter.resolve('started');\n }\n }\n\n private settleStartWaiter(\n taskId: string,\n waiter: StartWaiter,\n outcome: JobStartOutcome,\n ): void {\n if (waiter.timer) {\n clearTimeout(waiter.timer);\n waiter.timer = null;\n }\n\n const waiters = this.startWaiters.get(taskId);\n if (waiters) {\n const index = waiters.indexOf(waiter);\n if (index >= 0) waiters.splice(index, 1);\n if (waiters.length === 0) this.startWaiters.delete(taskId);\n }\n\n waiter.resolve(outcome);\n }\n\n private start(offer: AgentTaskOfferMessage): void {\n const job: ActiveJob = {\n key: this.jobKey(offer.task.id, offer.leaseId),\n leaseId: offer.leaseId,\n taskId: offer.task.id,\n offer,\n controller: new AbortController(),\n leaseExpiresAt: offer.leaseExpiresAt,\n stopReason: null,\n settled: false,\n outcome: null,\n outcomeError: null,\n lastProgressAt: 0,\n lastPercentSent: 0,\n pendingProgress: null,\n progressTimer: null,\n renewTimer: null,\n timeoutTimer: null,\n };\n\n this.running.set(job.key, job);\n this.noteJobStarted(job.taskId);\n this.sendAck(offer);\n this.startRenewal(job);\n\n job.timeoutTimer = setTimeout(() => {\n this.stop(job, 'timeout');\n }, this.jobDurationLimitMs(offer.task.jobType));\n job.timeoutTimer.unref?.();\n\n this.logger.info(\n `Starting ${offer.task.jobType} task ${offer.task.id} (lease ${offer.leaseId}, attempt ${offer.attempt}).`,\n );\n\n const run = this.execute(job).finally(() => {\n this.settle(job);\n });\n this.runs.set(job.key, run);\n }\n\n private async execute(job: ActiveJob): Promise<void> {\n try {\n const jobType = job.offer.task.jobType;\n\n if (jobType === 'TEST') {\n const result = await runTestJob(this.jobContext(job), {\n steps: this.testSteps,\n stepDelayMs: this.testStepDelayMs,\n });\n\n if (job.stopReason !== null) return;\n\n this.sendCompletion(job, {\n jobType,\n steps: result.steps,\n completedSteps: result.completedSteps,\n durationMs: result.durationMs,\n });\n this.logger.info(`Task ${job.taskId} completed in ${result.durationMs}ms.`);\n return;\n }\n\n if (jobType === 'EXPLORATION') {\n if (!this.explorationRunner) {\n this.sendFailure(\n job,\n 'This agent build has no exploration runner installed, so it cannot execute EXPLORATION jobs.',\n );\n return;\n }\n\n const startedAt = this.now();\n const { summary, report, openApi } = await this.explorationRunner(\n this.jobContext(job),\n job.offer.task,\n );\n if (job.stopReason !== null) return;\n\n this.sendCompletion(\n job,\n {\n jobType,\n durationMs: this.now() - startedAt,\n ...summary,\n },\n report,\n openApi,\n );\n this.logger.info(\n `Exploration task ${job.taskId} completed in ${this.now() - startedAt}ms.`,\n );\n return;\n }\n\n this.sendFailure(\n job,\n `Job type ${String(jobType)} is not executable by this agent build.`,\n );\n } catch (err) {\n if (job.stopReason === 'timeout') {\n this.sendFailure(\n job,\n `Job exceeded the local ${this.jobDurationLimitMs(job.offer.task.jobType)}ms execution limit.`,\n );\n return;\n }\n if (job.stopReason !== null || job.controller.signal.aborted) {\n this.logger.debug(`Task ${job.taskId} stopped (${job.stopReason ?? 'aborted'}).`);\n return;\n }\n this.sendFailure(job, this.errorMessage(err));\n }\n }\n\n private sendCompletion(\n job: ActiveJob,\n summary: Record<string, unknown>,\n report?: ExplorationReport,\n openApi?: ExplorationOpenApiSpec,\n ): void {\n const message: AgentTaskCompleteMessage = {\n ...this.base(),\n type: 'task.complete',\n taskId: job.taskId,\n leaseId: job.leaseId,\n summary,\n ...(report ? { report } : {}),\n ...(openApi ? { openApi } : {}),\n };\n if (!this.send(message)) {\n // Silently claiming success while the report never left the process is\n // the worst possible failure mode; make it visible.\n this.logger.warn(\n `Could not report completion for task ${job.taskId}: the transport is closed. ` +\n 'The lease will expire and the queue will decide what happens next.',\n );\n }\n if (job.outcome === null) job.outcome = 'completed';\n }\n\n private jobDurationLimitMs(jobType: string): number {\n return jobType === 'EXPLORATION' ? this.explorationMaxDurationMs : this.maxJobDurationMs;\n }\n\n private jobContext(job: ActiveJob): JobExecutionContext {\n return {\n signal: job.controller.signal,\n reportProgress: (percent, message) => this.reportProgress(job, percent, message),\n checkpoint: (label, state) => this.reportCheckpoint(job, label, state),\n sleep: (ms) => this.sleep(ms, job.controller.signal),\n };\n }\n\n /** Abortable delay so cancellation and timeout do not wait for a step. */\n private sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) {\n reject(abortError());\n return;\n }\n\n const onAbort = (): void => {\n clearTimeout(timer);\n reject(abortError());\n };\n\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n\n signal.addEventListener('abort', onAbort, { once: true });\n });\n }\n\n private reportProgress(job: ActiveJob, percent: number, message: string): void {\n if (job.settled || job.stopReason !== null) return;\n\n // Progress is a monotonic contract: consumers assume a percentage never\n // moves backwards. A throttled flush must not resurrect an older value\n // after a newer direct send.\n const value = Math.max(0, Math.min(100, Math.round(percent)));\n if (value < job.lastPercentSent) return;\n\n const now = this.now();\n if (now - job.lastProgressAt < this.progressIntervalMs) {\n if (job.pendingProgress === null || value >= job.pendingProgress.percent) {\n job.pendingProgress = { percent: value, message };\n }\n if (!job.progressTimer) {\n job.progressTimer = setTimeout(() => {\n job.progressTimer = null;\n this.flushProgress(job);\n }, this.progressIntervalMs);\n job.progressTimer.unref?.();\n }\n return;\n }\n\n this.sendProgress(job, value, message);\n }\n\n private flushProgress(job: ActiveJob): void {\n if (job.settled || job.stopReason !== null) return;\n const pending = job.pendingProgress;\n if (!pending) return;\n this.sendProgress(job, pending.percent, pending.message);\n }\n\n private sendProgress(job: ActiveJob, percent: number, message: string): void {\n // A direct send supersedes anything queued for the throttle window.\n if (job.progressTimer) {\n clearTimeout(job.progressTimer);\n job.progressTimer = null;\n }\n job.pendingProgress = null;\n job.lastPercentSent = Math.max(job.lastPercentSent, percent);\n\n const progress: AgentTaskProgressMessage = {\n ...this.base(),\n type: 'task.progress',\n taskId: job.taskId,\n leaseId: job.leaseId,\n percent: job.lastPercentSent,\n message,\n };\n job.lastProgressAt = this.now();\n this.send(progress);\n }\n\n private reportCheckpoint(job: ActiveJob, label: string, state: Record<string, unknown>): void {\n if (job.settled || job.stopReason !== null) return;\n\n const serialized = JSON.stringify(state);\n if (Buffer.byteLength(serialized, 'utf8') > this.checkpointMaxBytes) {\n this.logger.warn(\n `Skipping checkpoint \"${label}\" for task ${job.taskId}: exceeds ${this.checkpointMaxBytes} bytes.`,\n );\n return;\n }\n\n const message: AgentTaskCheckpointMessage = {\n ...this.base(),\n type: 'task.checkpoint',\n taskId: job.taskId,\n leaseId: job.leaseId,\n label,\n state,\n };\n this.send(message);\n }\n\n private sendAck(offer: AgentTaskOfferMessage): void {\n this.send({\n ...this.base(),\n type: 'task.ack',\n taskId: offer.task.id,\n leaseId: offer.leaseId,\n });\n }\n\n private sendFailure(job: ActiveJob, error: string): void {\n const message: AgentTaskFailMessage = {\n ...this.base(),\n type: 'task.fail',\n taskId: job.taskId,\n leaseId: job.leaseId,\n error: error.slice(0, MAX_ERROR_LENGTH),\n };\n if (!this.send(message)) {\n this.logger.warn(\n `Could not report failure for task ${job.taskId}: the transport is closed. ` +\n 'The lease will expire and the queue will decide what happens next.',\n );\n }\n this.logger.warn(`Task ${job.taskId} failed: ${message.error}`);\n if (job.outcome === null) {\n job.outcome = 'failed';\n job.outcomeError = message.error;\n }\n }\n\n private startRenewal(job: ActiveJob): void {\n const interval =\n this.leaseRenewIntervalMs ??\n clampInt(\n Math.floor((job.leaseExpiresAt - this.now()) / 3),\n MIN_RENEW_INTERVAL_MS,\n MAX_RENEW_INTERVAL_MS,\n );\n\n job.renewTimer = setInterval(() => {\n if (job.settled || job.stopReason !== null) return;\n const message: AgentTaskRenewMessage = {\n ...this.base(),\n type: 'task.renew',\n taskId: job.taskId,\n leaseId: job.leaseId,\n };\n this.send(message);\n }, interval);\n job.renewTimer.unref?.();\n }\n\n private stop(job: ActiveJob, reason: StopReason): void {\n if (job.settled) return;\n // Timeout and fencing are terminal; they must not be overwritten by a late\n // cancel frame for the same job.\n if (job.stopReason === null) {\n job.stopReason = reason;\n this.logger.info(`Stopping task ${job.taskId}: ${reason}.`);\n }\n job.controller.abort();\n }\n\n private settle(job: ActiveJob): void {\n if (job.settled) return;\n job.settled = true;\n\n if (job.progressTimer) {\n clearTimeout(job.progressTimer);\n job.progressTimer = null;\n }\n if (job.renewTimer) {\n clearInterval(job.renewTimer);\n job.renewTimer = null;\n }\n if (job.timeoutTimer) {\n clearTimeout(job.timeoutTimer);\n job.timeoutTimer = null;\n }\n\n this.running.delete(job.key);\n this.runs.delete(job.key);\n\n try {\n this.options.onJobFinished?.({\n taskId: job.taskId,\n leaseId: job.leaseId,\n jobType: job.offer.task.jobType,\n outcome: job.outcome ?? 'stopped',\n stopReason: job.stopReason,\n error: job.outcomeError,\n });\n } catch (err) {\n this.logger.warn(`onJobFinished listener failed: ${(err as Error).message}`);\n }\n\n this.pump();\n }\n\n private pump(): void {\n if (this.shuttingDown) return;\n\n while (this.running.size < this.maxConcurrentJobs && this.queued.length > 0) {\n const next = this.queued.shift();\n if (!next) return;\n\n if (next.leaseExpiresAt <= this.now()) {\n this.logger.warn(`Dropping queued offer for task ${next.task.id}: lease expired.`);\n continue;\n }\n if (this.running.has(this.jobKey(next.task.id, next.leaseId))) continue;\n\n this.start(next);\n }\n }\n\n private send(message: AgentTaskClientMessage): boolean {\n try {\n return this.options.send(message);\n } catch (err) {\n this.logger.warn(`Failed to send ${message.type}: ${(err as Error).message}`);\n return false;\n }\n }\n\n private base(): { version: '1.0'; agentId: string; timestamp: number } {\n return {\n version: '1.0',\n agentId: this.options.agentId,\n timestamp: Date.now(),\n };\n }\n\n private jobKey(taskId: string, leaseId: string): string {\n return `${taskId}:${leaseId}`;\n }\n\n private errorMessage(err: unknown): string {\n if (err instanceof Error && err.message.trim().length > 0) return err.message;\n return 'Unknown execution error.';\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min;\n return Math.max(min, Math.min(max, Math.trunc(value)));\n}\n\nfunction abortError(): Error {\n const error = new Error('Job aborted.');\n error.name = 'AbortError';\n return error;\n}\n","import { createHash } from 'node:crypto';\nimport { join } from 'node:path';\nimport type {\n CrawlPageResult,\n ExplorationOpenApiSpec,\n ExplorationReport,\n ExplorationTask,\n} from '@luxray/shared';\nimport type { ExplorationWorker, ExplorationOutcome, PageObservation } from '@luxray/exploration-worker';\nimport { DEFAULT_EXPLORATION_LIMITS } from '@luxray/exploration-worker';\nimport {\n applyOpenApiTransportBudget,\n generateOpenApiSpec,\n writeOpenApiArtifacts,\n} from './openapi-spec.js';\nimport type { ExplorationJobResult, ExplorationJobRunner } from './task-executor.js';\n\n/**\n * Operator-supplied sign-in for crawls started from this terminal.\n *\n * These values are never sent to the control plane: the task row records that a\n * sign-in happened, not how. `appliesTo` exists because this agent can be handed\n * unrelated queued tasks, and those must never inherit the operator's password.\n */\nexport interface ExploreAuthOptions {\n /** Form sign-in: proposed in a dedicated page before the crawl starts. */\n readonly credentials?: {\n readonly username: string;\n readonly password: string;\n };\n /** Arbitrary request headers; the general case for bearer tokens/API keys. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cookies installed on the task context before the first navigation. */\n readonly cookies?: readonly { readonly name: string; readonly value: string }[];\n /** Page that renders the sign-in form; defaults to the task's start URL. */\n readonly loginUrl?: string;\n readonly submitTimeoutMs?: number;\n /** Resolves once the operator finished a captcha/2FA sign-in by hand. */\n readonly manualAssist?: () => Promise<void>;\n /** Restore a saved session instead of signing in. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n /**\n * Only tasks this predicate accepts may use the session. Defaults to all.\n *\n * Async because the offer can reach the agent before the request that created\n * the task returns its id; a caller that has to wait for that id can do so\n * here instead of racing it.\n */\n readonly appliesTo?: (taskId: string) => boolean | Promise<boolean>;\n}\n\nexport interface ExplorationRunnerOptions {\n /** Directory that receives one subdirectory per task. */\n readonly artifactRoot: string;\n readonly headless?: boolean;\n readonly includeSecrets?: boolean;\n /** Sign-in material for tasks that may use it. */\n readonly auth?: ExploreAuthOptions;\n /**\n * Receives each page as the crawl observes it, not at the end.\n *\n * The executor publishes this to the results stream so a long crawl is\n * inspectable while it runs; the run summary is still the terminal report.\n */\n readonly onPage?: (page: CrawlPageResult) => void;\n readonly onFinished?: (result: {\n readonly taskId: string;\n readonly startUrl: string;\n readonly outcome: ExplorationOutcome;\n }) => void;\n readonly logger?: {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n };\n}\n\n/**\n * Adapts the isolated browser worker to the task executor.\n *\n * The task's stored scope is the authority for what may be crawled; the local\n * defaults only fill in operational limits the control plane does not store\n * (timeouts, checkpoint cadence).\n */\nexport function createExplorationRunner(\n worker: ExplorationWorker,\n options: ExplorationRunnerOptions,\n): ExplorationJobRunner {\n return async (execution, task: ExplorationTask): Promise<ExplorationJobResult> => {\n const scope = task.scope ?? {};\n const allowedDomains =\n scope.allowedDomains && scope.allowedDomains.length > 0\n ? scope.allowedDomains\n : [new URL(task.startUrl).hostname];\n\n const maySignIn = options.auth ? await (options.auth.appliesTo?.(task.id) ?? true) : false;\n const auth = maySignIn ? options.auth ?? null : null;\n\n // The digest must describe the page set the control plane stores, which is\n // keyed by URL. A URL re-observed later supersedes the earlier row, so the\n // collector keeps the last observation and the report is built from that.\n const emitted = new Map<string, CrawlPageResult>();\n\n const outcome = await worker.explore({\n startUrl: task.startUrl,\n scope: {\n allowedDomains,\n includeSubdomains: scope.includeSubdomains ?? false,\n },\n limits: {\n maxPages: scope.maxPages ?? DEFAULT_EXPLORATION_LIMITS.maxPages,\n maxDepth: scope.maxDepth ?? DEFAULT_EXPLORATION_LIMITS.maxDepth,\n },\n artifactDir: join(options.artifactRoot, task.id),\n headless: options.headless ?? true,\n includeSecrets: options.includeSecrets,\n ...(auth?.storageStatePath ? { storageStatePath: auth.storageStatePath } : {}),\n ...(auth?.saveStorageStatePath ? { saveStorageStatePath: auth.saveStorageStatePath } : {}),\n ...(auth && (auth.credentials || auth.headers || auth.cookies)\n ? {\n auth: {\n ...(auth.credentials ? { credentials: auth.credentials } : {}),\n ...(auth.headers ? { headers: auth.headers } : {}),\n ...(auth.cookies ? { cookies: auth.cookies } : {}),\n loginUrl: auth.loginUrl,\n submitTimeoutMs: auth.submitTimeoutMs,\n manualAssist: auth.manualAssist,\n },\n }\n : {}),\n signal: execution.signal,\n onProgress: execution.reportProgress,\n onCheckpoint: execution.checkpoint,\n // Always collect, even when nobody subscribed: the report's digest and\n // page count have to describe what the run emitted, not what a caller\n // happened to forward.\n onPage: (observed: PageObservation, sequence: number) => {\n const page = toPageResult(task, observed, sequence);\n emitted.set(page.url, page);\n options.onPage?.(page);\n },\n logger: options.logger,\n });\n\n options.onFinished?.({ taskId: task.id, startUrl: task.startUrl, outcome });\n\n const pages = [...emitted.values()].sort((a, b) => a.sequence - b.sequence);\n const summary = outcome.run.summary;\n\n // Specification generation is best effort: a crawl that observed API\n // traffic should not fail because the document could not be synthesized or\n // written. The report and the pages are the execution of record.\n const { openApi, openApiSummary } = await buildOpenApi(task, outcome, options.logger);\n\n const report: ExplorationReport = {\n version: 1,\n taskId: task.id,\n attempt: task.attempts,\n outcome: 'completed',\n startUrl: summary.startUrl,\n startedAt: summary.startedAt,\n finishedAt: summary.finishedAt,\n durationMs: summary.durationMs,\n truncatedByLimit: summary.truncatedByLimit,\n limits: summary.limits,\n totals: {\n pagesVisited: summary.pagesVisited,\n pagesFailed: summary.pagesFailed,\n duplicatePages: summary.duplicatePages,\n authRequiredPages: pages.filter((page) => page.authRequired).length,\n transactionsCaptured: summary.transactionsCaptured,\n linksDiscovered: summary.linksDiscovered,\n frontierRemaining: summary.frontierRemaining,\n },\n authentication: summary.authentication ?? null,\n pageCount: pages.length,\n pageDigest: digestPages(pages),\n artifactDir: outcome.paths.dir,\n };\n\n return {\n summary: {\n ...summary,\n artifactDir: outcome.paths.dir,\n transactionsCaptured: outcome.transactionsCaptured,\n openApi: openApiSummary,\n },\n report,\n ...(openApi ? { openApi } : {}),\n };\n };\n}\n\n/**\n * Generates the specification and its artifacts without letting a failure in\n * this optional stage turn a completed crawl into a failed task.\n */\nasync function buildOpenApi(\n task: ExplorationTask,\n outcome: ExplorationOutcome,\n logger: ExplorationRunnerOptions['logger'],\n): Promise<{\n readonly openApi?: ExplorationOpenApiSpec;\n readonly openApiSummary: Record<string, unknown>;\n}> {\n try {\n const generated = generateOpenApiSpec({\n taskId: task.id,\n attempt: task.attempts,\n startUrl: task.startUrl,\n title: task.name,\n transactions: outcome.transactions ?? [],\n });\n\n if (!generated) {\n return {\n openApiSummary: { generated: false, reason: 'no-api-traffic' },\n };\n }\n\n try {\n await writeOpenApiArtifacts(outcome.paths.dir, generated);\n } catch (error) {\n logger?.warn(\n `Could not write OpenAPI artifacts for task ${task.id}: ${(error as Error).message}`,\n );\n }\n\n const payload = applyOpenApiTransportBudget(generated);\n return {\n openApi: payload,\n openApiSummary: {\n generated: true,\n endpointCount: payload.summary.endpointCount,\n schemaCount: payload.summary.schemaCount,\n relationshipCount: payload.summary.relationshipCount,\n jsonBytes: payload.summary.jsonBytes,\n yamlBytes: payload.summary.yamlBytes,\n omitted: payload.summary.omission !== null,\n },\n };\n } catch (error) {\n logger?.warn(\n `Could not generate an OpenAPI specification for task ${task.id}: ${(error as Error).message}`,\n );\n return {\n openApiSummary: { generated: false, reason: 'generation-failed' },\n };\n }\n}\n\n/**\n * Identity of a streamed page set: `sha256:<hex>` over `sequence:url` lines in\n * visit order.\n *\n * The digest lets the control plane tell a redelivered report from a second,\n * different execution of the same attempt without shipping the page manifest in\n * the completion frame.\n */\nexport function digestPages(\n pages: readonly { readonly sequence: number; readonly url: string }[],\n): string {\n const hash = createHash('sha256');\n for (const page of pages) hash.update(`${page.sequence}:${page.url}\\n`);\n return `sha256:${hash.digest('hex')}`;\n}\n\n/**\n * Narrows a worker observation to the stream record.\n *\n * The worker knows more than the control plane needs (`requestedUrl`,\n * `linksQueued`); the stream carries only what the dashboard displays, and the\n * task id comes from the execution rather than the page.\n */\nfunction toPageResult(\n task: ExplorationTask,\n page: PageObservation,\n sequence: number,\n): CrawlPageResult {\n return {\n taskId: task.id,\n // The agent's current attempt fences this observation on the server: a page\n // from an execution that was already requeued is stored nowhere.\n attempt: task.attempts,\n sequence,\n url: page.url,\n depth: page.depth,\n httpStatus: page.httpStatus,\n title: page.title,\n fingerprint: page.fingerprint,\n duplicateOf: page.duplicateOf,\n linksFound: page.linksFound,\n transactions: page.transactions,\n durationMs: page.durationMs,\n observedAt: page.observedAt,\n error: page.error,\n authRequired: page.authRequired,\n };\n}\n","import { join } from 'node:path';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport { writeRunArtifacts, type ArtifactPaths } from './artifacts/run-artifacts.js';\nimport { TaskBrowser } from './browser/task-browser.js';\nimport { DeterministicCrawler, type CrawlAuthOptions, type CrawlLogger } from './crawl/crawler.js';\nimport { ExplorationAbortedError } from './errors.js';\nimport {\n DEFAULT_EXPLORATION_LIMITS,\n type ExplorationLimits,\n type ExplorationRun,\n type PageObservation,\n} from './crawl/types.js';\nimport type { CrawlScope } from './crawl/url-policy.js';\n\nexport interface ExplorationRequest {\n readonly startUrl: string;\n readonly scope: CrawlScope;\n /** Overrides for the local limits; task scope still bounds page count/depth. */\n readonly limits?: Partial<ExplorationLimits>;\n /** Where `run.json`, `pages.json` and `transactions.json` are written. */\n readonly artifactDir: string;\n readonly headless?: boolean;\n /** Keep credential headers in the artifacts. Off by default. */\n readonly includeSecrets?: boolean;\n /** Session material to restore before the first page. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n /**\n * Sign in before crawling. Credentials stay in this process: the task row\n * records only that a sign-in happened, and the password is scrubbed from\n * anything written to disk.\n */\n readonly auth?: CrawlAuthOptions;\n readonly signal?: AbortSignal;\n readonly onProgress?: (percent: number, message: string) => void;\n readonly onCheckpoint?: (label: string, state: Record<string, unknown>) => void;\n /** Streams each observation out while the crawl is still running. */\n readonly onPage?: (page: PageObservation, sequence: number) => void;\n readonly logger?: CrawlLogger;\n}\n\nexport interface ExplorationOutcome {\n readonly run: ExplorationRun;\n readonly paths: ArtifactPaths;\n readonly transactionsCaptured: number;\n /**\n * Every transaction the run captured, for downstream intelligence.\n *\n * Kept on the outcome rather than only in `transactions.json` so the agent\n * can build the OpenAPI specification without re-reading an artifact it did\n * not write.\n */\n readonly transactions: readonly CapturedTransaction[];\n}\n\nconst HARD_PAGE_CAP = 1_000;\nconst HARD_DEPTH_CAP = 10;\n\n/**\n * Public entry point for isolated browser exploration.\n *\n * One instance owns the Chromium process and is meant to live for the whole\n * agent process; every `explore` call gets a fresh, isolated browser context and\n * a fresh artifact directory.\n */\nexport class ExplorationWorker {\n private readonly browser: TaskBrowser;\n private readonly defaultHeadless: boolean;\n private disposed = false;\n\n public constructor(options?: { headless?: boolean }) {\n this.defaultHeadless = options?.headless ?? true;\n this.browser = new TaskBrowser({ headless: this.defaultHeadless });\n }\n\n public async explore(request: ExplorationRequest): Promise<ExplorationOutcome> {\n if (this.disposed) {\n throw new Error('ExplorationWorker has been disposed.');\n }\n\n const limits = this.resolveLimits(request.limits);\n const crawler = new DeterministicCrawler(this.browser, {\n limits,\n scope: request.scope,\n signal: request.signal,\n onProgress: request.onProgress,\n onCheckpoint: request.onCheckpoint,\n onPage: request.onPage,\n logger: request.logger,\n auth: request.auth,\n storageStatePath: request.storageStatePath,\n saveStorageStatePath: request.saveStorageStatePath,\n });\n\n let outcome: { run: ExplorationRun; transactions: readonly CapturedTransaction[] };\n try {\n outcome = await crawler.run(request.startUrl);\n } catch (error) {\n if (error instanceof ExplorationAbortedError) throw error;\n if (request.signal?.aborted) throw new ExplorationAbortedError();\n\n // A Chromium crash loses the rendered state but not the task: relaunch and\n // run the deterministic crawl once more. Any other failure is reported.\n if (!this.browser.isConnected()) {\n request.logger?.warn('Browser process is gone; relaunching and retrying the run once.');\n await this.browser.ensureStarted();\n outcome = await crawler.run(request.startUrl);\n } else {\n throw error;\n }\n }\n\n const paths = await writeRunArtifacts(request.artifactDir, outcome, {\n includeSecrets: request.includeSecrets,\n // Known secrets never reach disk, even when the operator asked to keep\n // credential headers: a password, a bearer token, a session cookie value.\n secrets: request.auth ? authSecrets(request.auth) : undefined,\n });\n\n return {\n run: {\n ...outcome.run,\n summary: { ...outcome.run.summary, artifactDir: paths.dir },\n },\n paths,\n transactionsCaptured: outcome.transactions.length,\n transactions: outcome.transactions,\n };\n }\n\n public async dispose(): Promise<void> {\n this.disposed = true;\n await this.browser.close();\n }\n\n private resolveLimits(overrides?: Partial<ExplorationLimits>): ExplorationLimits {\n const merged: ExplorationLimits = { ...DEFAULT_EXPLORATION_LIMITS, ...overrides };\n return {\n maxPages: clampInt(merged.maxPages, 1, HARD_PAGE_CAP),\n maxDepth: clampInt(merged.maxDepth, 1, HARD_DEPTH_CAP),\n pageTimeoutMs: clampInt(merged.pageTimeoutMs, 1_000, 120_000),\n settleTimeoutMs: clampInt(merged.settleTimeoutMs, 0, 60_000),\n maxDurationMs: clampInt(merged.maxDurationMs, 1_000, 60 * 60_000),\n checkpointEveryPages: clampInt(merged.checkpointEveryPages, 1, 100),\n };\n }\n}\n\nfunction clampInt(value: number, min: number, max: number): number {\n if (!Number.isFinite(value)) return min;\n return Math.min(max, Math.max(min, Math.trunc(value)));\n}\n\n/** Default artifact location used by the CLI when `--out` is not supplied. */\nexport function defaultArtifactDir(homeDir: string, taskId: string): string {\n return join(homeDir, '.luxray', 'runs', taskId);\n}\n\n/**\n * Every literal value that must be scrubbed from an artifact.\n *\n * The password is included even when form values are not captured, because a\n * page can echo a failed login back into an error message.\n */\nfunction authSecrets(auth: CrawlAuthOptions): readonly string[] {\n const secrets: string[] = [];\n if (auth.credentials) secrets.push(auth.credentials.password);\n secrets.push(...Object.values(auth.headers ?? {}));\n secrets.push(...(auth.cookies ?? []).map((cookie) => cookie.value));\n return secrets;\n}\n\nexport { ExplorationAbortedError } from './errors.js';\nexport { DEFAULT_EXPLORATION_LIMITS } from './crawl/types.js';\nexport type {\n ExplorationLimits,\n ExplorationRun,\n ExplorationRunSummary,\n PageObservation,\n} from './crawl/types.js';\nexport type { CrawlScope } from './crawl/url-policy.js';\nexport { canonicalizeUrl } from './crawl/url-canonicalizer.js';\nexport { isUrlInScope, isBlockedHost } from './crawl/url-policy.js';\n","import { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { CapturedTransaction, HttpHeaders } from '@luxray/shared';\nimport type { ExplorationRun } from '../crawl/types.js';\n\n/** Headers whose values must never be persisted in a run artifact. */\nconst SENSITIVE_HEADERS = new Set([\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'proxy-authorization',\n 'x-api-key',\n 'x-auth-token',\n 'x-csrf-token',\n]);\n\nconst DEFAULT_BODY_BUDGET_BYTES = 32 * 1024 * 1024;\nconst OMITTED_BODY = '[body omitted: artifact size budget reached]';\n\nexport interface ArtifactOptions {\n /** Keep credential-bearing headers verbatim. Off by default. */\n readonly includeSecrets?: boolean;\n /** Total response body bytes persisted before bodies are dropped. */\n readonly bodyBudgetBytes?: number;\n /**\n * Literal values scrubbed from every persisted string: passwords typed into\n * a sign-in form, mostly. Applied even when `includeSecrets` is set, because\n * a known secret is never evidence worth keeping.\n */\n readonly secrets?: readonly string[];\n}\n\n/** Shorter values are ignored: scrubbing \"a\" would mangle the whole artifact. */\nconst MIN_SECRET_LENGTH = 4;\nconst REDACTED = '[redacted]';\n\nexport interface ArtifactPaths {\n readonly dir: string;\n readonly runFile: string;\n readonly pagesFile: string;\n readonly transactionsFile: string;\n}\n\n/**\n * Writes the evidence for one run to disk.\n *\n * Until observation ingestion exists (Milestone 6) the artifacts are the only\n * durable record of what was crawled, so they are written as plain JSON beside\n * each other: `run.json` for the summary, `pages.json` for every observation and\n * `transactions.json` for the captured network traffic.\n *\n * Credentials are stripped before writing. Keeping them would turn a folder of\n * debugging output into a secret store.\n */\nexport async function writeRunArtifacts(\n dir: string,\n outcome: { run: ExplorationRun; transactions: readonly CapturedTransaction[] },\n options?: ArtifactOptions,\n): Promise<ArtifactPaths> {\n await mkdir(dir, { recursive: true });\n\n const paths: ArtifactPaths = {\n dir,\n runFile: join(dir, 'run.json'),\n pagesFile: join(dir, 'pages.json'),\n transactionsFile: join(dir, 'transactions.json'),\n };\n\n const transactions = redactTransactions(outcome.transactions, options);\n const secrets = usableSecrets(options?.secrets);\n\n await Promise.all([\n // The file records the directory it lives in, so a bundle copied away from\n // the workspace still says where it was produced.\n writeJson(paths.runFile, scrubValue({ ...outcome.run.summary, artifactDir: dir }, secrets)),\n writeJson(paths.pagesFile, scrubValue(outcome.run.pages, secrets)),\n writeJson(paths.transactionsFile, scrubValue(transactions, secrets)),\n ]);\n\n return paths;\n}\n\nexport function redactTransactions(\n transactions: readonly CapturedTransaction[],\n options?: ArtifactOptions,\n): CapturedTransaction[] {\n const budget = new Budget(options);\n const secrets = usableSecrets(options?.secrets);\n\n return transactions.map((transaction) => {\n const redacted =\n options?.includeSecrets === true\n ? transaction\n : {\n ...transaction,\n request: {\n ...transaction.request,\n headers: redactHeaders(transaction.request.headers),\n },\n ...(transaction.response\n ? {\n response: {\n ...transaction.response,\n headers: redactHeaders(transaction.response.headers),\n },\n }\n : {}),\n };\n\n return scrubValue(limitBody(redacted, budget), secrets);\n });\n}\n\nfunction usableSecrets(secrets: readonly string[] | undefined): readonly string[] {\n if (!secrets) return [];\n return secrets.filter((secret) => secret.length >= MIN_SECRET_LENGTH);\n}\n\n/** Deep copy with every known secret replaced, including request post data. */\nfunction scrubValue<T>(value: T, secrets: readonly string[]): T {\n return scrubUnknown(value, secrets) as T;\n}\n\nfunction scrubUnknown(value: unknown, secrets: readonly string[]): unknown {\n if (secrets.length === 0) return value;\n if (typeof value === 'string') {\n let scrubbed = value;\n for (const secret of secrets) {\n scrubbed = scrubbed.split(secret).join(REDACTED);\n }\n return scrubbed;\n }\n if (Array.isArray(value)) {\n return value.map((item) => scrubUnknown(item, secrets));\n }\n if (value !== null && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {\n result[key] = scrubUnknown(entry, secrets);\n }\n return result;\n }\n return value;\n}\n\nfunction redactHeaders(headers: HttpHeaders): HttpHeaders {\n const result: Record<string, string> = {};\n for (const [name, value] of Object.entries(headers)) {\n result[name] = SENSITIVE_HEADERS.has(name.toLowerCase()) ? '[redacted]' : value;\n }\n return result;\n}\n\nclass Budget {\n private remaining: number;\n\n public constructor(options?: ArtifactOptions) {\n this.remaining = options?.bodyBudgetBytes ?? DEFAULT_BODY_BUDGET_BYTES;\n }\n\n public take(bytes: number): boolean {\n if (bytes > this.remaining) return false;\n this.remaining -= bytes;\n return true;\n }\n}\n\n/** Drops bodies once the artifact budget is spent, keeping the metadata. */\nfunction limitBody(transaction: CapturedTransaction, budget: Budget): CapturedTransaction {\n const body = transaction.response?.body;\n if (!transaction.response || typeof body !== 'string' || body.length === 0) {\n return transaction;\n }\n if (budget.take(Buffer.byteLength(body, 'utf8'))) return transaction;\n\n return {\n ...transaction,\n response: {\n ...transaction.response,\n body: OMITTED_BODY,\n bodyEncoding: 'utf-8',\n bodyTruncated: true,\n },\n };\n}\n\nasync function writeJson(path: string, value: unknown): Promise<void> {\n await writeFile(path, `${JSON.stringify(value, null, 2)}\\n`, 'utf8');\n}\n","import { chromium, type Browser, type BrowserContext } from 'playwright';\n\n/** Cookies applied to a task context before the first navigation. */\nexport interface AuthCookie {\n readonly name: string;\n readonly value: string;\n}\n\nexport interface TaskBrowserOptions {\n readonly headless?: boolean;\n /** Viewport for every task context. */\n readonly viewport?: { readonly width: number; readonly height: number };\n}\n\n/**\n * Owns the Chromium process for an exploration worker.\n *\n * Isolation rule for M4: one `BrowserContext` per task, created fresh and\n * disposed at the end of the run. Nothing (cookies, storage, cache headers)\n * crosses tasks, and a task never sees the user's everyday browser profile.\n *\n * The browser process itself is shared across tasks in one agent process: it is\n * expensive, and isolation comes from the context, not the executable.\n */\nexport class TaskBrowser {\n private browser: Browser | null = null;\n private readonly headless: boolean;\n private readonly viewport: { readonly width: number; readonly height: number };\n private launchCount = 0;\n\n constructor(options?: TaskBrowserOptions) {\n this.headless = options?.headless ?? true;\n this.viewport = options?.viewport ?? { width: 1280, height: 720 };\n }\n\n /** Launches Chromium, or relaunches it after a crash. */\n public async ensureStarted(): Promise<Browser> {\n if (this.browser && this.browser.isConnected()) return this.browser;\n\n if (this.browser) {\n await this.browser.close().catch(() => {});\n this.browser = null;\n }\n\n const browser = await chromium.launch({ headless: this.headless });\n browser.on('disconnected', () => {\n if (this.browser === browser) this.browser = null;\n });\n this.browser = browser;\n this.launchCount += 1;\n return browser;\n }\n\n /**\n * Opens a fresh, isolated context for one task. `ignoreHTTPSErrors` is on so\n * local staging servers with self-signed certificates can be explored.\n *\n * `storageState` restores a previously saved session (cookies + localStorage)\n * so a crawl can reuse a sign-in instead of performing one. It is a path, not\n * an inline object, because the file is credential material and the operator\n * decides where it lives.\n *\n * `headers` and `cookies` are operator-supplied auth keys: a bearer token, an\n * API key, a session cookie. They apply to every request the context makes,\n * including the first one, which is what lets an authenticated crawl start on\n * a protected page instead of bouncing to the sign-in form.\n */\n public async openTaskContext(options?: {\n readonly storageState?: string;\n readonly headers?: Readonly<Record<string, string>>;\n readonly cookies?: readonly AuthCookie[];\n /** Origin the cookies belong to; required when `cookies` are given. */\n readonly cookieUrl?: string;\n }): Promise<BrowserContext> {\n const browser = await this.ensureStarted();\n const context = await browser.newContext({\n viewport: this.viewport,\n ignoreHTTPSErrors: true,\n serviceWorkers: 'block',\n ...(options?.storageState ? { storageState: options.storageState } : {}),\n ...(options?.headers && Object.keys(options.headers).length > 0\n ? { extraHTTPHeaders: { ...options.headers } }\n : {}),\n });\n\n if (options?.cookies && options.cookies.length > 0) {\n if (!options.cookieUrl) {\n await context.close().catch(() => {});\n throw new Error('cookieUrl is required when auth cookies are supplied.');\n }\n await context.addCookies(\n options.cookies.map((cookie) => ({\n name: cookie.name,\n value: cookie.value,\n url: options.cookieUrl,\n })),\n );\n }\n\n return context;\n }\n\n public isConnected(): boolean {\n return this.browser !== null && this.browser.isConnected();\n }\n\n public get launches(): number {\n return this.launchCount;\n }\n\n public async close(): Promise<void> {\n const browser = this.browser;\n this.browser = null;\n if (!browser) return;\n await browser.close().catch(() => {});\n }\n}\n","/** Raised when the run was stopped on purpose (cancel, pause, shutdown). */\nexport class ExplorationAbortedError extends Error {\n public constructor(message = 'Exploration was aborted.') {\n super(message);\n this.name = 'ExplorationAbortedError';\n }\n}\n\n/**\n * Raised when the operator asked for a signed-in crawl and the sign-in did not\n * take effect.\n *\n * Failing here is deliberate: continuing would crawl the login wall and report\n * a successful run full of unauthenticated shell pages, which is exactly the\n * outcome the sign-in step exists to prevent.\n */\nexport class AuthenticationFailedError extends Error {\n public constructor(message: string) {\n super(message);\n this.name = 'AuthenticationFailedError';\n }\n}\n","import type { BrowserContext, Locator, Page } from 'playwright';\nimport { AuthenticationFailedError, ExplorationAbortedError } from '../errors.js';\n\n/**\n * Signs the operator in before a crawl starts.\n *\n * The control plane never sees these credentials: they are held by the agent\n * process for the duration of one run and typed into the page, exactly like a\n * human would. The task row only ever records that a sign-in happened.\n */\n\nexport interface SiteCredentials {\n readonly username: string;\n readonly password: string;\n}\n\nexport type LoginStrategy = 'form' | 'manual';\n\nexport interface LoginLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n}\n\nexport interface LoginOptions {\n /** Page that renders the sign-in form. Defaults to the crawl's start page. */\n readonly loginUrl: string;\n readonly credentials: SiteCredentials;\n /** Budget for the first paint of the sign-in page. */\n readonly pageTimeoutMs?: number;\n /** How long to wait for the site to accept or reject the form. */\n readonly submitTimeoutMs?: number;\n /**\n * Escape hatch for captchas, 2FA prompts and device approvals: the operator\n * finishes the sign-in in a visible browser, then resolves this promise.\n * Without it an unverifiable sign-in is reported as a failure.\n */\n readonly manualAssist?: () => Promise<void>;\n readonly signal?: AbortSignal;\n readonly logger?: LoginLogger;\n}\n\nexport interface LoginResult {\n readonly strategy: LoginStrategy;\n readonly loginUrl: string;\n readonly finalUrl: string;\n /** Cookie count after the sign-in, used as a cheap sanity signal. */\n readonly cookies: number;\n}\n\nconst DEFAULT_PAGE_TIMEOUT_MS = 30_000;\nconst DEFAULT_SUBMIT_TIMEOUT_MS = 30_000;\nconst POLL_INTERVAL_MS = 200;\n\n/**\n * Username fields, most specific first. Sites that use a two-step flow still\n * expose an email field on the first screen, so this list intentionally ends\n * with plain text inputs.\n */\nconst USERNAME_SELECTORS = [\n 'input[autocomplete=\"username\"]',\n 'input[type=\"email\"]',\n 'input[name=\"username\"]',\n 'input[name=\"email\"]',\n 'input[id=\"username\"]',\n 'input[id=\"email\"]',\n 'input[name*=\"user\" i]',\n 'input[name*=\"email\" i]',\n 'input[id*=\"user\" i]',\n 'input[id*=\"email\" i]',\n 'input[type=\"text\"]',\n];\n\nconst PASSWORD_SELECTOR = 'input[type=\"password\"]';\n\nconst SUBMIT_SELECTORS = [\n 'form button[type=\"submit\"]',\n 'form input[type=\"submit\"]',\n 'button[type=\"submit\"]',\n 'input[type=\"submit\"]',\n 'form button',\n];\n\nexport async function signIn(\n context: BrowserContext,\n options: LoginOptions,\n): Promise<LoginResult> {\n const pageTimeoutMs = options.pageTimeoutMs ?? DEFAULT_PAGE_TIMEOUT_MS;\n const submitTimeoutMs = options.submitTimeoutMs ?? DEFAULT_SUBMIT_TIMEOUT_MS;\n\n // A dedicated page keeps the credential POST off the crawl's capture window:\n // transactions are attributed per page, so traffic here never reaches the\n // artifacts.\n const page = await context.newPage();\n try {\n page.setDefaultTimeout(pageTimeoutMs);\n await page.goto(options.loginUrl, { waitUntil: 'domcontentloaded', timeout: pageTimeoutMs });\n await settle(page, pageTimeoutMs);\n\n const passwordField = await visibleLocator(page, PASSWORD_SELECTOR);\n\n if (!passwordField) {\n return await assistManually(context, page, options);\n }\n\n const usernameField = await findUsernameField(page);\n if (!usernameField) {\n if (options.manualAssist) {\n options.logger?.warn(\n 'Sign-in page has a password field but no recognizable username field; asking the operator to finish it.',\n );\n return await assistManually(context, page, options);\n }\n throw new AuthenticationFailedError(\n `Found a password field at ${options.loginUrl} but no username/email field. ` +\n \"Pass --login-url with the site's form page, or run with --headed and sign in manually.\",\n );\n }\n\n await usernameField.fill(options.credentials.username);\n await passwordField.fill(options.credentials.password);\n options.logger?.info('Sign-in form filled; submitting.');\n\n await submit(page, passwordField);\n\n if (await waitForSignedIn(page, submitTimeoutMs, options.signal)) {\n return await result(context, page, 'form', options);\n }\n\n if (options.manualAssist) {\n options.logger?.warn(\n 'The site did not accept the scripted sign-in; asking the operator to finish it.',\n );\n return await assistManually(context, page, options);\n }\n\n throw new AuthenticationFailedError(\n `The sign-in form at ${options.loginUrl} did not accept the credentials ` +\n `(still on ${truncate(page.url())} after ${Math.round(submitTimeoutMs / 1000)}s). ` +\n 'Check the password, or run with --headed to sign in manually.',\n );\n } finally {\n await page.close().catch(() => {});\n }\n}\n\n/**\n * Hands the visible browser to the operator. Used for captchas, 2FA and device\n * approval, where no deterministic form fill can succeed.\n */\nasync function assistManually(\n context: BrowserContext,\n page: Page,\n options: LoginOptions,\n): Promise<LoginResult> {\n if (!options.manualAssist) {\n throw new AuthenticationFailedError(\n `No sign-in form was found at ${options.loginUrl}. ` +\n \"Pass --login-url with the site's login page, reuse a session with --auth-state, \" +\n 'or run with --headed to sign in interactively.',\n );\n }\n\n await options.manualAssist();\n\n if (await hasVisiblePasswordField(page)) {\n throw new AuthenticationFailedError(\n 'The sign-in still looks incomplete: the password form is still visible. ' +\n 'Nothing was crawled.',\n );\n }\n\n options.logger?.info('Manual sign-in completed.');\n return await result(context, page, 'manual', options);\n}\n\nasync function result(\n context: BrowserContext,\n page: Page,\n strategy: LoginStrategy,\n options: LoginOptions,\n): Promise<LoginResult> {\n const cookies = await context.cookies().catch(() => []);\n return {\n strategy,\n loginUrl: options.loginUrl,\n finalUrl: page.url(),\n cookies: cookies.length,\n };\n}\n\nasync function submit(page: Page, passwordField: Locator): Promise<void> {\n for (const selector of SUBMIT_SELECTORS) {\n const button = page.locator(selector).first();\n if (await button.isVisible().catch(() => false)) {\n await button.click({ timeout: 10_000 }).catch(() => {});\n return;\n }\n }\n // Many single-field forms submit on Enter only.\n await passwordField.press('Enter').catch(() => {});\n}\n\n/**\n * Waits until the password form is gone. That is the only signal most sites\n * give: the form is replaced by the signed-in shell, or by an error message\n * inside the same form.\n */\nasync function waitForSignedIn(\n page: Page,\n timeoutMs: number,\n signal: AbortSignal | undefined,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (Date.now() < deadline) {\n if (signal?.aborted) throw new ExplorationAbortedError();\n await sleep(POLL_INTERVAL_MS);\n if (signal?.aborted) throw new ExplorationAbortedError();\n if (!(await hasVisiblePasswordField(page))) return true;\n }\n return false;\n}\n\nasync function hasVisiblePasswordField(page: Page): Promise<boolean> {\n return (await visibleLocator(page, PASSWORD_SELECTOR)) !== null;\n}\n\n/** First visible match, or null. Tolerates navigation races. */\nasync function visibleLocator(page: Page, selector: string): Promise<Locator | null> {\n try {\n const matches = page.locator(selector);\n const count = await matches.count();\n for (let index = 0; index < count; index += 1) {\n const candidate = matches.nth(index);\n if (await candidate.isVisible().catch(() => false)) return candidate;\n }\n } catch {\n // The document was replaced mid-query; the caller polls again.\n }\n return null;\n}\n\nasync function findUsernameField(page: Page): Promise<Locator | null> {\n for (const selector of USERNAME_SELECTORS) {\n const field = await visibleLocator(page, selector);\n if (field) return field;\n }\n return null;\n}\n\nasync function settle(page: Page, timeoutMs: number): Promise<void> {\n await page\n .waitForLoadState('networkidle', { timeout: Math.min(3_000, timeoutMs) })\n .catch(() => {});\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction truncate(value: string, max = 300): string {\n return value.length > max ? `${value.slice(0, max)}…` : value;\n}\n","import { createHash } from 'node:crypto';\nimport type { Page } from 'playwright';\n\nexport interface StructuralNode {\n readonly tag: string;\n readonly depth: number;\n}\n\nexport interface PageSnapshot {\n readonly title: string | null;\n readonly links: readonly string[];\n readonly structure: readonly StructuralNode[];\n /**\n * True when a password input is rendered.\n *\n * This is the cheapest deterministic sign-in-wall signal: a page that asks\n * for a password and was reached without credentials is a gate, not content.\n */\n readonly hasPasswordField: boolean;\n /**\n * Body text of a JSON document, or null for anything else.\n *\n * API-first hosts answer with `application/json`. Chromium renders that in a\n * plain `<pre>`, so `links` is empty even when the payload points at every\n * other endpoint. The crawler mines this text instead of treating the page as\n * a dead end.\n */\n readonly jsonBody: string | null;\n /**\n * True when `jsonBody` was cut at `MAX_JSON_BODY_CHARS`.\n *\n * Truncated JSON cannot be parsed, so such a page is fingerprinted and\n * recorded but its links are not followed.\n */\n readonly jsonBodyTruncated: boolean;\n}\n\n/**\n * Structural fingerprint of a rendered document.\n *\n * Only element tags and their nesting depth are hashed: text, attributes,\n * classes and ids are discarded, because they differ between pages that render\n * from the same template. Two listing pages produced by one template therefore\n * share a fingerprint, which is how the crawler recognises a page it has\n * already understood without fetching its siblings forever.\n */\nexport function structuralFingerprint(structure: readonly StructuralNode[]): string {\n const canonical = structure.map((node) => `${node.depth}:${node.tag}`).join('|');\n return `sha256:${createHash('sha256').update(canonical).digest('hex')}`;\n}\n\nconst MAX_NODES = 4_000;\nconst MAX_LINKS = 2_000;\n\n/**\n * Upper bound on the JSON text carried out of the page, in characters.\n *\n * Roughly mirrors the capture engine's 2 MiB response-body budget. A larger\n * document is still fingerprinted (over the retained prefix) and recorded, but\n * its links are not mined, because half a JSON object is not parseable.\n */\nconst MAX_JSON_BODY_CHARS = 2 * 1024 * 1024;\n\n/** Longer strings are payloads (tokens, blobs), not crawlable links. */\nconst MAX_LINK_LENGTH = 2_048;\n\n/**\n * URLs a JSON document points at, in document order.\n *\n * The extracted values are candidates, not resolved URLs: relative paths are\n * returned as-is and go through the same canonicalization and scope filter as\n * anchors. Three shapes are rejected:\n *\n * - URI templates (`/repos/{owner}/{repo}`, `{?page,per_page}`) are patterns,\n * not resources; fetching one would request a literal `{`.\n * - Strings containing whitespace are prose that mentions a URL.\n * - Values longer than `MAX_LINK_LENGTH` are payloads.\n *\n * Order follows the serialized document so two crawls of the same host queue\n * the same URLs in the same order.\n */\nexport function extractJsonLinks(jsonBody: string): readonly string[] {\n let parsed: unknown;\n try {\n parsed = JSON.parse(jsonBody);\n } catch {\n return [];\n }\n\n const links: string[] = [];\n const seen = new Set<string>();\n const stack: unknown[] = [parsed];\n\n while (stack.length > 0) {\n const value = stack.pop();\n\n if (Array.isArray(value)) {\n for (let index = value.length - 1; index >= 0; index -= 1) {\n stack.push(value[index]);\n }\n continue;\n }\n\n if (value !== null && typeof value === 'object') {\n const keys = Object.keys(value);\n for (let index = keys.length - 1; index >= 0; index -= 1) {\n const key = keys[index];\n if (key !== undefined) stack.push((value as Record<string, unknown>)[key]);\n }\n continue;\n }\n\n if (typeof value !== 'string') continue;\n const candidate = value.trim();\n if (!isJsonLinkCandidate(candidate)) continue;\n if (seen.has(candidate)) continue;\n seen.add(candidate);\n links.push(candidate);\n if (links.length >= MAX_LINKS) break;\n }\n\n return links;\n}\n\nfunction isJsonLinkCandidate(value: string): boolean {\n if (value.length === 0 || value.length > MAX_LINK_LENGTH) return false;\n if (value.includes('{') || value.includes('}')) return false;\n if (/\\s/.test(value)) return false;\n return /^https?:\\/\\//i.test(value) || value.startsWith('/');\n}\n\n/**\n * Content fingerprint of a JSON document.\n *\n * Every JSON response is rendered with the same `<pre>` wrapper, so\n * `structuralFingerprint` would call two unrelated endpoints duplicates. The\n * payload is the page here, so the payload is what gets hashed.\n */\nexport function jsonDocumentFingerprint(jsonBody: string): string {\n return `sha256:${createHash('sha256').update(jsonBody).digest('hex')}`;\n}\n\n/**\n * Reads the rendered page. The function passed to `evaluate` must be\n * self-contained: Playwright serializes it and runs it inside the browser, so\n * it cannot close over module scope.\n */\nexport async function readPageSnapshot(page: Page): Promise<PageSnapshot> {\n return page.evaluate(\n (limits: { maxNodes: number; maxLinks: number; maxJsonChars: number }) => {\n const SKIP = new Set([\n 'script',\n 'style',\n 'noscript',\n 'template',\n 'svg',\n 'path',\n 'link',\n 'meta',\n 'head',\n ]);\n const structure: Array<{ tag: string; depth: number }> = [];\n\n const walk = (element: Element, depth: number): void => {\n if (structure.length >= limits.maxNodes) return;\n const tag = element.tagName.toLowerCase();\n if (SKIP.has(tag)) return;\n structure.push({ tag, depth });\n for (const child of Array.from(element.children)) {\n walk(child, depth + 1);\n if (structure.length >= limits.maxNodes) return;\n }\n };\n\n if (document.body) walk(document.body, 0);\n\n const links: string[] = [];\n const anchors = document.querySelectorAll('a[href]');\n for (const anchor of Array.from(anchors)) {\n if (links.length >= limits.maxLinks) break;\n const href = (anchor as HTMLAnchorElement).href;\n if (href) links.push(href);\n }\n\n const passwordInput = document.querySelector('input[type=\"password\"]');\n const hasPasswordField =\n passwordInput !== null &&\n Array.from(passwordInput.getClientRects()).some(\n (rect) => rect.width > 0 && rect.height > 0,\n );\n\n // Chromium wraps a JSON response in a single `<pre>`, so `textContent` is\n // the exact payload. The second child the viewer appends carries no text.\n const isJson = document.contentType.toLowerCase().includes('json');\n const jsonText = isJson && document.body ? (document.body.textContent ?? '') : null;\n const jsonBody =\n jsonText === null ? null : jsonText.slice(0, limits.maxJsonChars);\n const jsonBodyTruncated =\n jsonText !== null && jsonText.length > limits.maxJsonChars;\n\n return {\n title: document.title.length > 0 ? document.title : null,\n links,\n structure,\n hasPasswordField,\n jsonBody,\n jsonBodyTruncated,\n };\n },\n { maxNodes: MAX_NODES, maxLinks: MAX_LINKS, maxJsonChars: MAX_JSON_BODY_CHARS },\n );\n}\n","import { fileURLToPath } from 'node:url';\nimport { CaptureEngine, type CaptureEngineOptions, type CaptureSession } from './capture-engine.js';\nimport { ProcessLifecycle } from './lifecycle/process-lifecycle.js';\n\nexport * from './capture-engine.js';\nexport * from './browser/browser-manager.js';\nexport * from './interceptor/network-interceptor.js';\nexport * from './interceptor/body-resolver.js';\nexport * from './transaction/transaction-correlator.js';\nexport * from './storage/transaction-storage.js';\nexport * from './storage/memory-storage.js';\nexport * from './lifecycle/process-lifecycle.js';\nexport * from './cdp/cdp-events.js';\n\n/**\n * CaptureWorker class wrapping CaptureEngine for backwards compatibility and clean service abstraction.\n */\nexport class CaptureWorker extends CaptureEngine {\n constructor(options?: CaptureEngineOptions) {\n super(options);\n }\n}\n\n// Minimal direct executable entry point\nconst isDirectExecution =\n process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1];\n\nif (isDirectExecution) {\n const engine = new CaptureEngine({ headless: true });\n ProcessLifecycle.register(() => engine.stop());\n\n console.log('[CaptureEngine] Starting Luxray Capture Engine standalone process...');\n engine\n .start()\n .then(async () => {\n console.log('[CaptureEngine] Performing capture smoke verification...');\n const session = await engine.createCaptureSession();\n // Verify CDP communication\n const { protocolVersion } = (await session.cdpSession.send('Browser.getVersion')) as {\n protocolVersion: string;\n };\n console.log(`[CaptureEngine] Active CDP protocol version: ${protocolVersion}`);\n\n await session.close();\n await engine.stop();\n console.log('[CaptureEngine] Smoke verification completed successfully.');\n process.exit(0);\n })\n .catch((err) => {\n console.error('[CaptureEngine] Smoke verification failed:', err);\n process.exit(1);\n });\n}\n","import { chromium, type Browser, type BrowserContext, type Page, type CDPSession } from 'playwright';\nimport type { CaptureWorkerConfig } from '@luxray/shared';\n\nexport interface ManagedSession {\n readonly page: Page;\n readonly cdpSession: CDPSession;\n}\n\n/**\n * Manages Playwright Chromium lifecycle, contexts, and CDP session acquisition.\n */\nexport class BrowserManager {\n private browser: Browser | null = null;\n private context: BrowserContext | null = null;\n private readonly config: CaptureWorkerConfig;\n private readonly activeSessions = new Set<ManagedSession>();\n\n constructor(config?: Partial<CaptureWorkerConfig>) {\n this.config = {\n headless: config?.headless ?? true,\n viewport: config?.viewport ?? { width: 1280, height: 720 },\n userAgent: config?.userAgent,\n maxBodySizeBytes: config?.maxBodySizeBytes,\n maxStoredTransactions: config?.maxStoredTransactions,\n };\n }\n\n public async start(): Promise<void> {\n if (this.browser && this.context) {\n return;\n }\n\n this.browser = await chromium.launch({\n headless: this.config.headless,\n });\n\n this.context = await this.browser.newContext({\n viewport: this.config.viewport,\n userAgent: this.config.userAgent,\n });\n }\n\n /**\n * Spawns a new page and creates a dedicated CDP session for it.\n */\n public async createSession(url?: string): Promise<ManagedSession> {\n if (!this.context) {\n throw new Error('BrowserManager is not started. Call start() first.');\n }\n\n const page = await this.context.newPage();\n const cdpSession = await this.context.newCDPSession(page);\n const session: ManagedSession = { page, cdpSession };\n\n this.activeSessions.add(session);\n\n page.once('close', () => {\n this.activeSessions.delete(session);\n });\n\n if (url) {\n await page.goto(url, { waitUntil: 'domcontentloaded' });\n }\n\n return session;\n }\n\n /**\n * Closes a specific managed session.\n */\n public async closeSession(session: ManagedSession): Promise<void> {\n this.activeSessions.delete(session);\n try {\n await session.cdpSession.detach().catch(() => {});\n await session.page.close().catch(() => {});\n } catch {\n // Safe teardown\n }\n }\n\n /**\n * Shuts down all sessions, context, and browser instance.\n */\n public async stop(): Promise<void> {\n for (const session of Array.from(this.activeSessions)) {\n await this.closeSession(session);\n }\n this.activeSessions.clear();\n\n if (this.context) {\n await this.context.close().catch(() => {});\n this.context = null;\n }\n\n if (this.browser) {\n await this.browser.close().catch(() => {});\n this.browser = null;\n }\n }\n\n public isRunning(): boolean {\n return this.browser !== null && this.context !== null;\n }\n}\n\n","import type { CDPSession } from 'playwright';\nimport type {\n CDPRequestWillBeSentEvent,\n CDPResponseReceivedEvent,\n CDPLoadingFinishedEvent,\n CDPLoadingFailedEvent,\n CDPRequestWillBeSentExtraInfoEvent,\n CDPResponseReceivedExtraInfoEvent,\n} from '../cdp/cdp-events.js';\nimport type { TransactionCorrelator } from '../transaction/transaction-correlator.js';\n\nexport interface InterceptorOptions {\n /**\n * Maximum total buffer size for CDP network cache in bytes (default 10MB).\n */\n maxTotalBufferSize?: number;\n /**\n * Maximum single resource buffer size in bytes (default 5MB).\n */\n maxResourceBufferSize?: number;\n}\n\n/**\n * Manages CDP Network domain lifecycle, listeners, and event routing.\n */\nexport class NetworkInterceptor {\n private readonly cdpSession: CDPSession;\n private readonly correlator: TransactionCorrelator;\n private readonly options: InterceptorOptions;\n private isAttached = false;\n private unbindListeners: (() => void)[] = [];\n\n constructor(\n cdpSession: CDPSession,\n correlator: TransactionCorrelator,\n options?: InterceptorOptions\n ) {\n this.cdpSession = cdpSession;\n this.correlator = correlator;\n this.options = {\n maxTotalBufferSize: options?.maxTotalBufferSize ?? 10 * 1024 * 1024,\n maxResourceBufferSize: options?.maxResourceBufferSize ?? 5 * 1024 * 1024,\n };\n }\n\n /**\n * Enables CDP Network domain and wires event listeners.\n */\n public async attach(): Promise<void> {\n if (this.isAttached) {\n return;\n }\n\n // Enable Network instrumentation with buffer limits\n await this.cdpSession.send('Network.enable', {\n maxTotalBufferSize: this.options.maxTotalBufferSize,\n maxResourceBufferSize: this.options.maxResourceBufferSize,\n });\n\n const onRequestWillBeSent = (params: unknown) => {\n this.correlator.handleRequestWillBeSent(params as CDPRequestWillBeSentEvent);\n };\n\n const onResponseReceived = (params: unknown) => {\n this.correlator.handleResponseReceived(params as CDPResponseReceivedEvent);\n };\n\n const onLoadingFinished = (params: unknown) => {\n void this.correlator.handleLoadingFinished(params as CDPLoadingFinishedEvent);\n };\n\n const onLoadingFailed = (params: unknown) => {\n this.correlator.handleLoadingFailed(params as CDPLoadingFailedEvent);\n };\n\n const onRequestExtraInfo = (params: unknown) => {\n this.correlator.handleRequestExtraInfo(params as CDPRequestWillBeSentExtraInfoEvent);\n };\n\n const onResponseExtraInfo = (params: unknown) => {\n this.correlator.handleResponseExtraInfo(params as CDPResponseReceivedExtraInfoEvent);\n };\n\n this.cdpSession.on('Network.requestWillBeSent', onRequestWillBeSent);\n this.cdpSession.on('Network.responseReceived', onResponseReceived);\n this.cdpSession.on('Network.loadingFinished', onLoadingFinished);\n this.cdpSession.on('Network.loadingFailed', onLoadingFailed);\n this.cdpSession.on('Network.requestWillBeSentExtraInfo', onRequestExtraInfo);\n this.cdpSession.on('Network.responseReceivedExtraInfo', onResponseExtraInfo);\n\n this.unbindListeners = [\n () => this.cdpSession.off('Network.requestWillBeSent', onRequestWillBeSent),\n () => this.cdpSession.off('Network.responseReceived', onResponseReceived),\n () => this.cdpSession.off('Network.loadingFinished', onLoadingFinished),\n () => this.cdpSession.off('Network.loadingFailed', onLoadingFailed),\n () => this.cdpSession.off('Network.requestWillBeSentExtraInfo', onRequestExtraInfo),\n () => this.cdpSession.off('Network.responseReceivedExtraInfo', onResponseExtraInfo),\n ];\n\n this.isAttached = true;\n }\n\n /**\n * Unbinds all listeners and disables CDP Network domain.\n */\n public async detach(): Promise<void> {\n if (!this.isAttached) {\n return;\n }\n\n for (const unbind of this.unbindListeners) {\n try {\n unbind();\n } catch {\n // Safe disposal\n }\n }\n this.unbindListeners = [];\n\n try {\n await this.cdpSession.send('Network.disable');\n } catch {\n // Ignored if CDP session is already tearing down\n }\n\n this.correlator.cleanup();\n this.isAttached = false;\n }\n\n public getAttached(): boolean {\n return this.isAttached;\n }\n}\n\n","import type { CDPSession } from 'playwright';\nimport type { CDPGetResponseBodyResult } from '../cdp/cdp-events.js';\n\nexport interface BodyResolverOptions {\n /**\n * Maximum body size in bytes to store. Bodies larger than this will be truncated.\n * Default: 2MB (2,097,152 bytes)\n */\n maxBodySizeBytes?: number;\n /**\n * Maximum timeout in milliseconds to wait for CDP response body.\n * Default: 3000ms\n */\n timeoutMs?: number;\n}\n\nexport interface ResolvedBody {\n body: string | null;\n bodyEncoding: 'utf-8' | 'base64';\n bodyTruncated: boolean;\n}\n\n/**\n * Safely retrieves and bounds HTTP response bodies through Chrome DevTools Protocol.\n */\nexport class ResponseBodyResolver {\n private readonly maxBodySizeBytes: number;\n private readonly timeoutMs: number;\n\n constructor(options?: BodyResolverOptions) {\n this.maxBodySizeBytes = options?.maxBodySizeBytes ?? 2 * 1024 * 1024; // 2MB\n this.timeoutMs = options?.timeoutMs ?? 3000;\n }\n\n /**\n * Attempts to retrieve the response body for a completed request.\n * Never throws; returns null body gracefully on any failure.\n */\n public async resolve(\n cdpSession: CDPSession,\n requestId: string,\n mimeType?: string\n ): Promise<ResolvedBody> {\n try {\n const getBodyPromise = cdpSession.send('Network.getResponseBody', {\n requestId,\n }) as Promise<CDPGetResponseBodyResult>;\n\n let timer: NodeJS.Timeout | undefined;\n const timeoutPromise = new Promise<never>((_, reject) => {\n timer = setTimeout(() => {\n reject(new Error(`Timeout (${this.timeoutMs}ms) retrieving response body for ${requestId}`));\n }, this.timeoutMs);\n });\n\n const result = await Promise.race([getBodyPromise, timeoutPromise]).finally(() => {\n if (timer) clearTimeout(timer);\n });\n\n if (!result || typeof result.body !== 'string' || result.body.length === 0) {\n return { body: null, bodyEncoding: 'utf-8', bodyTruncated: false };\n }\n\n let content = result.body;\n let encoding: 'utf-8' | 'base64' = result.base64Encoded ? 'base64' : 'utf-8';\n\n // If base64-encoded text or json, decode to utf-8 if possible\n if (result.base64Encoded && this.isTextualMimeType(mimeType)) {\n try {\n content = Buffer.from(content, 'base64').toString('utf-8');\n encoding = 'utf-8';\n } catch {\n // Keep base64 if decoding fails\n }\n }\n\n // Check and enforce size bounds\n const byteLength = Buffer.byteLength(content, encoding === 'base64' ? 'base64' : 'utf-8');\n if (byteLength > this.maxBodySizeBytes) {\n // Truncate safely\n const truncated = content.slice(0, this.maxBodySizeBytes);\n return {\n body: truncated,\n bodyEncoding: encoding,\n bodyTruncated: true,\n };\n }\n\n return {\n body: content,\n bodyEncoding: encoding,\n bodyTruncated: false,\n };\n } catch {\n // Body retrieval can fail naturally for redirects, 204/304, aborted requests, or cached responses.\n return { body: null, bodyEncoding: 'utf-8', bodyTruncated: false };\n }\n }\n\n private isTextualMimeType(mimeType?: string): boolean {\n if (!mimeType) return false;\n const lower = mimeType.toLowerCase();\n return (\n lower.includes('json') ||\n lower.includes('text') ||\n lower.includes('javascript') ||\n lower.includes('xml') ||\n lower.includes('html') ||\n lower.includes('graphql')\n );\n }\n}\n","import type { CDPSession } from 'playwright';\nimport { randomUUID } from 'node:crypto';\nimport type {\n CapturedRequest,\n CapturedResponse,\n CapturedTransaction,\n HttpHeaders,\n HttpMethod,\n} from '@luxray/shared';\nimport type {\n CDPRequestWillBeSentEvent,\n CDPResponseReceivedEvent,\n CDPLoadingFinishedEvent,\n CDPLoadingFailedEvent,\n CDPRequestWillBeSentExtraInfoEvent,\n CDPResponseReceivedExtraInfoEvent,\n CDPResponse,\n} from '../cdp/cdp-events.js';\nimport type { TransactionStorage } from '../storage/transaction-storage.js';\nimport type { ResponseBodyResolver } from '../interceptor/body-resolver.js';\n\ninterface InFlightTransaction {\n readonly transactionId: string;\n readonly cdpRequestId: string;\n readonly parentTransactionId?: string;\n hopIndex: number;\n url: string;\n method: string;\n requestHeaders: HttpHeaders;\n postData?: string | null;\n startTime: number;\n initiator?: string;\n resourceType?: string;\n response?: {\n status: number;\n statusText: string;\n headers: HttpHeaders;\n mimeType?: string;\n responseTime: number;\n };\n}\n\n/**\n * Correlates asynchronous CDP Network events into unified, immutable CapturedTransactions.\n */\nexport class TransactionCorrelator {\n private readonly inFlight = new Map<string, InFlightTransaction>();\n private readonly storage: TransactionStorage;\n private readonly bodyResolver: ResponseBodyResolver;\n private readonly cdpSession: CDPSession;\n\n constructor(\n cdpSession: CDPSession,\n storage: TransactionStorage,\n bodyResolver: ResponseBodyResolver\n ) {\n this.cdpSession = cdpSession;\n this.storage = storage;\n this.bodyResolver = bodyResolver;\n }\n\n /**\n * Handles Network.requestWillBeSent.\n * Accurately tracks initial requests and handles multi-hop redirects.\n */\n public handleRequestWillBeSent(event: CDPRequestWillBeSentEvent): void {\n const existing = this.inFlight.get(event.requestId);\n\n // If redirectResponse is present, the previous request completed with a redirect status\n if (event.redirectResponse && existing) {\n this.finalizeRedirectHop(existing, event.redirectResponse, event.request.url);\n }\n\n const hopIndex = existing ? existing.hopIndex + 1 : 0;\n const transactionId = `${event.requestId}-${hopIndex}-${randomUUID().slice(0, 8)}`;\n const startTime = event.wallTime ? Math.round(event.wallTime * 1000) : Date.now();\n\n const inFlightRecord: InFlightTransaction = {\n transactionId,\n cdpRequestId: event.requestId,\n parentTransactionId: existing?.transactionId,\n hopIndex,\n url: event.request.url,\n method: event.request.method,\n requestHeaders: this.normalizeHeaders(event.request.headers),\n postData: event.request.postData ?? null,\n startTime,\n initiator: event.initiator?.type,\n resourceType: event.type,\n };\n\n this.inFlight.set(event.requestId, inFlightRecord);\n\n const initialTx: CapturedTransaction = {\n id: transactionId,\n status: 'pending',\n request: {\n id: transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: startTime,\n },\n timing: {\n startTime,\n },\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(initialTx);\n }\n\n /**\n * Handles Network.responseReceived.\n */\n public handleResponseReceived(event: CDPResponseReceivedEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n const responseTime = Date.now();\n inFlightRecord.response = {\n status: event.response.status,\n statusText: event.response.statusText,\n headers: this.normalizeHeaders(event.response.headers),\n mimeType: event.response.mimeType,\n responseTime,\n };\n\n const currentTx = this.storage.get(inFlightRecord.transactionId);\n if (currentTx) {\n const updatedTx: CapturedTransaction = {\n ...currentTx,\n response: {\n status: inFlightRecord.response.status,\n statusText: inFlightRecord.response.statusText,\n headers: inFlightRecord.response.headers,\n mimeType: inFlightRecord.response.mimeType,\n timestamp: responseTime,\n },\n timing: {\n ...currentTx.timing,\n responseTime,\n },\n };\n this.storage.save(updatedTx);\n }\n }\n\n /**\n * Handles Network.loadingFinished.\n * Resolves the response body and marks the transaction completed.\n */\n public async handleLoadingFinished(event: CDPLoadingFinishedEvent): Promise<void> {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n // Remove from in-flight tracker to free memory\n this.inFlight.delete(event.requestId);\n\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - inFlightRecord.startTime);\n\n // Safely retrieve body through resolver\n const resolvedBody = await this.bodyResolver.resolve(\n this.cdpSession,\n event.requestId,\n inFlightRecord.response?.mimeType\n );\n\n const capturedResponse: CapturedResponse | undefined = inFlightRecord.response\n ? {\n status: inFlightRecord.response.status,\n statusText: inFlightRecord.response.statusText,\n headers: inFlightRecord.response.headers,\n mimeType: inFlightRecord.response.mimeType,\n body: resolvedBody.body,\n bodyEncoding: resolvedBody.bodyEncoding,\n bodyTruncated: resolvedBody.bodyTruncated,\n timestamp: inFlightRecord.response.responseTime,\n }\n : undefined;\n\n const completedTx: CapturedTransaction = {\n id: inFlightRecord.transactionId,\n status: 'completed',\n request: {\n id: inFlightRecord.transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: inFlightRecord.startTime,\n },\n response: capturedResponse,\n timing: {\n startTime: inFlightRecord.startTime,\n responseTime: inFlightRecord.response?.responseTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(completedTx);\n }\n\n /**\n * Handles Network.loadingFailed.\n */\n public handleLoadingFailed(event: CDPLoadingFailedEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (!inFlightRecord) {\n return;\n }\n\n this.inFlight.delete(event.requestId);\n\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - inFlightRecord.startTime);\n const errorMessage = event.errorText || (event.canceled ? 'net::ERR_ABORTED' : 'net::ERR_FAILED');\n\n const failedTx: CapturedTransaction = {\n id: inFlightRecord.transactionId,\n status: 'failed',\n error: errorMessage,\n request: {\n id: inFlightRecord.transactionId,\n url: inFlightRecord.url,\n method: inFlightRecord.method as HttpMethod,\n headers: inFlightRecord.requestHeaders,\n postData: inFlightRecord.postData,\n timestamp: inFlightRecord.startTime,\n },\n timing: {\n startTime: inFlightRecord.startTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: inFlightRecord.initiator,\n resourceType: inFlightRecord.resourceType,\n parentTransactionId: inFlightRecord.parentTransactionId,\n };\n\n this.storage.save(failedTx);\n }\n\n /**\n * Handles Network.requestWillBeSentExtraInfo to enrich wire headers.\n */\n public handleRequestExtraInfo(event: CDPRequestWillBeSentExtraInfoEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (inFlightRecord) {\n inFlightRecord.requestHeaders = {\n ...inFlightRecord.requestHeaders,\n ...this.normalizeHeaders(event.headers),\n };\n }\n }\n\n /**\n * Handles Network.responseReceivedExtraInfo to enrich response wire headers.\n */\n public handleResponseExtraInfo(event: CDPResponseReceivedExtraInfoEvent): void {\n const inFlightRecord = this.inFlight.get(event.requestId);\n if (inFlightRecord && inFlightRecord.response) {\n inFlightRecord.response.headers = {\n ...inFlightRecord.response.headers,\n ...this.normalizeHeaders(event.headers),\n };\n }\n }\n\n /**\n * Finalizes the previous redirect hop as a completed redirect transaction.\n */\n private finalizeRedirectHop(\n previous: InFlightTransaction,\n redirectResponse: CDPResponse,\n targetUrl: string\n ): void {\n const endTime = Date.now();\n const durationMs = Math.max(0, endTime - previous.startTime);\n const redirectHeaders = this.normalizeHeaders(redirectResponse.headers);\n\n const redirectTx: CapturedTransaction = {\n id: previous.transactionId,\n status: 'completed',\n isRedirect: true,\n redirectUrl: targetUrl,\n request: {\n id: previous.transactionId,\n url: previous.url,\n method: previous.method as HttpMethod,\n headers: previous.requestHeaders,\n postData: previous.postData,\n timestamp: previous.startTime,\n },\n response: {\n status: redirectResponse.status,\n statusText: redirectResponse.statusText,\n headers: redirectHeaders,\n mimeType: redirectResponse.mimeType,\n body: null,\n timestamp: endTime,\n },\n timing: {\n startTime: previous.startTime,\n responseTime: endTime,\n endTime,\n durationMs,\n },\n durationMs,\n initiator: previous.initiator,\n resourceType: previous.resourceType,\n parentTransactionId: previous.parentTransactionId,\n };\n\n this.storage.save(redirectTx);\n }\n\n /**\n * Normalizes header key names to lower-case.\n */\n private normalizeHeaders(headers: Record<string, string>): HttpHeaders {\n const normalized: HttpHeaders = {};\n for (const [key, value] of Object.entries(headers)) {\n normalized[key.toLowerCase()] = String(value);\n }\n return normalized;\n }\n\n /**\n * Returns current count of in-flight tracked requests.\n */\n public getInFlightCount(): number {\n return this.inFlight.size;\n }\n\n /**\n * Cleans up all pending in-flight requests during shutdown.\n */\n public cleanup(): void {\n const now = Date.now();\n for (const [requestId, inFlightRecord] of this.inFlight) {\n const pendingTx = this.storage.get(inFlightRecord.transactionId);\n if (pendingTx && pendingTx.status === 'pending') {\n this.storage.save({\n ...pendingTx,\n status: 'failed',\n error: 'Worker session closed while request was in-flight',\n timing: {\n ...pendingTx.timing,\n endTime: now,\n durationMs: Math.max(0, now - inFlightRecord.startTime),\n },\n });\n }\n this.inFlight.delete(requestId);\n }\n }\n}\n\n","import type { CapturedTransaction } from '@luxray/shared';\nimport type { TransactionStorage } from './transaction-storage.js';\n\nexport interface InMemoryStorageOptions {\n /**\n * Maximum number of transactions retained before oldest are evicted.\n * Default: 1000\n */\n maxCapacity?: number;\n}\n\n/**\n * High-performance, memory-bounded in-memory transaction storage.\n * Maintains insertion order and enforces strict memory bounds.\n */\nexport class InMemoryTransactionStorage implements TransactionStorage {\n private readonly transactions = new Map<string, CapturedTransaction>();\n private readonly maxCapacity: number;\n private readonly listeners = new Set<(tx: CapturedTransaction) => void>();\n\n constructor(options?: InMemoryStorageOptions) {\n this.maxCapacity = Math.max(1, options?.maxCapacity ?? 1000);\n }\n\n public save(transaction: CapturedTransaction): void {\n // If updating existing, remove first to refresh insertion order\n if (this.transactions.has(transaction.id)) {\n this.transactions.delete(transaction.id);\n } else if (this.transactions.size >= this.maxCapacity) {\n // Evict oldest transaction (first key in iteration)\n const oldestKey = this.transactions.keys().next().value;\n if (oldestKey !== undefined) {\n this.transactions.delete(oldestKey);\n }\n }\n\n this.transactions.set(transaction.id, transaction);\n this.notifyListeners(transaction);\n }\n\n public get(id: string): CapturedTransaction | undefined {\n return this.transactions.get(id);\n }\n\n public getAll(): readonly CapturedTransaction[] {\n return Array.from(this.transactions.values());\n }\n\n public filter(predicate: (tx: CapturedTransaction) => boolean): CapturedTransaction[] {\n const results: CapturedTransaction[] = [];\n for (const tx of this.transactions.values()) {\n if (predicate(tx)) {\n results.push(tx);\n }\n }\n return results;\n }\n\n public getByUrl(urlSubstring: string): CapturedTransaction[] {\n return this.filter((tx) => tx.request.url.includes(urlSubstring));\n }\n\n public clear(): void {\n this.transactions.clear();\n }\n\n public size(): number {\n return this.transactions.size;\n }\n\n public onTransaction(listener: (transaction: CapturedTransaction) => void): () => void {\n this.listeners.add(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n private notifyListeners(tx: CapturedTransaction): void {\n for (const listener of this.listeners) {\n try {\n listener(tx);\n } catch (err) {\n console.error('[InMemoryTransactionStorage] Error in transaction listener:', err);\n }\n }\n }\n}\n\n","import type { Page, CDPSession } from 'playwright';\nimport type { CaptureWorkerConfig, WorkerLifecycleState } from '@luxray/shared';\nimport { BrowserManager, type ManagedSession } from './browser/browser-manager.js';\nimport { NetworkInterceptor } from './interceptor/network-interceptor.js';\nimport { ResponseBodyResolver } from './interceptor/body-resolver.js';\nimport { TransactionCorrelator } from './transaction/transaction-correlator.js';\nimport { InMemoryTransactionStorage } from './storage/memory-storage.js';\nimport type { TransactionStorage } from './storage/transaction-storage.js';\n\nexport interface CaptureSession {\n readonly page: Page;\n readonly cdpSession: CDPSession;\n readonly interceptor: NetworkInterceptor;\n readonly correlator: TransactionCorrelator;\n close(): Promise<void>;\n}\n\nexport interface CaptureEngineOptions extends Partial<CaptureWorkerConfig> {\n storage?: TransactionStorage;\n}\n\n/**\n * High-level coordinator orchestrating browser automation, CDP network interception,\n * event correlation, and transaction storage.\n */\nexport class CaptureEngine {\n private readonly browserManager: BrowserManager;\n private readonly storage: TransactionStorage;\n private readonly bodyResolver: ResponseBodyResolver;\n private readonly activeSessions = new Set<CaptureSession>();\n private state: WorkerLifecycleState = 'uninitialized';\n\n constructor(options?: CaptureEngineOptions) {\n this.browserManager = new BrowserManager(options);\n this.storage =\n options?.storage ??\n new InMemoryTransactionStorage({\n maxCapacity: options?.maxStoredTransactions ?? 1000,\n });\n this.bodyResolver = new ResponseBodyResolver({\n maxBodySizeBytes: options?.maxBodySizeBytes,\n });\n }\n\n public getState(): WorkerLifecycleState {\n return this.state;\n }\n\n public getStorage(): TransactionStorage {\n return this.storage;\n }\n\n /**\n * Initializes browser runtime.\n */\n public async start(): Promise<void> {\n if (this.state === 'running' || this.state === 'starting') {\n return;\n }\n\n this.state = 'starting';\n try {\n await this.browserManager.start();\n this.state = 'running';\n console.log('[CaptureEngine] Capture engine initialized successfully.');\n } catch (error) {\n this.state = 'error';\n console.error('[CaptureEngine] Failed to initialize capture engine:', error);\n await this.stop();\n throw error;\n }\n }\n\n /**\n * Creates an instrumented page with network capture actively running.\n */\n public async createCaptureSession(url?: string): Promise<CaptureSession> {\n if (this.state !== 'running') {\n throw new Error(`CaptureEngine is not running. Current state: ${this.state}`);\n }\n\n const managed: ManagedSession = await this.browserManager.createSession();\n const correlator = new TransactionCorrelator(\n managed.cdpSession,\n this.storage,\n this.bodyResolver\n );\n const interceptor = new NetworkInterceptor(managed.cdpSession, correlator);\n\n // Attach CDP network domain before navigation to ensure zero dropped packets\n await interceptor.attach();\n\n const session: CaptureSession = {\n page: managed.page,\n cdpSession: managed.cdpSession,\n interceptor,\n correlator,\n close: async () => {\n this.activeSessions.delete(session);\n await interceptor.detach().catch(() => {});\n await this.browserManager.closeSession(managed).catch(() => {});\n },\n };\n\n this.activeSessions.add(session);\n\n managed.page.once('close', () => {\n this.activeSessions.delete(session);\n void interceptor.detach().catch(() => {});\n });\n\n if (url) {\n await managed.page.goto(url, { waitUntil: 'domcontentloaded' });\n }\n\n return session;\n }\n\n /**\n * Gracefully shuts down all sessions, interceptors, and the browser process.\n */\n public async stop(): Promise<void> {\n if (this.state === 'stopping' || this.state === 'stopped') {\n return;\n }\n\n this.state = 'stopping';\n console.log('[CaptureEngine] Stopping capture engine and clearing sessions...');\n\n try {\n for (const session of Array.from(this.activeSessions)) {\n await session.close().catch(() => {});\n }\n this.activeSessions.clear();\n\n await this.browserManager.stop().catch(() => {});\n this.state = 'stopped';\n console.log('[CaptureEngine] Capture engine stopped gracefully.');\n } catch (error) {\n this.state = 'error';\n console.error('[CaptureEngine] Error while stopping capture engine:', error);\n throw error;\n }\n }\n}\n\n","export type ShutdownHandler = (signal: string) => Promise<void>;\n\n/**\n * Manages clean OS signal trapping, exception monitoring, and orderly exit.\n */\nexport class ProcessLifecycle {\n private static isShuttingDown = false;\n\n public static register(handler: ShutdownHandler): () => void {\n const onSignal = (signal: string) => {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n console.log(`\\n[ProcessLifecycle] Received ${signal}. Initiating orderly teardown...`);\n\n handler(signal)\n .then(() => {\n process.exit(0);\n })\n .catch((err) => {\n console.error('[ProcessLifecycle] Error during teardown:', err);\n process.exit(1);\n });\n };\n\n const sigintListener = () => onSignal('SIGINT');\n const sigtermListener = () => onSignal('SIGTERM');\n\n const unhandledRejectionListener = (reason: unknown) => {\n console.error('[ProcessLifecycle] Unhandled Rejection:', reason);\n };\n\n const uncaughtExceptionListener = (error: Error) => {\n console.error('[ProcessLifecycle] Uncaught Exception:', error);\n onSignal('uncaughtException');\n };\n\n process.on('SIGINT', sigintListener);\n process.on('SIGTERM', sigtermListener);\n process.on('unhandledRejection', unhandledRejectionListener);\n process.on('uncaughtException', uncaughtExceptionListener);\n\n return () => {\n process.off('SIGINT', sigintListener);\n process.off('SIGTERM', sigtermListener);\n process.off('unhandledRejection', unhandledRejectionListener);\n process.off('uncaughtException', uncaughtExceptionListener);\n };\n }\n\n public static resetForTesting(): void {\n this.isShuttingDown = false;\n }\n}\n\n","import type { BrowserContext, Page } from 'playwright';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport {\n InMemoryTransactionStorage,\n NetworkInterceptor,\n ResponseBodyResolver,\n TransactionCorrelator,\n} from '@luxray/capture-worker';\n\nexport interface TaskCaptureOptions {\n /** Transactions retained in memory for one task. */\n readonly maxTransactions?: number;\n readonly maxBodySizeBytes?: number;\n}\n\n/**\n * Wires the existing capture engine's CDP interceptor into one task context.\n *\n * The engine is reused rather than reimplemented: request/response correlation,\n * redirect handling and body decoding are the parts Milestone 1 already proved.\n * What this class adds is attribution: transactions are collected into a\n * per-page window so an observation can say how much network traffic that page\n * produced.\n */\nexport class TaskCapture {\n private readonly all = new Map<string, CapturedTransaction>();\n private current = new Map<string, CapturedTransaction>();\n private disposed = false;\n\n private constructor(\n private readonly cdpSession: Awaited<ReturnType<BrowserContext['newCDPSession']>>,\n private readonly interceptor: NetworkInterceptor,\n private readonly correlator: TransactionCorrelator,\n private readonly storage: InMemoryTransactionStorage,\n ) {\n this.storage.onTransaction((transaction) => {\n if (this.disposed) return;\n this.all.set(transaction.id, transaction);\n this.current.set(transaction.id, transaction);\n });\n }\n\n public static async attach(\n context: BrowserContext,\n page: Page,\n options?: TaskCaptureOptions,\n ): Promise<TaskCapture> {\n const cdpSession = await context.newCDPSession(page);\n const storage = new InMemoryTransactionStorage({\n maxCapacity: options?.maxTransactions ?? 5_000,\n });\n const correlator = new TransactionCorrelator(\n cdpSession,\n storage,\n new ResponseBodyResolver({ maxBodySizeBytes: options?.maxBodySizeBytes }),\n );\n const interceptor = new NetworkInterceptor(cdpSession, correlator);\n await interceptor.attach();\n return new TaskCapture(cdpSession, interceptor, correlator, storage);\n }\n\n /** Starts a fresh attribution window for the next navigation. */\n public beginPage(): void {\n this.current = new Map();\n }\n\n /**\n * Ends the window and returns every transaction seen in it. Sub-resources that\n * finish after this call are attributed to the next page; that only affects\n * counters, never crawl decisions.\n */\n public endPage(): CapturedTransaction[] {\n const transactions = Array.from(this.current.values());\n this.current = new Map();\n return transactions;\n }\n\n public allTransactions(): CapturedTransaction[] {\n return Array.from(this.all.values());\n }\n\n public async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n await this.interceptor.detach().catch(() => {});\n this.correlator.cleanup();\n await this.cdpSession.detach().catch(() => {});\n }\n}\n","export interface FrontierEntry {\n readonly url: string;\n readonly depth: number;\n}\n\n/**\n * Breadth-first frontier with canonical-URL deduplication.\n *\n * BFS rather than DFS keeps page order reproducible and makes \"closest pages\n * first\" true when a page limit truncates the crawl.\n */\nexport class Frontier {\n private readonly queue: FrontierEntry[] = [];\n private readonly seen = new Set<string>();\n\n constructor(\n startUrl: string,\n private readonly maxDepth: number,\n ) {\n this.enqueue(startUrl, 0);\n }\n\n /** Returns false when the URL was already scheduled or is too deep. */\n public enqueue(url: string, depth: number): boolean {\n if (depth > this.maxDepth) return false;\n if (this.seen.has(url)) return false;\n this.seen.add(url);\n this.queue.push({ url, depth });\n return true;\n }\n\n public next(): FrontierEntry | null {\n return this.queue.shift() ?? null;\n }\n\n public has(url: string): boolean {\n return this.seen.has(url);\n }\n\n public get size(): number {\n return this.queue.length;\n }\n\n public get scheduled(): number {\n return this.seen.size;\n }\n}\n","/**\n * URL canonicalization for deterministic crawls.\n *\n * Two spellings of the same resource must map to one string, otherwise the\n * frontier grows with duplicates and the same page is fetched repeatedly. The\n * rules here are deliberately conservative and documented: anything they drop\n * is either meaningless to an origin server or is a known tracking parameter.\n */\n\nconst DEFAULT_PORTS: Record<string, string> = {\n 'http:': '80',\n 'https:': '443',\n};\n\n/**\n * Query parameters that identify a campaign, not a resource. Removing them\n * keeps `?utm_source=x` from being crawled as a separate page from `/`.\n */\nconst TRACKING_PARAM_PREFIXES = ['utm_'];\nconst TRACKING_PARAMS = new Set(['fbclid', 'gclid', 'mc_cid', 'mc_eid', 'igshid']);\n\nexport interface CanonicalizeOptions {\n /** Base used to resolve relative URLs. Omit for absolute-only input. */\n readonly base?: string;\n}\n\n/**\n * Returns the canonical absolute form of an http(s) URL, or null when the input\n * is not an http(s) URL (mailto:, javascript:, data:, malformed...).\n */\nexport function canonicalizeUrl(raw: string, options?: CanonicalizeOptions): string | null {\n let parsed: URL;\n try {\n parsed = options?.base ? new URL(raw, options.base) : new URL(raw);\n } catch {\n return null;\n }\n\n if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') return null;\n\n const url = new URL(parsed.toString());\n url.protocol = url.protocol.toLowerCase();\n url.hostname = url.hostname.toLowerCase();\n url.hash = '';\n\n // `URL` already drops the port when it equals the scheme default, but an\n // explicit default port in the input must not survive as a difference.\n const defaultPort = DEFAULT_PORTS[url.protocol];\n if (defaultPort && url.port === defaultPort) url.port = '';\n\n // Duplicate slashes are the same path for every server we target.\n url.pathname = url.pathname.replace(/\\/{2,}/g, '/');\n if (url.pathname.length > 1 && url.pathname.endsWith('/')) {\n url.pathname = url.pathname.slice(0, -1);\n }\n\n // Stable query order: two URLs with the same parameters in a different order\n // are the same resource.\n const entries = Array.from(url.searchParams.entries()).filter(([key]) => !isTrackingParam(key));\n entries.sort(([aKey, aValue], [bKey, bValue]) => {\n if (aKey === bKey) return aValue < bValue ? -1 : aValue > bValue ? 1 : 0;\n return aKey < bKey ? -1 : 1;\n });\n url.search = '';\n for (const [key, value] of entries) {\n url.searchParams.append(key, value);\n }\n\n return url.toString();\n}\n\nfunction isTrackingParam(key: string): boolean {\n const normalized = key.toLowerCase();\n if (TRACKING_PARAMS.has(normalized)) return true;\n return TRACKING_PARAM_PREFIXES.some((prefix) => normalized.startsWith(prefix));\n}\n\n/** Hostname of a canonical URL, or null when it cannot be parsed. */\nexport function hostnameOf(url: string): string | null {\n try {\n return new URL(url).hostname.toLowerCase();\n } catch {\n return null;\n }\n}\n","import { hostnameOf } from './url-canonicalizer.js';\n\nexport interface CrawlScope {\n readonly allowedDomains: readonly string[];\n readonly includeSubdomains: boolean;\n}\n\n/**\n * Hosts that answer with cloud credentials rather than application data. A\n * crawl must never reach them, even when the operator put the whole domain in\n * scope: `169.254.169.254` is the EC2/GCP metadata service.\n */\nconst BLOCKED_HOSTS = new Set([\n 'metadata.google.internal',\n 'metadata.goog',\n 'instance-data',\n '169.254.169.254',\n '100.100.100.200',\n 'fd00:ec2::254',\n]);\n\n/** Link-local ranges, where metadata endpoints live. */\nfunction isLinkLocal(host: string): boolean {\n return host.startsWith('169.254.') || host.startsWith('fe80:') || host.startsWith('[fe80:');\n}\n\nexport function isBlockedHost(host: string): boolean {\n const normalized = host.toLowerCase().replace(/^\\[|\\]$/g, '');\n if (BLOCKED_HOSTS.has(host.toLowerCase()) || BLOCKED_HOSTS.has(normalized)) return true;\n return isLinkLocal(normalized);\n}\n\n/**\n * True when a canonical URL may be crawled under this scope. The start host is\n * always allowed (the caller puts it in `allowedDomains`).\n */\nexport function isUrlInScope(url: string, scope: CrawlScope): boolean {\n const host = hostnameOf(url);\n if (!host) return false;\n if (isBlockedHost(host)) return false;\n\n return scope.allowedDomains.some((domain) => {\n if (host === domain) return true;\n return scope.includeSubdomains && host.endsWith(`.${domain}`);\n });\n}\n\n/** Extracts the hostname to treat as the crawl origin. */\nexport function startHostname(startUrl: string): string {\n const host = hostnameOf(startUrl);\n if (!host) {\n throw new Error(`Cannot determine the hostname of ${startUrl}.`);\n }\n return host;\n}\n\nexport function assertCrawlTarget(url: string): void {\n const host = hostnameOf(url);\n if (!host) {\n throw new Error(`Refusing to crawl an invalid URL: ${url}`);\n }\n if (isBlockedHost(host)) {\n throw new Error(\n `Refusing to crawl ${host}: it is a cloud metadata endpoint and must never be fetched.`,\n );\n }\n}\n","import type { Page } from 'playwright';\nimport type { CapturedTransaction } from '@luxray/shared';\nimport { signIn, type LoginResult, type SiteCredentials } from '../auth/login.js';\nimport type { AuthCookie, TaskBrowser } from '../browser/task-browser.js';\nimport {\n extractJsonLinks,\n jsonDocumentFingerprint,\n readPageSnapshot,\n structuralFingerprint,\n} from '../browser/page-snapshot.js';\nimport { TaskCapture } from '../browser/task-capture.js';\nimport { ExplorationAbortedError } from '../errors.js';\nimport { Frontier } from './frontier.js';\nimport { canonicalizeUrl } from './url-canonicalizer.js';\nimport { isUrlInScope, type CrawlScope } from './url-policy.js';\nimport {\n type AuthenticationSummary,\n type ExplorationLimits,\n type ExplorationRun,\n type PageObservation,\n} from './types.js';\n\nexport interface CrawlLogger {\n info: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n}\n\n/**\n * Operator-supplied authentication, applied before the first page is observed.\n *\n * Two shapes are supported and they are deliberately exclusive: a form sign-in\n * is a sequence of interactions, while auth keys are values the browser sends\n * with every request. Passing both would make it ambiguous which one the site\n * actually accepted, and the run record has to say something true.\n */\nexport interface CrawlAuthOptions {\n /** Form sign-in. */\n readonly credentials?: SiteCredentials;\n /** Defaults to the crawl's start URL. */\n readonly loginUrl?: string;\n readonly submitTimeoutMs?: number;\n readonly manualAssist?: () => Promise<void>;\n /** Arbitrary request headers, e.g. `Authorization: Bearer …`. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Cookies installed on the task context before the first navigation. */\n readonly cookies?: readonly AuthCookie[];\n}\n\nexport interface CrawlOptions {\n readonly limits: ExplorationLimits;\n readonly scope: CrawlScope;\n readonly signal?: AbortSignal;\n readonly onProgress?: (percent: number, message: string) => void;\n readonly onCheckpoint?: (label: string, state: Record<string, unknown>) => void;\n /**\n * Fires once per observation, in visit order.\n *\n * A transport failure here must never abort a crawl: the artifact directory\n * is still the full record, and the page can be replayed from it. The crawler\n * therefore swallows hook errors and logs them.\n */\n readonly onPage?: (page: PageObservation, sequence: number) => void;\n readonly logger?: CrawlLogger;\n readonly auth?: CrawlAuthOptions;\n /** Restore a saved session instead of signing in. */\n readonly storageStatePath?: string;\n /** Persist the session after a successful sign-in. */\n readonly saveStorageStatePath?: string;\n}\n\nexport interface CrawlOutcome {\n readonly run: ExplorationRun;\n readonly transactions: readonly CapturedTransaction[];\n}\n\nconst RECENT_URLS_IN_CHECKPOINT = 10;\nconst BODY_SETTLE_GRACE_MS = 250;\n\ninterface ObservationResult {\n readonly observation: PageObservation;\n /** Links to follow, already canonical and in scope. Empty for duplicates. */\n readonly nextUrls: readonly string[];\n}\n\n/**\n * Deterministic breadth-first discovery.\n *\n * The rule set is mechanical on purpose: follow in-scope links, hash the\n * rendered structure, and stop expanding pages that repeat a template already\n * seen. No model decides what to click, so the same site produces the same order\n * and any failure is explainable by a URL and a limit.\n */\nexport class DeterministicCrawler {\n constructor(\n private readonly browser: TaskBrowser,\n private readonly options: CrawlOptions,\n ) {}\n\n public async run(startUrl: string): Promise<CrawlOutcome> {\n const { limits, scope, signal, onProgress, onCheckpoint, onPage, logger } = this.options;\n\n const canonicalStart = canonicalizeUrl(startUrl);\n if (!canonicalStart) {\n throw new Error(`Cannot explore ${startUrl}: it is not a valid http(s) URL.`);\n }\n if (!isUrlInScope(canonicalStart, scope)) {\n throw new Error(\n `${canonicalStart} is outside the allowed domains (${scope.allowedDomains.join(', ')}).`,\n );\n }\n\n const authOptions = this.options.auth;\n const authHeaders = authOptions?.headers ?? {};\n const authCookies = authOptions?.cookies ?? [];\n const headerCount = Object.keys(authHeaders).length;\n const keyAuth = headerCount > 0 || authCookies.length > 0;\n const formAuth = Boolean(authOptions?.credentials);\n\n if (keyAuth && formAuth) {\n throw new Error(\n 'Pass either sign-in credentials (--login-url/--username) or auth keys ' +\n '(--auth-header/--auth-cookie), not both.',\n );\n }\n\n const context = await this.browser.openTaskContext({\n storageState: this.options.storageStatePath,\n headers: authHeaders,\n cookies: authCookies,\n cookieUrl: canonicalStart,\n });\n\n let authentication: AuthenticationSummary | null = keyAuth\n ? {\n strategy: headerCount > 0 ? 'headers' : 'cookies',\n loginUrl: null,\n finalUrl: null,\n cookies: authCookies.length,\n headers: headerCount,\n }\n : this.options.storageStatePath\n ? { strategy: 'session', loginUrl: null, finalUrl: null, cookies: null, headers: 0 }\n : null;\n\n // Sign in before the crawl page exists. The sign-in runs on its own page,\n // so the credential POST is never attributed to a crawl window or written\n // to the artifacts.\n if (formAuth && authOptions?.credentials) {\n const loginUrl = authOptions.loginUrl ?? canonicalStart;\n onProgress?.(0, `Signing in at ${loginUrl}`);\n logger?.info(`Signing in at ${loginUrl} before crawling.`);\n let signedIn: LoginResult;\n try {\n signedIn = await signIn(context, {\n loginUrl,\n credentials: authOptions.credentials,\n pageTimeoutMs: limits.pageTimeoutMs,\n submitTimeoutMs: authOptions.submitTimeoutMs,\n manualAssist: authOptions.manualAssist,\n signal,\n logger,\n });\n } catch (err) {\n await context.close().catch(() => {});\n throw err;\n }\n\n authentication = {\n strategy: signedIn.strategy,\n loginUrl: signedIn.loginUrl,\n finalUrl: signedIn.finalUrl,\n cookies: signedIn.cookies,\n headers: 0,\n };\n logger?.info(\n `Signed in (${signedIn.strategy}); ${signedIn.cookies} cookie(s) in the task context.`,\n );\n\n if (this.options.saveStorageStatePath) {\n try {\n await context.storageState({ path: this.options.saveStorageStatePath });\n logger?.info(`Session saved to ${this.options.saveStorageStatePath}.`);\n } catch (err) {\n logger?.warn(`Could not save the session: ${(err as Error).message}`);\n }\n }\n }\n\n // A crawl with no auth at all is expected to meet sign-in walls; it must\n // mark them instead of counting the login form as the page it asked for.\n const anonymous = authentication === null;\n\n const page = await context.newPage();\n const capture = await TaskCapture.attach(context, page);\n const abort = (): void => {\n // Closing the context is what interrupts a hung navigation; the loop below\n // only checks the flag between pages.\n void context.close().catch(() => {});\n };\n signal?.addEventListener('abort', abort, { once: true });\n\n const startedAt = Date.now();\n const frontier = new Frontier(canonicalStart, limits.maxDepth);\n const pages: PageObservation[] = [];\n const fingerprints = new Map<string, string>();\n let transactionsCaptured = 0;\n let linksDiscovered = 0;\n let truncatedByLimit = false;\n\n try {\n onProgress?.(0, `Opening ${canonicalStart}`);\n logger?.info(\n `Exploring ${canonicalStart} (max ${limits.maxPages} pages, depth ${limits.maxDepth}).`,\n );\n\n while (true) {\n if (signal?.aborted) throw new ExplorationAbortedError();\n\n if (pages.length >= limits.maxPages) {\n truncatedByLimit = frontier.size > 0;\n logger?.info(`Page limit reached (${limits.maxPages}); stopping.`);\n break;\n }\n const elapsed = Date.now() - startedAt;\n if (elapsed >= limits.maxDurationMs) {\n truncatedByLimit = frontier.size > 0;\n logger?.warn(`Time limit reached after ${elapsed}ms; stopping.`);\n break;\n }\n\n const entry = frontier.next();\n if (!entry) break;\n\n const { observation, nextUrls } = await this.observe(\n page,\n capture,\n entry.url,\n entry.depth,\n fingerprints,\n signal,\n anonymous,\n );\n pages.push(observation);\n transactionsCaptured += observation.transactions;\n linksDiscovered += observation.linksFound;\n\n let queued = 0;\n for (const nextUrl of nextUrls) {\n if (frontier.enqueue(nextUrl, entry.depth + 1)) queued += 1;\n }\n const recorded: PageObservation = { ...observation, linksQueued: queued };\n pages[pages.length - 1] = recorded;\n\n if (onPage) {\n try {\n onPage(recorded, pages.length);\n } catch (err) {\n logger?.warn(\n `Page hook failed for ${entry.url}: ${(err as Error).message}. Continuing the crawl.`,\n );\n }\n }\n\n const percent = Math.min(\n 95,\n Math.floor((pages.length / Math.max(1, limits.maxPages)) * 100),\n );\n const suffix = observation.authRequired\n ? ' (authentication required; skipped)'\n : observation.error\n ? ` (failed: ${observation.error})`\n : observation.duplicateOf\n ? ` (duplicate template of ${observation.duplicateOf}, links not followed)`\n : ` (+${queued} links, ${observation.transactions} requests)`;\n onProgress?.(percent, `page ${pages.length}/${limits.maxPages} — ${entry.url}${suffix}`);\n logger?.info(`[${pages.length}/${limits.maxPages}] ${entry.url}${suffix}`);\n\n if (onCheckpoint && pages.length % limits.checkpointEveryPages === 0) {\n onCheckpoint(`pages:${pages.length}`, {\n startUrl: canonicalStart,\n pagesVisited: pages.length,\n pagesFailed: pages.filter((item) => item.error !== null).length,\n duplicatePages: pages.filter((item) => item.duplicateOf !== null).length,\n transactionsCaptured,\n linksDiscovered,\n frontierQueued: frontier.size,\n frontierScheduled: frontier.scheduled,\n recentUrls: pages.slice(-RECENT_URLS_IN_CHECKPOINT).map((item) => item.url),\n elapsedMs: Date.now() - startedAt,\n });\n }\n }\n\n const finishedAt = Date.now();\n const run: ExplorationRun = {\n summary: {\n startUrl: canonicalStart,\n startedAt,\n finishedAt,\n durationMs: finishedAt - startedAt,\n pagesVisited: pages.length,\n pagesFailed: pages.filter((item) => item.error !== null).length,\n duplicatePages: pages.filter((item) => item.duplicateOf !== null).length,\n transactionsCaptured,\n linksDiscovered,\n frontierRemaining: frontier.size,\n limits,\n artifactDir: '',\n truncatedByLimit,\n authentication: authentication,\n },\n pages,\n scope,\n };\n\n return { run, transactions: capture.allTransactions() };\n } finally {\n signal?.removeEventListener('abort', abort);\n await capture.dispose().catch(() => {});\n await context.close().catch(() => {});\n }\n }\n\n private async observe(\n page: Page,\n capture: TaskCapture,\n url: string,\n depth: number,\n fingerprints: Map<string, string>,\n signal: AbortSignal | undefined,\n anonymous: boolean,\n ): Promise<ObservationResult> {\n const { limits, scope } = this.options;\n const observedAt = Date.now();\n capture.beginPage();\n\n let httpStatus: number | null = null;\n let title: string | null = null;\n let hrefs: readonly string[] = [];\n let fingerprint = 'unavailable';\n let duplicateOf: string | null = null;\n let error: string | null = null;\n let authRequired = false;\n\n try {\n const response = await page.goto(url, {\n waitUntil: 'domcontentloaded',\n timeout: limits.pageTimeoutMs,\n });\n httpStatus = response?.status() ?? null;\n\n // Best effort: apps with long-lived connections never reach network idle,\n // so this wait is bounded and its timeout is not an error.\n await page\n .waitForLoadState('networkidle', { timeout: limits.settleTimeoutMs })\n .catch(() => {});\n await new Promise((resolve) => setTimeout(resolve, BODY_SETTLE_GRACE_MS));\n\n if (signal?.aborted) throw new ExplorationAbortedError();\n\n const snapshot = await readPageSnapshot(page);\n title = snapshot.title;\n\n // JSON documents have no anchors; the payload itself is the link index.\n // Candidates go through the same canonicalization and scope filter below,\n // and `linksFound` counts both sources because both were discovered.\n const jsonLinks =\n snapshot.jsonBody === null ? [] : extractJsonLinks(snapshot.jsonBody);\n hrefs = [...snapshot.links, ...jsonLinks];\n\n // The JSON viewer's markup is identical for every response, so the\n // structure hash would collapse unrelated endpoints into one duplicate.\n fingerprint =\n snapshot.jsonBody === null\n ? structuralFingerprint(snapshot.structure)\n : jsonDocumentFingerprint(snapshot.jsonBody);\n\n if (snapshot.jsonBodyTruncated) {\n this.options.logger?.debug(\n `JSON body at ${url} exceeded the snapshot limit; fingerprint truncated, links not mined.`,\n );\n }\n\n // Only an unauthenticated crawl can be \"walled\": with a session or keys,\n // a password field is ordinary page content (change password, admin).\n authRequired =\n anonymous &&\n (snapshot.hasPasswordField || isAuthRedirect(url, page.url()));\n } catch (err) {\n if (signal?.aborted || err instanceof ExplorationAbortedError) {\n throw new ExplorationAbortedError();\n }\n error = errorMessage(err);\n }\n\n // A walled page is not the page the frontier asked for, and its links lead\n // back into the gate. It is recorded as gated rather than expanded.\n if (error === null && !authRequired) {\n const seenOn = fingerprints.get(fingerprint);\n if (seenOn === undefined) {\n fingerprints.set(fingerprint, url);\n } else {\n duplicateOf = seenOn;\n }\n }\n\n const transactions = capture.endPage();\n const nextUrls =\n duplicateOf === null && error === null && !authRequired\n ? this.resolveLinks(hrefs, url, scope)\n : [];\n\n return {\n observation: {\n url,\n requestedUrl: url,\n depth,\n httpStatus,\n title,\n fingerprint,\n duplicateOf,\n linksFound: hrefs.length,\n linksQueued: 0,\n transactions: transactions.length,\n durationMs: Date.now() - observedAt,\n observedAt,\n error,\n authRequired: authRequired,\n },\n nextUrls,\n };\n }\n\n private resolveLinks(\n hrefs: readonly string[],\n baseUrl: string,\n scope: CrawlScope,\n ): readonly string[] {\n const resolved: string[] = [];\n const unique = new Set<string>();\n for (const href of hrefs) {\n const canonical = canonicalizeUrl(href, { base: baseUrl });\n if (!canonical) continue;\n if (!isUrlInScope(canonical, scope)) continue;\n if (unique.has(canonical)) continue;\n unique.add(canonical);\n resolved.push(canonical);\n }\n return resolved;\n }\n}\n\nfunction errorMessage(error: unknown): string {\n const message = error instanceof Error ? error.message : String(error);\n return message.length > 500 ? `${message.slice(0, 500)}…` : message;\n}\n\n/**\n * Sign-in paths seen in the wild, as a path segment.\n *\n * Kept narrow on purpose: `/account` or `/auth-docs` are ordinary pages, so the\n * segment must be one of these exact names. A false positive would hide a page\n * from the crawl, which is worse than crawling one login form.\n */\nconst AUTH_PATH_SEGMENT =\n /(?:^|\\/)(?:login|log-in|log_in|signin|sign-in|sign_in|sso|session|oauth2?|authorize)(?:\\/|$)/i;\n\n/** True when a navigation was redirected to a sign-in route. */\nfunction isAuthRedirect(requestedUrl: string, finalUrl: string): boolean {\n if (finalUrl === requestedUrl) return false;\n try {\n return AUTH_PATH_SEGMENT.test(new URL(finalUrl).pathname);\n } catch {\n return false;\n }\n}\n","/**\n * Bounds for one deterministic exploration run.\n *\n * Every limit is enforced locally by the worker; the control plane also stores\n * `scope.maxPages` and `scope.maxDepth` with the task, and the runner passes\n * those values in. The remaining limits protect the machine the agent runs on,\n * so they are local defaults rather than task data.\n */\nexport interface ExplorationLimits {\n readonly maxPages: number;\n readonly maxDepth: number;\n /** Navigation timeout for a single page. */\n readonly pageTimeoutMs: number;\n /** How long to wait for quiet network after DOM content loaded. */\n readonly settleTimeoutMs: number;\n /** Hard wall-clock limit for the whole run. */\n readonly maxDurationMs: number;\n /** Emit a durable checkpoint every N visited pages. */\n readonly checkpointEveryPages: number;\n}\n\nexport const DEFAULT_EXPLORATION_LIMITS: ExplorationLimits = Object.freeze({\n maxPages: 25,\n maxDepth: 2,\n pageTimeoutMs: 20_000,\n settleTimeoutMs: 3_000,\n maxDurationMs: 8 * 60_000,\n checkpointEveryPages: 5,\n});\n\nexport interface ExplorationScope {\n readonly allowedDomains: readonly string[];\n readonly includeSubdomains: boolean;\n}\n\n/** One page the crawl actually loaded and observed. */\nexport interface PageObservation {\n /** Canonical URL used as the dedupe key. */\n readonly url: string;\n /** URL the browser was asked for, before canonicalization. */\n readonly requestedUrl: string;\n readonly depth: number;\n readonly httpStatus: number | null;\n readonly title: string | null;\n /** Structural hash of the rendered DOM; identical pages share a hash. */\n readonly fingerprint: string;\n /** First page with the same fingerprint, when this page was a duplicate. */\n readonly duplicateOf: string | null;\n readonly linksFound: number;\n readonly linksQueued: number;\n readonly transactions: number;\n readonly durationMs: number;\n readonly observedAt: number;\n readonly error: string | null;\n /**\n * True when the response was a sign-in wall rather than the page's content.\n *\n * Anonymous crawls mark these instead of counting the login form as the\n * visited page, so a dashboard can tell \"not crawled\" from \"crawled empty\".\n */\n readonly authRequired: boolean;\n}\n\nexport interface ExplorationRunSummary {\n readonly startUrl: string;\n readonly startedAt: number;\n readonly finishedAt: number;\n readonly durationMs: number;\n readonly pagesVisited: number;\n readonly pagesFailed: number;\n readonly duplicatePages: number;\n readonly transactionsCaptured: number;\n readonly linksDiscovered: number;\n readonly frontierRemaining: number;\n readonly limits: ExplorationLimits;\n readonly artifactDir: string;\n /** True when a limit stopped the crawl rather than an empty frontier. */\n readonly truncatedByLimit: boolean;\n /**\n * Present when the operator asked for a signed-in crawl. Counts and URLs\n * only: credentials are never part of a run record.\n */\n readonly authentication?: AuthenticationSummary | null;\n}\n\n/**\n * What the run record may say about authentication. Counts and URLs only:\n * credential values are never part of a run record.\n *\n * `null` fields are meaningful: a headers/cookies run has no sign-in URL, and a\n * restored session's cookie count is unknown without opening the context.\n */\nexport interface AuthenticationSummary {\n readonly strategy: 'form' | 'manual' | 'headers' | 'cookies' | 'session';\n readonly loginUrl: string | null;\n readonly finalUrl: string | null;\n readonly cookies: number | null;\n /** Number of request headers supplied by the operator. */\n readonly headers: number;\n}\n\nexport interface ExplorationRun {\n readonly summary: ExplorationRunSummary;\n readonly pages: readonly PageObservation[];\n readonly scope: ExplorationScope;\n}\n","import { writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type {\n CapturedTransaction,\n ExplorationOpenApiDocument,\n ExplorationOpenApiSpec,\n} from '@luxray/shared';\nimport { EndpointAggregator, EndpointNormalizer } from '@luxray/normalization';\nimport {\n OpenApiGenerator,\n serializeToJson,\n serializeToYaml,\n} from '@luxray/openapi-generator';\nimport { RelationshipDiscoveryEngine } from '@luxray/relationship-discovery';\nimport { SchemaInferenceEngine } from '@luxray/schema-inference';\n\n/**\n * Budget for the two documents carried in one completion frame.\n *\n * Kafka's default record limit is 1 MiB. The structured report already takes\n * up to 64 KiB of the frame, and the envelope adds a little more, so the specs\n * are held well below the limit instead of relying on broker configuration.\n */\nexport const OPENAPI_TRANSPORT_BUDGET_BYTES = 768 * 1024;\n\n/** Capture resource types that represent programmatic API traffic. */\nconst API_RESOURCE_TYPES = new Set(['xhr', 'fetch']);\n\n/**\n * Resource types that are the operation itself rather than a page load.\n *\n * On an API-first host the address bar is the only client, so every endpoint a\n * crawl visits arrives as a `document` navigation. A JSON payload proves the\n * response is data, not markup, which is enough to document it.\n */\nconst DATA_DOCUMENT_RESOURCE_TYPES = new Set(['document']);\n\n/** Response media types that are never API payloads worth documenting. */\nconst NON_API_MIME_PREFIXES = ['image/', 'audio/', 'video/', 'font/'];\n\nexport interface GenerateOpenApiSpecInput {\n readonly taskId: string;\n readonly attempt: number;\n readonly startUrl: string;\n /** Document title; usually the task name. */\n readonly title: string;\n readonly transactions: readonly CapturedTransaction[];\n readonly now?: () => number;\n}\n\n/**\n * True when a captured transaction belongs in the discovered API contract.\n *\n * The crawler captures everything the browser loaded, including images and\n * stylesheets. An OpenAPI document built from those would describe the site's\n * assets rather than its API, so only programmatic requests are considered.\n * Redirects are dropped because the hop is transport, not an operation.\n */\nexport function isExportableApiTransaction(transaction: CapturedTransaction): boolean {\n if (transaction.status !== 'completed') return false;\n if (!transaction.response) return false;\n if (transaction.isRedirect) return false;\n\n const method = String(transaction.request.method).toUpperCase();\n if (method === 'OPTIONS' || method === 'HEAD') return false;\n\n const status = transaction.response.status;\n if (status <= 0 || (status >= 300 && status < 400)) return false;\n\n try {\n const url = new URL(transaction.request.url);\n if (url.protocol !== 'http:' && url.protocol !== 'https:') return false;\n } catch {\n return false;\n }\n\n const mime = responseMimeType(transaction);\n if (NON_API_MIME_PREFIXES.some((prefix) => mime.startsWith(prefix))) return false;\n\n const resourceType = (transaction.resourceType ?? '').trim().toLowerCase();\n if (resourceType.length > 0) {\n if (API_RESOURCE_TYPES.has(resourceType)) return true;\n // A direct navigation to a JSON response is still an operation: API-first\n // hosts have no HTML shell to issue an XHR. HTML documents stay excluded.\n return DATA_DOCUMENT_RESOURCE_TYPES.has(resourceType) && mime.includes('json');\n }\n\n // Older capture records may omit the CDP resource type. Fall back to the\n // payload itself rather than silently dropping genuine API traffic.\n return mime.includes('json');\n}\n\n/**\n * Runs the deterministic discovery pipeline over an exploration's traffic and\n * serializes the result as OpenAPI 3.1.0 JSON and YAML.\n *\n * Returns null when nothing survived filtering: a crawl of a purely\n * server-rendered site has no API to document, and an empty specification\n * would be a misleading artifact.\n */\nexport function generateOpenApiSpec(\n input: GenerateOpenApiSpecInput,\n): ExplorationOpenApiSpec | null {\n const transactions = orderTransactions(\n dedupeTransactions(input.transactions.filter(isExportableApiTransaction)),\n );\n if (transactions.length === 0) return null;\n\n // One normalizer instance for both engines: the schema aggregate is keyed by\n // the same endpoint identity the aggregator produced, which is what lets the\n // generator join operations to request/response schemas.\n const normalizer = new EndpointNormalizer();\n const aggregator = new EndpointAggregator(normalizer);\n const schemas = new SchemaInferenceEngine({ normalizer });\n\n for (const transaction of transactions) {\n aggregator.ingest(transaction);\n schemas.ingestTransaction(transaction);\n }\n\n const endpoints = aggregator.getAll();\n const schemaAggregates = schemas.getAllAggregates();\n\n const discovery = new RelationshipDiscoveryEngine();\n discovery.registerEndpoints(endpoints);\n discovery.registerSchemas(schemaAggregates);\n const relationships = discovery.discoverRelationships();\n\n const generator = new OpenApiGenerator({\n openApiVersion: '3.1.0',\n info: {\n title: input.title,\n version: '1.0.0',\n description:\n `Discovered by Luxray from ${transactions.length} captured API transaction(s) ` +\n `during a crawl of ${input.startUrl}.`,\n },\n });\n\n const generationInput = { endpoints, schemas: schemaAggregates, relationships };\n const generatedAt = (input.now ?? Date.now)();\n\n // One document, two serializations. The generator stamps the document with\n // its own wall-clock time; that would make the same traffic produce\n // different bytes on every run, so the crawl's clock is written instead. The\n // timestamp is metadata, not API structure, and pinning it makes a spec\n // reproducible from the same traffic.\n const document = generator.generate(generationInput);\n document['x-luxray-generated-at'] = generatedAt;\n\n const json = toDocument('json', 'application/json', serializeToJson(document));\n const yaml = toDocument('yaml', 'application/yaml', serializeToYaml(document));\n\n return {\n version: 1,\n taskId: input.taskId,\n attempt: input.attempt,\n summary: {\n version: '3.1.0',\n endpointCount: endpoints.length,\n schemaCount: schemaAggregates.length,\n relationshipCount: relationships.length,\n sourceTransactions: transactions.length,\n generatedAt,\n jsonBytes: json.byteLength,\n yamlBytes: yaml.byteLength,\n omission: null,\n },\n json,\n yaml,\n };\n}\n\n/**\n * Applies the transport budget without truncating anything.\n *\n * A partial OpenAPI document is worse than none: it looks valid while hiding\n * operations. When both documents cannot fit, their content is omitted whole\n * and the summary records the size, so the operator can still pick the files\n * up from the agent's artifact directory.\n */\nexport function applyOpenApiTransportBudget(\n spec: ExplorationOpenApiSpec,\n limitBytes: number = OPENAPI_TRANSPORT_BUDGET_BYTES,\n): ExplorationOpenApiSpec {\n const byteLength = spec.summary.jsonBytes + spec.summary.yamlBytes;\n if (byteLength <= limitBytes) return spec;\n\n return {\n ...spec,\n json: null,\n yaml: null,\n summary: {\n ...spec.summary,\n omission: { reason: 'too-large', limitBytes, byteLength },\n },\n };\n}\n\n/**\n * Writes both serializations next to the crawl artifacts.\n *\n * These files are the operator's copy even when the documents are too large to\n * travel over the task stream.\n */\nexport async function writeOpenApiArtifacts(\n directory: string,\n spec: ExplorationOpenApiSpec,\n): Promise<{ readonly jsonPath: string; readonly yamlPath: string }> {\n if (!spec.json || !spec.yaml) {\n throw new Error('OpenAPI artifact content was omitted before it could be written.');\n }\n\n const jsonPath = join(directory, 'openapi.json');\n const yamlPath = join(directory, 'openapi.yaml');\n await writeFile(jsonPath, spec.json.content, 'utf8');\n await writeFile(yamlPath, spec.yaml.content, 'utf8');\n return { jsonPath, yamlPath };\n}\n\nfunction toDocument(\n format: ExplorationOpenApiDocument['format'],\n contentType: ExplorationOpenApiDocument['contentType'],\n content: string,\n): ExplorationOpenApiDocument {\n return {\n format,\n contentType,\n byteLength: Buffer.byteLength(content, 'utf8'),\n content,\n };\n}\n\nfunction responseMimeType(transaction: CapturedTransaction): string {\n const direct = transaction.response?.mimeType;\n if (direct) return direct.toLowerCase();\n\n const headers = transaction.response?.headers ?? {};\n for (const [name, value] of Object.entries(headers)) {\n if (name.toLowerCase() === 'content-type') return value.toLowerCase();\n }\n return '';\n}\n\nfunction dedupeTransactions(\n transactions: readonly CapturedTransaction[],\n): readonly CapturedTransaction[] {\n const seen = new Set<string>();\n const unique: CapturedTransaction[] = [];\n for (const transaction of transactions) {\n if (seen.has(transaction.id)) continue;\n seen.add(transaction.id);\n unique.push(transaction);\n }\n return unique;\n}\n\n/**\n * Visit order is whatever the capture engine produced; the pipeline needs a\n * stable order so two runs over the same traffic serialize identically.\n */\nfunction orderTransactions(\n transactions: readonly CapturedTransaction[],\n): readonly CapturedTransaction[] {\n return [...transactions].sort((left, right) => {\n const byTime = left.timing.startTime - right.timing.startTime;\n return byTime !== 0 ? byTime : left.id.localeCompare(right.id);\n });\n}\n","import type { ParsedUrl } from './types.js';\n\nconst DUMMY_BASE = 'http://localhost';\n\n/**\n * Safely decodes a URI component without throwing on malformed sequences.\n */\nexport function safeDecodeURIComponent(component: string): string {\n try {\n return decodeURIComponent(component);\n } catch {\n return component;\n }\n}\n\n/**\n * Robust, deterministic URL parser and sanitizer.\n * Complies with RFC 3986 URL semantics and normalizes whitespace, repeated slashes,\n * trailing slashes, and casing.\n */\nexport class UrlParser {\n /**\n * Parses an absolute or relative URL into a structured ParsedUrl entity.\n */\n public static parse(inputUrl: string): ParsedUrl {\n const raw = inputUrl.trim();\n let urlObj: URL;\n let isRelative = false;\n\n try {\n urlObj = new URL(raw);\n } catch {\n // Input might be a relative path like \"/api/users/123?page=1\"\n try {\n urlObj = new URL(raw.startsWith('/') ? raw : `/${raw}`, DUMMY_BASE);\n isRelative = true;\n } catch {\n // Fallback for severely malformed strings\n urlObj = new URL('/', DUMMY_BASE);\n isRelative = true;\n }\n }\n\n const protocol = isRelative ? '' : urlObj.protocol.toLowerCase();\n const hostname = isRelative ? '' : urlObj.hostname.toLowerCase();\n const port = isRelative ? '' : urlObj.port;\n\n // Build canonical origin\n let origin = '';\n if (!isRelative && hostname) {\n const hasDefaultPort =\n (protocol === 'http:' && (port === '80' || port === '')) ||\n (protocol === 'https:' && (port === '443' || port === ''));\n\n origin = hasDefaultPort || !port\n ? `${protocol}//${hostname}`\n : `${protocol}//${hostname}:${port}`;\n }\n\n // Process pathname: split into clean segments, collapsing empty ones\n const rawPath = urlObj.pathname;\n const splitSegments = rawPath.split('/');\n const cleanSegments: string[] = [];\n\n for (const segment of splitSegments) {\n if (segment.length > 0) {\n cleanSegments.push(safeDecodeURIComponent(segment));\n }\n }\n\n // Build canonical clean path (strip trailing slash unless root)\n const cleanPath = cleanSegments.length === 0 ? '/' : `/${cleanSegments.join('/')}`;\n\n // Extract query parameters\n const searchParams = new Map<string, string[]>();\n for (const [key, value] of urlObj.searchParams.entries()) {\n // Normalize array-bracket notation in key: \"filter[]\" -> \"filter\"\n const normalizedKey = key.endsWith('[]') ? key.slice(0, -2) : key;\n const existing = searchParams.get(normalizedKey);\n if (existing) {\n existing.push(value);\n } else {\n searchParams.set(normalizedKey, [value]);\n }\n }\n\n const fragment = urlObj.hash ? urlObj.hash.slice(1) : undefined;\n\n return {\n rawUrl: raw,\n protocol,\n hostname,\n port,\n origin,\n rawPath,\n cleanPath,\n segments: cleanSegments,\n searchParams,\n fragment,\n };\n }\n}\n\n","/**\n * Regular expressions and validation patterns for dynamic identifier detection.\n */\n\n// Pure integer ID (e.g. \"123\", \"4567890\")\nexport const NUMERIC_ID_REGEX = /^\\d+$/;\n\n// Standard UUID (v1-v5, case-insensitive)\nexport const UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\n\n// Relaxed UUID (any 8-4-4-4-12 hex string)\nexport const RELAXED_UUID_REGEX =\n /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;\n\n// ULID (26-character Crockford's Base32)\nexport const ULID_REGEX = /^[0-9A-HJ-KM-NP-Za-km-np-z]{26}$/;\n\n// MongoDB ObjectId (24 hex characters)\nexport const OBJECT_ID_REGEX = /^[0-9a-fA-F]{24}$/;\n\n// Generic long hex hash (16, 32, 40, or 64 hex characters, with at least one digit to avoid all-letter words)\nexport const HEX_HASH_REGEX = /^(?=.*\\d)[0-9a-fA-F]{16,64}$/;\n\n// Prefixed identifier (e.g. \"cus_12345\", \"ch_1A2b3C\", \"ORD-2026-001\", \"INV-2023-99\", \"USR_8899\")\nexport const PREFIXED_ID_REGEX = /^[a-zA-Z]{2,6}[-_][a-zA-Z0-9]+(-[0-9]+)*$/;\n\n// Slug pattern (words joined by hyphens)\nexport const SLUG_REGEX = /^[a-z0-9]+(-[a-z0-9]+)+$/i;\n\n// Hashid / Short alphanumeric mixed identifier (length 6 to 16, must contain both letters and numbers)\nexport const HASHID_REGEX = /^(?=.*[a-zA-Z])(?=.*\\d)[a-zA-Z0-9_-]{6,20}$/;\n\n// Version pattern: e.g. \"v1\", \"v2\", \"v1.0\", \"v2023-01-01\", \"v1beta1\"\nexport const VERSION_REGEX = /^v\\d+(\\.\\d+)?([a-zA-Z]+[0-9]*)?(-[a-zA-Z0-9]+)*$/i;\n","import { VERSION_REGEX } from './patterns.js';\n\n/**\n * Common REST actions, architectural words, and static keywords that should\n * NEVER be considered dynamic parameters even if they resemble slugs or identifiers.\n */\nexport const RESERVED_STATIC_WORDS = new Set<string>([\n // Infrastructure & routing\n 'api',\n 'rest',\n 'graphql',\n 'rpc',\n 'grpc',\n 'ws',\n 'wss',\n 'internal',\n 'admin',\n 'public',\n 'private',\n 'dev',\n 'staging',\n 'prod',\n 'v1',\n 'v2',\n 'v3',\n\n // Authentication & Session\n 'auth',\n 'oauth',\n 'oauth2',\n 'login',\n 'logout',\n 'signin',\n 'signup',\n 'signout',\n 'register',\n 'token',\n 'session',\n 'sessions',\n 'refresh',\n 'verify',\n 'verification',\n 'reset-password',\n 'forgot-password',\n 'change-password',\n 'mfa',\n '2fa',\n 'sso',\n\n // Actions & Operations\n 'new',\n 'create',\n 'edit',\n 'update',\n 'delete',\n 'destroy',\n 'remove',\n 'cancel',\n 'confirm',\n 'approve',\n 'reject',\n 'archive',\n 'archived',\n 'restore',\n 'submit',\n 'execute',\n 'run',\n 'start',\n 'stop',\n 'pause',\n 'resume',\n 'publish',\n 'unpublish',\n 'activate',\n 'deactivate',\n 'enable',\n 'disable',\n\n // Query & Data Manipulation\n 'search',\n 'query',\n 'filter',\n 'find',\n 'export',\n 'import',\n 'upload',\n 'download',\n 'sync',\n 'batch',\n 'bulk',\n 'aggregate',\n 'stats',\n 'analytics',\n 'summary',\n 'count',\n\n // Self & Metadata\n 'me',\n 'self',\n 'my',\n 'current',\n 'active',\n 'all',\n 'recent',\n 'popular',\n 'featured',\n 'trending',\n 'status',\n 'health',\n 'healthz',\n 'live',\n 'ready',\n 'ping',\n 'metrics',\n 'info',\n 'version',\n 'config',\n 'configuration',\n 'settings',\n 'profile',\n 'schema',\n 'openapi',\n 'swagger',\n 'docs',\n 'spec',\n\n // Notifications & Webhooks\n 'callback',\n 'callbacks',\n 'webhook',\n 'webhooks',\n 'notifications',\n 'alerts',\n 'events',\n 'logs',\n 'audit',\n]);\n\n/**\n * Checks whether a given path segment is a reserved static keyword or API version.\n */\nexport function isReservedStaticSegment(segment: string): boolean {\n const lower = segment.toLowerCase();\n if (RESERVED_STATIC_WORDS.has(lower)) {\n return true;\n }\n // Check version pattern: v1, v2, v2024-01-01, v1beta1, etc.\n if (VERSION_REGEX.test(segment)) {\n return true;\n }\n // Check file extensions: e.g. \"favicon.ico\", \"robots.txt\", \"data.json\"\n if (/\\.[a-zA-Z0-9]{1,5}$/.test(segment)) {\n return true;\n }\n return false;\n}\n\n","import {\n NUMERIC_ID_REGEX,\n UUID_REGEX,\n RELAXED_UUID_REGEX,\n ULID_REGEX,\n OBJECT_ID_REGEX,\n HEX_HASH_REGEX,\n PREFIXED_ID_REGEX,\n SLUG_REGEX,\n HASHID_REGEX,\n} from './patterns.js';\nimport { isReservedStaticSegment } from './static-words.js';\n\nexport type DynamicSegmentKind =\n | 'numeric'\n | 'uuid'\n | 'ulid'\n | 'objectid'\n | 'hex'\n | 'prefixed'\n | 'slug'\n | 'hashid';\n\nexport interface SegmentClassification {\n readonly isDynamic: boolean;\n readonly kind?: DynamicSegmentKind;\n readonly confidence: number; // 0.0 to 1.0\n}\n\n/**\n * Deterministically classifies an individual path segment as static or dynamic.\n * Follows conservative heuristics to prevent false-positive route merging.\n */\nexport class SegmentClassifier {\n public static classify(\n segment: string,\n previousSegment?: string\n ): SegmentClassification {\n const trimmed = segment.trim();\n\n // 1. Empty or whitespace-only is never dynamic\n if (trimmed.length === 0) {\n return { isDynamic: false, confidence: 1.0 };\n }\n\n // 2. Reserved static words and API version strings are strictly static\n if (isReservedStaticSegment(trimmed)) {\n return { isDynamic: false, confidence: 1.0 };\n }\n\n // 3. Numeric ID (e.g. \"123\", \"4567890\")\n if (NUMERIC_ID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'numeric', confidence: 1.0 };\n }\n\n // 4. Standard or Relaxed UUID\n if (UUID_REGEX.test(trimmed) || RELAXED_UUID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'uuid', confidence: 1.0 };\n }\n\n // 5. ULID (26-character Base32)\n if (ULID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'ulid', confidence: 0.95 };\n }\n\n // 6. MongoDB ObjectId (24 hex characters)\n if (OBJECT_ID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'objectid', confidence: 0.95 };\n }\n\n // 7. Generic Hex Hash (16-64 hex chars with digits)\n if (HEX_HASH_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'hex', confidence: 0.9 };\n }\n\n // 8. Prefixed ID (e.g. \"cus_12345\", \"ORD-2026-001\", \"INV-2023-99\", \"USR_8899\")\n // Explicitly targets:\n // a) Underscore-separated IDs (e.g. Stripe \"cus_12345\", \"ch_1A2b3C\")\n // b) Uppercase business prefixes with numeric suffixes (e.g. \"ORD-2026-001\", \"INV-2023-99\")\n if (\n /^[a-zA-Z]{2,6}_[a-zA-Z0-9]+$/.test(trimmed) ||\n /^[A-Z]{2,6}-\\d+(-\\d+)*$/.test(trimmed)\n ) {\n return { isDynamic: true, kind: 'prefixed', confidence: 0.95 };\n }\n\n // 9. Slug (e.g. \"how-to-build-apis\", \"my-first-post-2026\", \"tech-news\")\n // Hyphenated string with 3+ parts, OR 2+ parts when preceded by a resource collection\n if (SLUG_REGEX.test(trimmed)) {\n const parts = trimmed.split('-');\n if (parts.length >= 3) {\n return { isDynamic: true, kind: 'slug', confidence: 0.85 };\n }\n if (\n previousSegment &&\n /^(posts|articles|blogs|stories|topics|categories|items)$/i.test(previousSegment)\n ) {\n return { isDynamic: true, kind: 'slug', confidence: 0.85 };\n }\n }\n\n // Fallback prefixed ID for general kebab with digits (e.g. \"usr-12345\")\n if (PREFIXED_ID_REGEX.test(trimmed) && /\\d/.test(trimmed)) {\n return { isDynamic: true, kind: 'prefixed', confidence: 0.9 };\n }\n\n // 10. Alphanumeric mixed ID / Hashid (e.g. \"abc123\", \"usr88a99\")\n // Length between 6 and 20, must have both letters and numbers\n if (HASHID_REGEX.test(trimmed)) {\n return { isDynamic: true, kind: 'hashid', confidence: 0.8 };\n }\n\n // Default fallback: preserve segment as static\n return { isDynamic: false, confidence: 0.9 };\n }\n}\n","/**\n * Basic, robust English noun singularization for parameter naming.\n * Covers regular plurals, -ies, -es, and irregular common nouns.\n */\n\nconst IRREGULAR_PLURALS: Record<string, string> = {\n people: 'person',\n children: 'child',\n men: 'man',\n women: 'woman',\n data: 'data',\n media: 'medium',\n criteria: 'criterion',\n indices: 'index',\n};\n\nconst UNCOUNTABLE_OR_SINGULAR_S: Set<string> = new Set([\n 'status',\n 'news',\n 'series',\n 'species',\n 'analytics',\n 'metrics',\n 'address',\n 'process',\n 'access',\n 'business',\n 'class',\n 'pass',\n]);\n\n/**\n * Returns the singular form of an English noun.\n */\nexport function singularize(word: string): string {\n const lower = word.toLowerCase().trim();\n\n if (lower.length <= 2) {\n return word;\n }\n\n // Check irregulars\n const irregular = IRREGULAR_PLURALS[lower];\n if (irregular) {\n return irregular;\n }\n\n // Words that end in s but are already singular\n if (UNCOUNTABLE_OR_SINGULAR_S.has(lower)) {\n return word;\n }\n\n // -ies -> -y (e.g. categories -> category, companies -> company)\n if (lower.endsWith('ies') && lower.length > 4) {\n return word.slice(0, -3) + 'y';\n }\n\n // -ses, -shes, -ches, -xes, -zes -> strip -es (e.g. statuses -> status, boxes -> box, watches -> watch)\n if (/(sses|shes|ches|xes|zes|ses)$/i.test(lower)) {\n return word.slice(0, -2);\n }\n\n // standard -s plural (e.g. users -> user, products -> product)\n if (lower.endsWith('s') && !lower.endsWith('ss')) {\n return word.slice(0, -1);\n }\n\n return word;\n}\n","import { singularize } from './singularize.js';\nimport type { DynamicSegmentKind } from '../heuristics/segment-classifier.js';\n\nexport interface DynamicSegmentContext {\n readonly index: number;\n readonly value: string;\n readonly kind: DynamicSegmentKind;\n readonly previousSegment?: string;\n}\n\n/**\n * Deterministically infers parameter names from contextual path hierarchy.\n */\nexport class ParameterNamer {\n /**\n * Generates parameter names for all dynamic segments in a path.\n */\n public static nameParameters(\n segments: readonly string[],\n dynamicIndices: ReadonlyMap<number, DynamicSegmentKind>\n ): Map<number, string> {\n const result = new Map<number, string>();\n const totalDynamic = dynamicIndices.size;\n const usedNames = new Set<string>();\n\n for (const [index, kind] of dynamicIndices.entries()) {\n const prevSegment = index > 0 ? segments[index - 1] : undefined;\n let paramName: string;\n\n if (kind === 'slug') {\n paramName = totalDynamic === 1 ? 'slug' : prevSegment ? `${singularize(prevSegment)}Slug` : 'slug';\n } else if (totalDynamic === 1) {\n // Single dynamic parameter: use standard \":id\" fallback as in \"/api/users/:id\"\n paramName = 'id';\n } else {\n // Nested / multiple dynamic parameters: use context to disambiguate,\n // e.g. \"/products/:productId/reviews/:reviewId\"\n if (prevSegment && prevSegment.length > 1) {\n const singular = singularize(prevSegment);\n paramName = `${singular}Id`;\n } else {\n paramName = 'id';\n }\n }\n\n // Avoid collision if multiple parameters derive the same name\n let uniqueName = paramName;\n let counter = 2;\n while (usedNames.has(uniqueName)) {\n uniqueName = `${paramName}_${counter}`;\n counter++;\n }\n\n usedNames.add(uniqueName);\n result.set(index, `:${uniqueName}`);\n }\n\n return result;\n }\n}\n\n","import type { QueryParamInferredType, QueryParamMetadata } from '@luxray/shared';\n\n/**\n * Analyzes and classifies query parameters observed across HTTP requests.\n */\nexport class QueryAnalyzer {\n /**\n * Infers primitive scalar data type from a query parameter string value.\n */\n public static inferType(value: string): QueryParamInferredType {\n const trimmed = value.trim();\n\n if (trimmed === '' || trimmed.toLowerCase() === 'null') {\n return 'null';\n }\n\n if (trimmed === 'true' || trimmed === 'false') {\n return 'boolean';\n }\n\n // Number check: pure integer or float\n if (/^-?\\d+(\\.\\d+)?$/.test(trimmed)) {\n return 'number';\n }\n\n return 'string';\n }\n\n /**\n * Merges a newly observed parameter values array into an existing or new QueryParamMetadata record.\n */\n public static merge(\n paramName: string,\n existing: QueryParamMetadata | undefined,\n observedValues: readonly string[],\n totalEndpointObservations: number\n ): QueryParamMetadata {\n const isArrayObservation = observedValues.length > 1;\n const observedTypes = new Set<QueryParamInferredType>(existing?.types ?? []);\n\n for (const val of observedValues) {\n observedTypes.add(this.inferType(val));\n }\n\n if (isArrayObservation) {\n observedTypes.add('array');\n }\n\n const occurrences = (existing?.occurrences ?? 0) + 1;\n const required = occurrences === totalEndpointObservations;\n\n // Collect bounded set of unique sample values (max 5)\n const samples = new Set<string>(existing?.sampleValues ?? []);\n for (const val of observedValues) {\n if (samples.size < 5) {\n samples.add(val);\n }\n }\n\n return {\n name: paramName,\n types: Array.from(observedTypes),\n isArray: existing?.isArray || isArrayObservation,\n required,\n occurrences,\n sampleValues: Array.from(samples),\n };\n }\n}\n\n","import type { EndpointIdentity, NormalizedEndpoint } from '@luxray/shared';\nimport { UrlParser } from '../url/url-parser.js';\nimport { SegmentClassifier, type DynamicSegmentKind } from '../heuristics/segment-classifier.js';\nimport { ParameterNamer } from '../naming/parameter-namer.js';\n\nexport interface NormalizerOptions {\n /**\n * If true, always formats parameter names contextually (e.g. \":userId\")\n * instead of \":id\" when only one dynamic parameter is present.\n * Default: false\n */\n alwaysUseContextualNames?: boolean;\n}\n\n/**\n * Deterministic API Endpoint Normalizer.\n * Analyzes raw HTTP request URLs and converts them into standardized API endpoint identities.\n */\nexport class EndpointNormalizer {\n private readonly options: NormalizerOptions;\n\n constructor(options?: NormalizerOptions) {\n this.options = {\n alwaysUseContextualNames: options?.alwaysUseContextualNames ?? false,\n };\n }\n\n /**\n * Normalizes a raw URL and HTTP method into a NormalizedEndpoint entity.\n */\n public normalize(url: string, method = 'GET'): NormalizedEndpoint {\n const parsed = UrlParser.parse(url);\n const upperMethod = method.toUpperCase().trim();\n const segments = parsed.segments;\n\n const dynamicIndices = new Map<number, DynamicSegmentKind>();\n\n // Step 1: Classify each segment\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]!;\n const prevSegment = i > 0 ? segments[i - 1] : undefined;\n const classification = SegmentClassifier.classify(segment, prevSegment);\n\n if (classification.isDynamic && classification.kind) {\n dynamicIndices.set(i, classification.kind);\n }\n }\n\n // Step 2: Infer parameter names\n const parameterTokens = ParameterNamer.nameParameters(segments, dynamicIndices);\n\n // Step 3: Reconstruct normalized path and extract path parameters\n const pathParameters: Record<string, string> = {};\n const normalizedSegments: string[] = [];\n\n for (let i = 0; i < segments.length; i++) {\n const rawSegment = segments[i]!;\n const token = parameterTokens.get(i);\n\n if (token) {\n normalizedSegments.push(token);\n const paramKey = token.slice(1); // remove leading colon\n pathParameters[paramKey] = rawSegment;\n } else {\n normalizedSegments.push(rawSegment);\n }\n }\n\n const normalizedPath =\n normalizedSegments.length === 0 ? '/' : `/${normalizedSegments.join('/')}`;\n\n // Step 4: Construct canonical endpoint identity\n const originPart = parsed.origin ? parsed.origin : '';\n const identityId = `${upperMethod} ${originPart}${normalizedPath}`;\n\n const identity: EndpointIdentity = {\n id: identityId,\n method: upperMethod,\n origin: parsed.origin,\n pathname: normalizedPath,\n };\n\n // Step 5: Convert searchParams Map to plain object\n const queryParameters: Record<string, string[]> = {};\n for (const [key, values] of parsed.searchParams.entries()) {\n queryParameters[key] = [...values];\n }\n\n return {\n identity,\n rawUrl: parsed.rawUrl,\n rawPath: parsed.rawPath,\n normalizedPath,\n pathParameters,\n queryParameters,\n };\n }\n}\n\n","import type {\n CapturedTransaction,\n EndpointAggregate,\n QueryParamMetadata,\n} from '@luxray/shared';\nimport { EndpointNormalizer } from './endpoint-normalizer.js';\nimport { QueryAnalyzer } from '../query/query-analyzer.js';\n\ninterface MutableAggregate {\n aggregate: EndpointAggregate;\n transactions: CapturedTransaction[];\n latencies: number[];\n}\n\n/**\n * Aggregates raw CapturedTransactions into structured API endpoint intelligence.\n * Tracks observation counts, latency profiles, status distributions, and query schemas.\n */\nexport class EndpointAggregator {\n private readonly normalizer: EndpointNormalizer;\n private readonly aggregates = new Map<string, MutableAggregate>();\n\n constructor(normalizer?: EndpointNormalizer) {\n this.normalizer = normalizer ?? new EndpointNormalizer();\n }\n\n /**\n * Ingests a single captured transaction, updating or creating an EndpointAggregate.\n */\n public ingest(transaction: CapturedTransaction): EndpointAggregate {\n const method = String(transaction.request.method);\n const normalized = this.normalizer.normalize(transaction.request.url, method);\n const endpointId = normalized.identity.id;\n const timestamp = transaction.request.timestamp || Date.now();\n\n const existing = this.aggregates.get(endpointId);\n\n if (!existing) {\n // First observation\n const isSuccess =\n transaction.status === 'completed' &&\n (!transaction.response ||\n (transaction.response.status >= 200 && transaction.response.status < 400));\n\n const statusCodes: Record<number, number> = {};\n if (transaction.response?.status) {\n statusCodes[transaction.response.status] = 1;\n }\n\n // Initialize query params\n const queryParams: Record<string, QueryParamMetadata> = {};\n for (const [key, values] of Object.entries(normalized.queryParameters)) {\n queryParams[key] = QueryAnalyzer.merge(key, undefined, values, 1);\n }\n\n const durationMs = transaction.timing.durationMs;\n const latencies = durationMs !== undefined ? [durationMs] : [];\n\n const newAggregate: EndpointAggregate = {\n identity: normalized.identity,\n observationCount: 1,\n firstObservedAt: timestamp,\n lastObservedAt: timestamp,\n statusCodes,\n successCount: isSuccess ? 1 : 0,\n failureCount: isSuccess ? 0 : 1,\n latency:\n durationMs !== undefined\n ? { minMs: durationMs, maxMs: durationMs, avgMs: durationMs }\n : undefined,\n queryParams,\n sampleUrls: [transaction.request.url],\n transactionIds: [transaction.id],\n };\n\n this.aggregates.set(endpointId, {\n aggregate: newAggregate,\n transactions: [transaction],\n latencies,\n });\n\n return newAggregate;\n }\n\n // Subsequent observations: mutate state\n const current = existing.aggregate;\n const observationCount = current.observationCount + 1;\n const firstObservedAt = Math.min(current.firstObservedAt, timestamp);\n const lastObservedAt = Math.max(current.lastObservedAt, timestamp);\n\n // Update status code counts\n const statusCodes = { ...current.statusCodes };\n if (transaction.response?.status) {\n const code = transaction.response.status;\n statusCodes[code] = (statusCodes[code] ?? 0) + 1;\n }\n\n const isSuccess =\n transaction.status === 'completed' &&\n (!transaction.response ||\n (transaction.response.status >= 200 && transaction.response.status < 400));\n\n const successCount = current.successCount + (isSuccess ? 1 : 0);\n const failureCount = current.failureCount + (isSuccess ? 0 : 1);\n\n // Update latency metrics\n if (transaction.timing.durationMs !== undefined) {\n existing.latencies.push(transaction.timing.durationMs);\n }\n\n let latency = current.latency;\n if (existing.latencies.length > 0) {\n const sorted = [...existing.latencies].sort((a, b) => a - b);\n const minMs = sorted[0]!;\n const maxMs = sorted[sorted.length - 1]!;\n const sum = sorted.reduce((acc, val) => acc + val, 0);\n const avgMs = Math.round((sum / sorted.length) * 10) / 10;\n latency = { minMs, maxMs, avgMs };\n }\n\n // Update query parameters\n const updatedQueryParams: Record<string, QueryParamMetadata> = { ...current.queryParams };\n for (const [key, values] of Object.entries(normalized.queryParameters)) {\n updatedQueryParams[key] = QueryAnalyzer.merge(\n key,\n updatedQueryParams[key],\n values,\n observationCount\n );\n }\n\n // Recalculate required flag for all query params against total observations\n for (const [key, meta] of Object.entries(updatedQueryParams)) {\n if (meta.occurrences !== observationCount) {\n updatedQueryParams[key] = { ...meta, required: false };\n }\n }\n\n // Retain bounded sample URLs (max 5)\n const sampleUrls = current.sampleUrls.includes(transaction.request.url)\n ? current.sampleUrls\n : current.sampleUrls.length < 5\n ? [...current.sampleUrls, transaction.request.url]\n : current.sampleUrls;\n\n // Retain transaction IDs\n const transactionIds = [...current.transactionIds, transaction.id];\n existing.transactions.push(transaction);\n\n const updatedAggregate: EndpointAggregate = {\n identity: current.identity,\n observationCount,\n firstObservedAt,\n lastObservedAt,\n statusCodes,\n successCount,\n failureCount,\n latency,\n queryParams: updatedQueryParams,\n sampleUrls,\n transactionIds,\n };\n\n existing.aggregate = updatedAggregate;\n return updatedAggregate;\n }\n\n /**\n * Ingests an array of transactions in sequential order.\n */\n public ingestBatch(transactions: readonly CapturedTransaction[]): readonly EndpointAggregate[] {\n for (const tx of transactions) {\n this.ingest(tx);\n }\n return this.getAll();\n }\n\n /**\n * Retrieves an aggregate by its unique endpoint identity string.\n */\n public get(endpointId: string): EndpointAggregate | undefined {\n return this.aggregates.get(endpointId)?.aggregate;\n }\n\n /**\n * Returns all aggregated endpoints.\n */\n public getAll(): readonly EndpointAggregate[] {\n return Array.from(this.aggregates.values()).map((m) => m.aggregate);\n }\n\n /**\n * Returns all original captured transactions associated with an endpoint.\n */\n public getTransactions(endpointId: string): readonly CapturedTransaction[] {\n return this.aggregates.get(endpointId)?.transactions ?? [];\n }\n\n /**\n * Filters aggregated endpoints by predicate.\n */\n public filter(predicate: (agg: EndpointAggregate) => boolean): EndpointAggregate[] {\n return this.getAll().filter(predicate);\n }\n\n /**\n * Finds endpoints whose normalized path contains the specified substring.\n */\n public findByPath(pathnameSubstring: string): EndpointAggregate[] {\n return this.filter((agg) => agg.identity.pathname.includes(pathnameSubstring));\n }\n\n public size(): number {\n return this.aggregates.size;\n }\n\n public clear(): void {\n this.aggregates.clear();\n }\n}\n\n","import { singularize } from '@luxray/normalization';\nimport type { ResourceCandidate } from '../domain/types.js';\n\nexport { singularize };\n\nexport const DEFAULT_STRIP_PREFIXES: readonly string[] = [\n '/api',\n '/v1',\n '/v2',\n '/v3',\n '/v4',\n '/v5',\n '/rest',\n '/public',\n '/internal',\n];\n\nexport const DEFAULT_ACTION_VERBS: ReadonlySet<string> = new Set([\n 'activate',\n 'deactivate',\n 'enable',\n 'disable',\n 'verify',\n 'checkout',\n 'search',\n 'export',\n 'import',\n 'login',\n 'logout',\n 'sync',\n 'reset',\n 'cancel',\n 'archive',\n 'unarchive',\n 'publish',\n 'unpublish',\n 'clone',\n 'fork',\n 'submit',\n 'validate',\n 'confirm',\n 'reorder',\n 'download',\n 'upload',\n 'lock',\n 'unlock',\n 'process',\n 'approve',\n 'reject',\n 'history',\n 'stats',\n 'summary',\n 'overview',\n 'preview',\n 'details',\n 'feed',\n 'recent',\n]);\n\n/**\n * Common REST pseudo-parameters representing the caller's identity (e.g. /users/me).\n */\nexport const IDENTITY_ALIAS_SEGMENTS: ReadonlySet<string> = new Set([\n 'me',\n 'self',\n 'current',\n 'mine',\n]);\n\n/**\n * Result of decomposing a path into its resource hierarchy and optional terminal action.\n */\nexport interface PathResourceHierarchy {\n /** The clean path with prefixes stripped */\n readonly normalizedPath: string;\n /** Primary resource candidate (e.g. 'user' for /users/:userId) */\n readonly primaryResource?: ResourceCandidate;\n /** Secondary/nested resource candidate (e.g. 'order' for /users/:userId/orders) */\n readonly nestedResource?: ResourceCandidate;\n /** All resource candidates found along the path in hierarchical order */\n readonly resources: readonly ResourceCandidate[];\n /** Action verb if terminal segment is an operational action rather than a resource */\n readonly action?: string;\n /** Parameter segments mapped to their preceding resource, e.g. { user: 'userId', order: 'orderId' } */\n readonly resourceParams: ReadonlyMap<string, string>;\n}\n\n/**\n * Strips configured API prefixes from the beginning of a URL path.\n */\nexport function stripApiPrefixes(\n pathname: string,\n prefixes: readonly string[] = DEFAULT_STRIP_PREFIXES,\n): string {\n let cleaned = pathname.trim();\n if (!cleaned.startsWith('/')) {\n cleaned = `/${cleaned}`;\n }\n\n let matched = true;\n while (matched) {\n matched = false;\n for (const prefix of prefixes) {\n const normalizedPrefix = prefix.startsWith('/') ? prefix : `/${prefix}`;\n if (cleaned.toLowerCase().startsWith(normalizedPrefix.toLowerCase())) {\n const nextChar = cleaned[normalizedPrefix.length];\n if (nextChar === '/' || nextChar === undefined) {\n cleaned = cleaned.slice(normalizedPrefix.length);\n if (!cleaned.startsWith('/')) {\n cleaned = `/${cleaned}`;\n }\n matched = true;\n break;\n }\n }\n }\n }\n\n return cleaned === '' ? '/' : cleaned;\n}\n\n/**\n * Checks whether a path segment represents a parameter (e.g. `:userId`, `{id}`).\n */\nexport function isParameterSegment(segment: string): boolean {\n if (!segment) return false;\n return (\n segment.startsWith(':') ||\n (segment.startsWith('{') && segment.endsWith('}')) ||\n (segment.startsWith('[') && segment.endsWith(']'))\n );\n}\n\n/**\n * Extracts the clean parameter name without parameter syntax delimiters.\n */\nexport function extractParamName(segment: string): string {\n if (segment.startsWith(':')) {\n return segment.slice(1);\n }\n if (\n (segment.startsWith('{') && segment.endsWith('}')) ||\n (segment.startsWith('[') && segment.endsWith(']'))\n ) {\n return segment.slice(1, -1);\n }\n return segment;\n}\n\n/**\n * Checks whether a segment represents an action verb.\n */\nexport function isActionVerb(\n segment: string,\n customVerbs?: ReadonlySet<string>,\n): boolean {\n const lower = segment.toLowerCase().trim();\n const verbs = customVerbs ?? DEFAULT_ACTION_VERBS;\n return verbs.has(lower);\n}\n\n/**\n * Decomposes an endpoint path template into resource candidates, nesting hierarchy, and actions.\n */\nexport function extractPathHierarchy(\n pathTemplate: string,\n options?: {\n stripPrefixes?: readonly string[];\n actionVerbs?: ReadonlySet<string>;\n },\n): PathResourceHierarchy {\n const strippedPath = stripApiPrefixes(pathTemplate, options?.stripPrefixes);\n const segments = strippedPath\n .split('/')\n .map((s) => s.trim())\n .filter((s) => s.length > 0);\n\n const resources: ResourceCandidate[] = [];\n const resourceParams = new Map<string, string>();\n let action: string | undefined;\n\n let currentSubpath = '';\n let parentResourceName: string | undefined;\n\n for (let i = 0; i < segments.length; i++) {\n const segment = segments[i]!;\n currentSubpath += `/${segment}`;\n\n if (isParameterSegment(segment)) {\n const paramName = extractParamName(segment);\n if (resources.length > 0) {\n const lastResource = resources[resources.length - 1]!;\n resourceParams.set(lastResource.name, paramName);\n }\n continue;\n }\n\n // Check if segment is an identity alias following a resource (e.g. /users/me, /accounts/current)\n if (resources.length > 0 && IDENTITY_ALIAS_SEGMENTS.has(segment.toLowerCase())) {\n const lastResource = resources[resources.length - 1]!;\n resourceParams.set(lastResource.name, segment.toLowerCase());\n continue;\n }\n\n const isTerminal = i === segments.length - 1;\n // Check if terminal segment is an action verb or preceded by a param and not plural\n if (isTerminal && isActionVerb(segment, options?.actionVerbs)) {\n action = segment;\n break;\n }\n\n // Singularize segment to derive canonical resource name\n const singular = singularize(segment).toLowerCase();\n const isPlural = singular !== segment.toLowerCase();\n const isNested = resources.length > 0;\n\n // If terminal segment is not plural, but follows a parameter, check if it's an action\n if (isTerminal && !isPlural && i > 0 && isParameterSegment(segments[i - 1]!)) {\n // If it looks like a verb or known action\n if (isActionVerb(segment, options?.actionVerbs) || segment.endsWith('e') || segment.endsWith('ing')) {\n action = segment;\n break;\n }\n }\n\n const candidate: ResourceCandidate = {\n name: singular,\n pluralName: isPlural ? segment.toLowerCase() : `${singular}s`,\n rawSegment: segment,\n path: currentSubpath,\n isNested,\n parentResource: parentResourceName,\n };\n\n resources.push(candidate);\n parentResourceName = singular;\n }\n\n const primaryResource = resources[0];\n const nestedResource = resources.length > 1 ? resources[1] : undefined;\n\n return {\n normalizedPath: strippedPath,\n primaryResource,\n nestedResource,\n resources,\n action,\n resourceParams,\n };\n}\n","import type {\n EndpointClassification,\n EndpointClassificationType,\n HttpMethod,\n} from '../domain/types.js';\nimport {\n extractPathHierarchy,\n isParameterSegment,\n IDENTITY_ALIAS_SEGMENTS,\n type PathResourceHierarchy,\n} from './resource-identifier.js';\n\nexport interface EndpointClassificationInput {\n readonly id: string;\n readonly method: HttpMethod | string;\n readonly pathTemplate: string;\n}\n\nexport const SYSTEM_UTILITY_SEGMENTS: ReadonlySet<string> = new Set([\n 'health',\n 'healthz',\n 'ping',\n 'live',\n 'livez',\n 'ready',\n 'readyz',\n 'metrics',\n 'version',\n 'info',\n 'docs',\n 'openapi',\n 'swagger',\n]);\n\n/**\n * Classifies an endpoint based on its HTTP method and path hierarchy.\n */\nexport function classifyEndpoint(\n endpoint: EndpointClassificationInput,\n options?: {\n stripPrefixes?: readonly string[];\n actionVerbs?: ReadonlySet<string>;\n },\n): EndpointClassification {\n const method = (endpoint.method?.toUpperCase() ?? 'GET') as HttpMethod;\n\n const hierarchy: PathResourceHierarchy = extractPathHierarchy(\n endpoint.pathTemplate,\n options,\n );\n\n const rawSegments = hierarchy.normalizedPath\n .split('/')\n .filter((s) => s.length > 0);\n\n // If path is a recognized non-resource system check (e.g. /health, /ping)\n if (\n rawSegments.length === 1 &&\n SYSTEM_UTILITY_SEGMENTS.has(rawSegments[0]!.toLowerCase())\n ) {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'UNKNOWN',\n confidence: 0.9,\n };\n }\n\n const lastSegment = rawSegments.length > 0 ? rawSegments[rawSegments.length - 1]! : '';\n const isTerminalParam =\n isParameterSegment(lastSegment) ||\n IDENTITY_ALIAS_SEGMENTS.has(lastSegment.toLowerCase());\n\n // If hierarchy identified an explicit action\n if (hierarchy.action) {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'ACTION',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n actionName: hierarchy.action,\n confidence: 0.95,\n };\n }\n\n // Nested resource patterns (hierarchy has >= 2 resources)\n if (hierarchy.resources.length >= 2) {\n if (isTerminalParam) {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'NESTED_RESOURCE_READ',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.9,\n };\n }\n if (method === 'PUT' || method === 'PATCH') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_UPDATE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n if (method === 'DELETE') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_DELETE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n } else {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'NESTED_COLLECTION_READ',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.9,\n };\n }\n if (method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_CREATE',\n primaryResource: hierarchy.primaryResource,\n nestedResource: hierarchy.nestedResource,\n confidence: 0.85,\n };\n }\n }\n }\n\n // Single resource patterns\n if (hierarchy.primaryResource) {\n if (isTerminalParam) {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_READ',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'PUT' || method === 'PATCH') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_UPDATE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'DELETE') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_DELETE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n } else {\n if (method === 'GET') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'COLLECTION_READ',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n if (method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'RESOURCE_CREATE',\n primaryResource: hierarchy.primaryResource,\n confidence: 0.95,\n };\n }\n }\n }\n\n // Fallbacks: non-GET terminal or root actions\n if (rawSegments.length > 0 && !isTerminalParam && method === 'POST') {\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'ACTION',\n actionName: lastSegment,\n confidence: 0.7,\n };\n }\n\n return {\n endpointId: endpoint.id,\n method,\n pathTemplate: endpoint.pathTemplate,\n type: 'UNKNOWN',\n confidence: 0.5,\n };\n}\n","import { createHmac } from 'node:crypto';\nimport type {\n EndpointAggregate,\n EndpointSchemaAggregate,\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n} from '@luxray/shared';\nimport type {\n DiscoveryEngineOptions,\n IdentifierCandidate,\n IdentifierLocation,\n} from '../domain/types.js';\nimport {\n extractParamName,\n extractPathHierarchy,\n isParameterSegment,\n} from '../resources/resource-identifier.js';\n\nexport const SENSITIVE_IDENTIFIER_SUBSTRINGS: readonly string[] = [\n 'password',\n 'passwd',\n 'secret',\n 'token',\n 'apikey',\n 'api_key',\n 'privatekey',\n 'private_key',\n 'authkey',\n 'auth_key',\n 'authcode',\n 'auth_code',\n 'authtoken',\n 'auth_token',\n 'sessionkey',\n 'bearer',\n 'authorization',\n 'cookie',\n 'cvv',\n 'cvc',\n 'ssn',\n 'pin',\n 'otp',\n 'passcode',\n 'signature',\n];\n\n/**\n * Computes an HMAC-SHA-256 cryptographic fingerprint for an identifier sample value.\n * Requires an explicit secret key (e.g. per-workspace or per-tenant).\n * Never uses a hardcoded fallback.\n */\nexport function computeHmacFingerprint(\n val: string | number,\n secretKey: string,\n): string {\n if (!secretKey || secretKey.trim().length === 0) {\n throw new Error(\n 'computeHmacFingerprint requires an explicit, non-empty secretKey.',\n );\n }\n return createHmac('sha256', secretKey.trim())\n .update(String(val))\n .digest('hex')\n .slice(0, 32);\n}\n\n/**\n * Backward-compatible wrapper for keyed fingerprinting.\n */\nexport function computeSaltedFingerprint(\n val: string | number,\n secretKey?: string,\n): string {\n if (!secretKey) {\n throw new Error(\n 'Fingerprinting requires an explicit secret key. No hardcoded default fallback is permitted.',\n );\n }\n return computeHmacFingerprint(val, secretKey);\n}\n\nexport interface EndpointInput {\n readonly id: string;\n readonly method: string;\n readonly pathTemplate: string;\n readonly queryParams?: EndpointAggregate['queryParams'];\n readonly sampleUrls?: readonly string[];\n}\n\n/**\n * Normalizes property name to a lowercase alphanumeric string for fuzzy comparison.\n * e.g. \"userId\", \"user_id\", \"user-id\", \"UserID\" -> \"userid\"\n */\nexport function canonicalizeIdentifierName(name: string): string {\n return name.toLowerCase().replace(/[^a-z0-9]/g, '');\n}\n\n/**\n * Checks whether a property or parameter name looks like an entity identifier.\n * Automatically rejects sensitive credentials and secret keywords.\n */\nexport function isIdentifierName(name: string): boolean {\n const lower = name.toLowerCase().replace(/[-_]/g, '');\n\n // Reject credentials, passwords, tokens, API keys, and OTPs\n for (const sensitive of SENSITIVE_IDENTIFIER_SUBSTRINGS) {\n if (lower.includes(sensitive.replace(/[-_]/g, ''))) {\n return false;\n }\n }\n\n if (lower === 'id' || lower === 'uuid' || lower === 'pk' || lower === 'slug') {\n return true;\n }\n return (\n lower.endsWith('id') ||\n lower.endsWith('uuid') ||\n lower.endsWith('slug') ||\n (lower.endsWith('key') && !lower.includes('secret') && !lower.includes('auth')) ||\n (lower.endsWith('code') && !lower.includes('pin') && !lower.includes('otp'))\n );\n}\n\n/**\n * Attempts to parse sample parameter values from sample URLs given a path template.\n */\nexport function extractPathSamplesFromUrls(\n pathTemplate: string,\n sampleUrls?: readonly string[],\n): Map<string, string[]> {\n const paramSamples = new Map<string, string[]>();\n if (!sampleUrls || sampleUrls.length === 0) {\n return paramSamples;\n }\n\n const templateSegments = pathTemplate\n .split('/')\n .filter((s) => s.length > 0);\n\n for (const urlStr of sampleUrls) {\n try {\n const parsed = new URL(urlStr, 'https://example.local');\n const actualSegments = parsed.pathname\n .split('/')\n .filter((s) => s.length > 0);\n\n // Find offset if path template has prefixes or vice versa\n if (actualSegments.length >= templateSegments.length) {\n const offset = actualSegments.length - templateSegments.length;\n for (let i = 0; i < templateSegments.length; i++) {\n const tSeg = templateSegments[i]!;\n if (isParameterSegment(tSeg)) {\n const paramName = extractParamName(tSeg);\n const actualVal = actualSegments[offset + i];\n if (actualVal) {\n const existing = paramSamples.get(paramName) ?? [];\n if (!existing.includes(actualVal)) {\n existing.push(actualVal);\n paramSamples.set(paramName, existing);\n }\n }\n }\n }\n }\n } catch {\n // Ignore URL parsing errors\n }\n }\n\n return paramSamples;\n}\n\n/**\n * Normalizes endpoint input from either an EndpointAggregate or custom EndpointInput.\n */\nexport function normalizeEndpointInput(\n endpoint: EndpointAggregate | EndpointInput,\n): EndpointInput {\n if ('identity' in endpoint) {\n return {\n id: endpoint.identity.id,\n method: endpoint.identity.method,\n pathTemplate: endpoint.identity.pathname,\n queryParams: endpoint.queryParams,\n sampleUrls: endpoint.sampleUrls,\n };\n }\n return endpoint;\n}\n\n/**\n * Safely extracts primitive scalar sample values from schema or field metadata.\n */\nexport function sanitizeSampleValues(\n rawSamples?: readonly unknown[],\n maxCount = 50,\n): readonly (string | number)[] {\n if (!rawSamples || !Array.isArray(rawSamples)) {\n return [];\n }\n const clean: (string | number)[] = [];\n const seen = new Set<string>();\n\n for (const val of rawSamples) {\n if (val === null || val === undefined) continue;\n if (typeof val === 'string' || typeof val === 'number') {\n const key = `${typeof val}:${val}`;\n if (!seen.has(key)) {\n seen.add(key);\n clean.push(val);\n if (clean.length >= maxCount) break;\n }\n }\n }\n\n return clean;\n}\n\n/**\n * Extracts candidate identifiers from an endpoint's path and query parameters.\n */\nexport function extractEndpointParamIdentifiers(\n endpoint: EndpointInput,\n options?: DiscoveryEngineOptions,\n): IdentifierCandidate[] {\n const candidates: IdentifierCandidate[] = [];\n const hierarchy = extractPathHierarchy(endpoint.pathTemplate, {\n stripPrefixes: options?.stripPrefixes,\n });\n\n const pathSamples = extractPathSamplesFromUrls(\n endpoint.pathTemplate,\n endpoint.sampleUrls,\n );\n\n const secretKey = options?.fingerprintSecret?.trim();\n\n // Extract from path parameters\n for (const [resource, paramName] of hierarchy.resourceParams.entries()) {\n const canonical = canonicalizeIdentifierName(paramName);\n const samples = (pathSamples.get(paramName) ?? []).slice(\n 0,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? samples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `path.${paramName}`,\n location: 'path_param',\n type: 'string', // Path segments default to string unless known\n sampleFingerprints: fingerprints,\n sampleValues: samples,\n endpointId: endpoint.id,\n isPrimaryKeyCandidate: true,\n });\n }\n\n // Also check raw segments for any other path params not tied to a recognized resource\n const rawSegments = endpoint.pathTemplate.split('/').filter((s) => s.length > 0);\n for (const seg of rawSegments) {\n if (isParameterSegment(seg)) {\n const paramName = extractParamName(seg);\n if (!candidates.some((c) => c.name === paramName)) {\n const canonical = canonicalizeIdentifierName(paramName);\n const samples = (pathSamples.get(paramName) ?? []).slice(\n 0,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? samples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `path.${paramName}`,\n location: 'path_param',\n type: 'string',\n sampleFingerprints: fingerprints,\n sampleValues: samples,\n endpointId: endpoint.id,\n isPrimaryKeyCandidate: true,\n });\n }\n }\n }\n\n // Extract from query parameters\n if (endpoint.queryParams) {\n for (const [paramName, meta] of Object.entries(endpoint.queryParams)) {\n if (isIdentifierName(paramName)) {\n const canonical = canonicalizeIdentifierName(paramName);\n const inferredType = meta.types.includes('number')\n ? 'number'\n : meta.types.includes('string')\n ? 'string'\n : 'unknown';\n const cleanSamples = sanitizeSampleValues(\n meta.sampleValues,\n options?.maxSampleValues ?? 50,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? cleanSamples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n candidates.push({\n name: paramName,\n canonicalName: canonical,\n propertyPath: `query.${paramName}`,\n location: 'query_param',\n type: inferredType,\n sampleFingerprints: fingerprints,\n sampleValues: cleanSamples,\n endpointId: endpoint.id,\n isForeignKeyCandidate: true,\n });\n }\n }\n }\n\n return candidates;\n}\n\n/**\n * Recursively traverses an inferred schema to find identifier properties.\n */\nfunction traverseSchemaForIdentifiers(\n schema: InferredSchema,\n currentPath: string,\n location: IdentifierLocation,\n endpointId: string,\n results: IdentifierCandidate[],\n currentDepth: number,\n maxDepth: number,\n maxSampleValues: number,\n secretKey?: string,\n): void {\n if (!schema || !schema.type || currentDepth > maxDepth) return;\n\n if (schema.type === 'object') {\n const obj = schema as InferredObjectSchema;\n if (!obj.fields) return;\n for (const [fieldName, fieldMeta] of Object.entries(obj.fields)) {\n if (!fieldMeta) continue;\n const fieldPath = currentPath ? `${currentPath}.${fieldName}` : fieldName;\n const childSchema = fieldMeta.schema;\n\n if (isIdentifierName(fieldName)) {\n let type:\n | 'string'\n | 'number'\n | 'integer'\n | 'boolean'\n | 'object'\n | 'array'\n | 'unknown' = 'unknown';\n let format: string | undefined;\n\n if (childSchema) {\n if (childSchema.type === 'string') {\n type = 'string';\n } else if (childSchema.type === 'integer') {\n type = 'integer';\n } else if (childSchema.type === 'number') {\n type = 'number';\n } else if (childSchema.type === 'boolean') {\n type = 'boolean';\n } else if (childSchema.type === 'object') {\n type = 'object';\n } else if (childSchema.type === 'array') {\n type = 'array';\n }\n }\n\n const isPk =\n fieldName.toLowerCase() === 'id' ||\n fieldName.toLowerCase() === '_id' ||\n fieldName.toLowerCase() === 'uuid';\n const isFk = !isPk && isIdentifierName(fieldName);\n\n const cleanSamples = sanitizeSampleValues(\n fieldMeta.sampleValues,\n maxSampleValues,\n );\n const fingerprints =\n secretKey && secretKey.length > 0\n ? cleanSamples.map((s) => computeHmacFingerprint(s, secretKey))\n : undefined;\n\n results.push({\n name: fieldName,\n canonicalName: canonicalizeIdentifierName(fieldName),\n propertyPath: `${location}.${fieldPath}`,\n location,\n type,\n format,\n sampleFingerprints: fingerprints,\n sampleValues: cleanSamples,\n endpointId,\n isPrimaryKeyCandidate: isPk,\n isForeignKeyCandidate: isFk,\n });\n }\n\n // Recurse into nested object or array\n if (childSchema && (childSchema.type === 'object' || childSchema.type === 'array')) {\n traverseSchemaForIdentifiers(\n childSchema,\n fieldPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n }\n } else if (schema.type === 'array') {\n const arr = schema as InferredArraySchema & { items?: InferredSchema };\n const child = arr.itemSchema ?? arr.items;\n if (child) {\n const itemPath = `${currentPath}[]`;\n traverseSchemaForIdentifiers(\n child,\n itemPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n } else if (schema.type === 'union') {\n for (const variant of schema.variants) {\n if (variant.type === 'object' || variant.type === 'array') {\n traverseSchemaForIdentifiers(\n variant,\n currentPath,\n location,\n endpointId,\n results,\n currentDepth + 1,\n maxDepth,\n maxSampleValues,\n secretKey,\n );\n }\n }\n }\n}\n\n/**\n * Extracts candidate identifiers from an endpoint schema aggregate.\n */\nexport function extractSchemaIdentifiers(\n endpointId: string,\n schemaAggregate: EndpointSchemaAggregate,\n options?: DiscoveryEngineOptions,\n): IdentifierCandidate[] {\n const candidates: IdentifierCandidate[] = [];\n const maxDepth = options?.maxSchemaDepth ?? 5;\n const maxSamples = options?.maxSampleValues ?? 50;\n const secretKey = options?.fingerprintSecret?.trim();\n\n // Inspect request schema\n if (schemaAggregate.request?.schema) {\n traverseSchemaForIdentifiers(\n schemaAggregate.request.schema,\n 'body',\n 'request_body',\n endpointId,\n candidates,\n 1,\n maxDepth,\n maxSamples,\n secretKey,\n );\n }\n\n // Inspect 2xx responses (prioritizing 200 and 201)\n const statusCodes = schemaAggregate.responses\n ? Object.keys(schemaAggregate.responses)\n .map(Number)\n .filter((code) => code >= 200 && code < 300)\n .sort((a, b) => a - b)\n : [];\n\n for (const status of statusCodes) {\n const mediaMap = schemaAggregate.responses[status];\n if (!mediaMap) continue;\n\n for (const resDef of Object.values(mediaMap)) {\n if (resDef.schema) {\n traverseSchemaForIdentifiers(\n resDef.schema,\n 'body',\n 'response_body',\n endpointId,\n candidates,\n 1,\n maxDepth,\n maxSamples,\n secretKey,\n );\n }\n }\n }\n\n return candidates;\n}\n","import type { EvidenceRecord } from '../domain/types.js';\nimport type { IdentifierCandidate } from '../domain/types.js';\n\nexport interface IdentifierMatchResult {\n readonly isMatch: boolean;\n readonly score: number;\n readonly evidence: readonly EvidenceRecord[];\n readonly sourceCandidate: IdentifierCandidate;\n readonly targetCandidate: IdentifierCandidate;\n readonly contradictionDetected: boolean;\n}\n\n/**\n * Checks whether two identifier names match by exact, canonical, or resource-prefixed heuristics.\n */\nexport function matchIdentifierNames(\n nameA: string,\n nameB: string,\n resourceA?: string,\n resourceB?: string,\n): { isMatch: boolean; kind: 'exact' | 'canonical' | 'resource_prefixed' | 'none' } {\n const canonA = nameA.toLowerCase().replace(/[^a-z0-9]/g, '');\n const canonB = nameB.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n // If both are simply generic \"id\", \"uuid\", or \"pk\", but belong to two different resources,\n // they are independent primary keys of different entities, not a reference relationship.\n if (\n (canonA === 'id' || canonA === 'uuid' || canonA === 'pk') &&\n (canonB === 'id' || canonB === 'uuid' || canonB === 'pk')\n ) {\n if (resourceA && resourceB && resourceA.toLowerCase() !== resourceB.toLowerCase()) {\n return { isMatch: false, kind: 'none' };\n }\n return { isMatch: true, kind: 'exact' };\n }\n\n if (nameA === nameB) {\n return { isMatch: true, kind: 'exact' };\n }\n\n if (canonA === canonB) {\n return { isMatch: true, kind: 'canonical' };\n }\n\n // Check resource prefix:\n // Case 1: Source A is resourceA, with id='id', matching foreign key 'resourceAId' on Target B\n if (resourceA) {\n const resA = resourceA.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (canonA === 'id' && (canonB === `${resA}id` || canonB === `${resA}uuid`)) {\n return { isMatch: true, kind: 'resource_prefixed' };\n }\n }\n\n // Case 2: Target B is resourceB, with id='id', matching foreign key 'resourceBId' on Source A\n if (resourceB) {\n const resB = resourceB.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (canonB === 'id' && (canonA === `${resB}id` || canonA === `${resB}uuid`)) {\n return { isMatch: true, kind: 'resource_prefixed' };\n }\n }\n\n return { isMatch: false, kind: 'none' };\n}\n\n/**\n * Evaluates type compatibility between two identifier candidates.\n */\nexport function evaluateTypeCompatibility(\n typeA: string,\n typeB: string,\n): { compatible: boolean; contradiction: boolean } {\n if (typeA === 'unknown' || typeB === 'unknown') {\n return { compatible: true, contradiction: false };\n }\n\n if (typeA === typeB) {\n return { compatible: true, contradiction: false };\n }\n\n if (\n (typeA === 'number' && typeB === 'integer') ||\n (typeA === 'integer' && typeB === 'number')\n ) {\n return { compatible: true, contradiction: false };\n }\n\n // If one is string and the other is integer/number, check if string could be numeric id\n // In HTTP REST APIs, path params are often strings while JSON payloads use numbers.\n // This is weakly compatible rather than a strict contradiction, unless sample values clash.\n if (\n (typeA === 'string' && (typeB === 'number' || typeB === 'integer')) ||\n (typeB === 'string' && (typeA === 'number' || typeA === 'integer'))\n ) {\n return { compatible: true, contradiction: false };\n }\n\n // Contradiction: incompatible scalar types\n return { compatible: false, contradiction: true };\n}\n\nfunction extractComparisonItems(\n input:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n): readonly string[] {\n // If raw array is passed directly (e.g. testing the mathematical set logic), compare those\n if (Array.isArray(input)) {\n return (input as readonly (string | number)[]).map(String);\n }\n\n const obj = input as {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n };\n\n // For identifier candidates, strictly require keyed HMAC fingerprints.\n // Never silently fall back to plaintext comparisons when unconfigured.\n if (obj.sampleFingerprints && obj.sampleFingerprints.length > 0) {\n return obj.sampleFingerprints;\n }\n\n return [];\n}\n\n/**\n * Calculates sample value overlap between two candidate identifiers using privacy-preserving fingerprints.\n * Accepts either identifier candidate objects or raw sample arrays.\n */\nexport function calculateSampleOverlap(\n candidateA:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n candidateB:\n | {\n readonly sampleFingerprints?: readonly string[];\n readonly sampleValues?: readonly (string | number)[];\n }\n | readonly (string | number)[],\n): {\n overlapRatio: number;\n intersectionCount: number;\n sampleAStats: number;\n sampleBStats: number;\n sharedFingerprints: readonly string[];\n sharedSamples?: readonly string[];\n} {\n const itemsA = extractComparisonItems(candidateA);\n const itemsB = extractComparisonItems(candidateB);\n\n if (itemsA.length === 0 || itemsB.length === 0) {\n return {\n overlapRatio: 0,\n intersectionCount: 0,\n sampleAStats: itemsA.length,\n sampleBStats: itemsB.length,\n sharedFingerprints: [],\n };\n }\n\n const setA = new Set(itemsA);\n const setB = new Set(itemsB);\n\n const intersection: string[] = [];\n for (const item of setA) {\n if (setB.has(item)) {\n intersection.push(item);\n }\n }\n\n const minSetSize = Math.min(setA.size, setB.size);\n const overlapRatio = minSetSize > 0 ? intersection.length / minSetSize : 0;\n\n return {\n overlapRatio,\n intersectionCount: intersection.length,\n sampleAStats: setA.size,\n sampleBStats: setB.size,\n sharedFingerprints: intersection.slice(0, 10),\n sharedSamples: intersection.slice(0, 10),\n };\n}\n\n/**\n * Compares two identifier candidates and produces match evidence and score.\n */\nexport function matchIdentifierCandidates(\n source: IdentifierCandidate,\n target: IdentifierCandidate,\n sourceResource?: string,\n targetResource?: string,\n): IdentifierMatchResult {\n const evidence: EvidenceRecord[] = [];\n let score = 0;\n let contradictionDetected = false;\n\n // If both candidates are generic \"id\" or \"uuid\" on different resources,\n // they are independent primary keys (e.g. user.id vs order.id).\n // They must not match, even if numerical sample values happen to overlap.\n const isBothGenericIdOnDifferentResources =\n Boolean(sourceResource) &&\n Boolean(targetResource) &&\n sourceResource?.toLowerCase() !== targetResource?.toLowerCase() &&\n (source.name.toLowerCase() === 'id' || source.name.toLowerCase() === 'uuid') &&\n (target.name.toLowerCase() === 'id' || target.name.toLowerCase() === 'uuid');\n\n if (isBothGenericIdOnDifferentResources) {\n return {\n isMatch: false,\n score: 0,\n evidence: [],\n sourceCandidate: source,\n targetCandidate: target,\n contradictionDetected: false,\n };\n }\n\n // 1. Name Match\n const nameMatch = matchIdentifierNames(\n source.name,\n target.name,\n sourceResource,\n targetResource,\n );\n\n if (nameMatch.isMatch) {\n let weight = 0.25;\n if (nameMatch.kind === 'exact') {\n weight = 0.3;\n } else if (nameMatch.kind === 'resource_prefixed') {\n weight = 0.35;\n }\n score += weight;\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight,\n description: `Identifier name match between '${source.propertyPath}' and '${target.propertyPath}' (${nameMatch.kind})`,\n details: {\n sourceProperty: source.propertyPath,\n targetProperty: target.propertyPath,\n sourceName: source.name,\n targetName: target.name,\n matchKind: nameMatch.kind,\n },\n });\n } else {\n // If names don't match at all, they might still be related if sample values overlap strongly,\n // but without name match or sample overlap, it's not a match.\n }\n\n // 2. Type Compatibility\n const typeComp = evaluateTypeCompatibility(source.type, target.type);\n if (typeComp.contradiction) {\n contradictionDetected = true;\n score -= 0.5;\n evidence.push({\n kind: 'CONTRADICTION',\n weight: -0.5,\n description: `Type incompatibility between '${source.propertyPath}' (${source.type}) and '${target.propertyPath}' (${target.type})`,\n details: {\n sourceType: source.type,\n targetType: target.type,\n },\n });\n } else if (nameMatch.isMatch && typeComp.compatible) {\n const typeWeight = 0.15;\n score += typeWeight;\n evidence.push({\n kind: 'SCHEMA_TYPE_MATCH',\n weight: typeWeight,\n description: `Compatible schema types: source '${source.type}', target '${target.type}'`,\n details: {\n sourceType: source.type,\n targetType: target.type,\n },\n });\n }\n\n // 3. Sample Value Overlap\n const overlap = calculateSampleOverlap(source, target);\n\n if (overlap.intersectionCount > 0) {\n const overlapWeight = Math.min(0.35, 0.15 + overlap.overlapRatio * 0.2);\n score += overlapWeight;\n evidence.push({\n kind: 'SAMPLE_VALUE_OVERLAP',\n weight: overlapWeight,\n description: `Observed ${overlap.intersectionCount} overlapping sample identifier values via keyed HMAC-SHA-256`,\n details: {\n intersectionCount: overlap.intersectionCount,\n overlapRatio: overlap.overlapRatio,\n },\n });\n }\n\n // Final match determination\n // Must have name match or sample value overlap, and overall positive score\n const isMatch = (nameMatch.isMatch || overlap.intersectionCount > 0) && score > 0.2;\n\n return {\n isMatch,\n score: Math.max(0, Math.min(1.0, score)),\n evidence,\n sourceCandidate: source,\n targetCandidate: target,\n contradictionDetected,\n };\n}\n","import type {\n EndpointTopologyType,\n EntityCardinality,\n EvidenceRecord,\n RelationshipConfidence,\n RelationshipConfidenceTier,\n RelationshipType,\n} from '../domain/types.js';\n\nexport interface ScoreComputationResult {\n readonly confidence: RelationshipConfidence;\n readonly inferredType: RelationshipType;\n}\n\n/**\n * Extracts a stable evidence identity key to prevent duplicate evidence inflation\n * while ensuring distinct properties sharing descriptions are not collapsed.\n */\nfunction getEvidenceIdentity(item: EvidenceRecord): string {\n const details = item.details as Record<string, unknown> | undefined;\n const src = details?.sourceProperty ? String(details.sourceProperty) : '';\n const tgt = details?.targetProperty ? String(details.targetProperty) : '';\n const desc = item.description ?? '';\n return `${item.kind}|${src}->${tgt}|${desc}`;\n}\n\n/**\n * Computes relationship confidence and assigns tier, reasons, and penalties.\n * Deduplicates evidence to ensure duplicate observations do not falsely inflate confidence.\n */\nexport function computeRelationshipConfidence(\n evidence: readonly EvidenceRecord[],\n): RelationshipConfidence {\n // Deduplicate evidence records by stable identity\n const seen = new Set<string>();\n const uniqueEvidence: EvidenceRecord[] = [];\n for (const item of evidence) {\n const key = getEvidenceIdentity(item);\n if (!seen.has(key)) {\n seen.add(key);\n uniqueEvidence.push(item);\n }\n }\n\n let score = 0;\n const reasons: string[] = [];\n const penalties: string[] = [];\n\n for (const item of uniqueEvidence) {\n score += item.weight;\n if (item.weight > 0) {\n reasons.push(item.description);\n } else if (item.weight < 0) {\n penalties.push(item.description);\n }\n }\n\n // Multi-observation consistency bonus strictly requires >= 3 distinct signal kinds and no contradictions\n const positiveSignalKinds = new Set<string>();\n for (const item of uniqueEvidence) {\n if (item.weight > 0) {\n positiveSignalKinds.add(item.kind);\n }\n }\n\n if (positiveSignalKinds.size >= 3 && penalties.length === 0) {\n const multiObsBonus = 0.1;\n score += multiObsBonus;\n reasons.push(\n `Multiple distinct corroborating signal kinds observed (${positiveSignalKinds.size} distinct kinds)`,\n );\n }\n\n // Clamp score strictly between 0.0 and 1.0\n const clampedScore = Math.max(0, Math.min(1.0, Math.round(score * 1000) / 1000));\n\n let tier: RelationshipConfidenceTier = 'LOW';\n if (clampedScore >= 0.8) {\n tier = 'HIGH';\n } else if (clampedScore >= 0.5) {\n tier = 'MEDIUM';\n }\n\n return {\n score: clampedScore,\n tier,\n reasons,\n penalties,\n };\n}\n\n/**\n * Infers relationship type, endpoint topology, and entity cardinality.\n * Strictly separates endpoint routing topology from entity-level data model cardinality.\n */\nexport function inferRelationshipSemantics(options: {\n isStructuralHierarchy?: boolean;\n hasIdentifierReference?: boolean;\n isCollectionToInstance?: boolean;\n isActionDispatch?: boolean;\n sourceClassification?: string;\n targetClassification?: string;\n sourceIsParent?: boolean;\n}): {\n type: RelationshipType;\n topology: EndpointTopologyType;\n cardinality: EntityCardinality;\n} {\n const {\n isStructuralHierarchy,\n hasIdentifierReference,\n isCollectionToInstance,\n isActionDispatch,\n sourceClassification,\n targetClassification,\n } = options;\n\n // Case 1: Action dispatch (e.g. POST /users/:id/activate)\n if (isActionDispatch) {\n return {\n type: 'ACTION',\n topology: 'ACTION_DISPATCH',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 2: Collection to instance relationship (e.g. GET /users -> GET /users/:id)\n if (isCollectionToInstance) {\n return {\n type: 'COLLECTION_INSTANCE',\n topology: 'COLLECTION_TO_INSTANCE',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 3: Pure structural hierarchy (e.g. GET /users/:id -> GET /users/:id/orders)\n if (isStructuralHierarchy && !hasIdentifierReference) {\n return {\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n };\n }\n\n // Case 4: Cross-resource identifier reference\n if (hasIdentifierReference) {\n // If source is a collection referencing a target single resource detail (MANY_TO_ONE)\n if (\n (sourceClassification === 'COLLECTION_READ' ||\n sourceClassification === 'NESTED_COLLECTION_READ') &&\n targetClassification === 'RESOURCE_READ'\n ) {\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'MANY_TO_ONE',\n };\n }\n\n // If source is a single resource referencing a target collection (ONE_TO_MANY)\n if (\n sourceClassification === 'RESOURCE_READ' &&\n (targetClassification === 'NESTED_COLLECTION_READ' ||\n targetClassification === 'COLLECTION_READ')\n ) {\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'ONE_TO_MANY',\n };\n }\n\n // Generic cross-endpoint foreign key reference when uniqueness is unverified (e.g. detail to detail)\n return {\n type: 'REFERENCES',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'UNKNOWN',\n };\n }\n\n if (isStructuralHierarchy) {\n return {\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n };\n }\n\n return {\n type: 'UNKNOWN',\n topology: 'CROSS_RESOURCE_REFERENCE',\n cardinality: 'UNKNOWN',\n };\n}\n\n/**\n * Infers relationship type and cardinality based on endpoint classifications and evidence.\n */\nexport function inferRelationshipType(options: {\n isStructuralHierarchy: boolean;\n hasIdentifierReference: boolean;\n sourceClassification?: string;\n targetClassification?: string;\n sourceIsParent?: boolean;\n}): RelationshipType {\n return inferRelationshipSemantics(options).type;\n}\n\n","import type {\n ApiRelationship,\n DiscoveryEngineOptions,\n DiscoveryMetrics,\n EndpointAggregate,\n EndpointClassification,\n EndpointSchemaAggregate,\n EvidenceRecord,\n IdentifierCandidate,\n RelationshipType,\n} from '../domain/types.js';\nimport {\n extractEndpointParamIdentifiers,\n extractSchemaIdentifiers,\n normalizeEndpointInput,\n type EndpointInput,\n} from '../identifiers/identifier-extractor.js';\nimport { matchIdentifierCandidates } from '../identifiers/identifier-matcher.js';\nimport { classifyEndpoint } from '../resources/endpoint-classifier.js';\nimport {\n extractPathHierarchy,\n type PathResourceHierarchy,\n} from '../resources/resource-identifier.js';\nimport {\n computeRelationshipConfidence,\n inferRelationshipSemantics,\n inferRelationshipType,\n} from '../scoring/relationship-scorer.js';\n\n/**\n * Extracts indexing keys for an endpoint to prune non-viable candidate pair comparisons.\n */\nfunction extractEndpointIndexKeys(\n candidates: readonly IdentifierCandidate[],\n primaryResourceName?: string,\n): Set<string> {\n const keys = new Set<string>();\n const res = primaryResourceName?.toLowerCase().replace(/[^a-z0-9]/g, '');\n\n for (const c of candidates) {\n const canon = c.name.toLowerCase().replace(/[^a-z0-9]/g, '');\n if (!canon) continue;\n\n if (canon === 'id' || canon === 'uuid' || canon === 'pk') {\n if (res) {\n keys.add(`${res}id`);\n keys.add(`${res}uuid`);\n } else {\n keys.add(canon);\n }\n } else {\n keys.add(canon);\n }\n }\n\n return keys;\n}\n\nexport class RelationshipDiscoveryEngine {\n private readonly endpoints = new Map<string, EndpointInput>();\n private readonly schemas = new Map<string, EndpointSchemaAggregate>();\n private readonly classifications = new Map<string, EndpointClassification>();\n private readonly relationships = new Map<string, ApiRelationship>();\n private readonly options: DiscoveryEngineOptions;\n private lastMetrics?: DiscoveryMetrics;\n\n constructor(options?: DiscoveryEngineOptions) {\n this.options = {\n minConfidence: 0.3,\n maxSchemaDepth: 5,\n maxSampleValues: 50,\n stripPrefixes: [\n '/api',\n '/v1',\n '/v2',\n '/v3',\n '/v4',\n '/rest',\n '/public',\n '/internal',\n ],\n ...options,\n };\n }\n\n /**\n * Updates the HMAC fingerprint secret for privacy-preserving identifier matching.\n * Enables runtime key rotation without losing existing manual confirmation states.\n */\n public setFingerprintSecret(secret?: string): void {\n (this.options as { fingerprintSecret?: string }).fingerprintSecret = secret;\n }\n\n /**\n * Retrieves telemetry metrics from the most recent discovery run, if any.\n */\n public getLastMetrics(): DiscoveryMetrics | undefined {\n return this.lastMetrics;\n }\n\n /**\n * Registers a single endpoint aggregate or endpoint input.\n */\n public registerEndpoint(endpoint: EndpointAggregate | EndpointInput): void {\n const normalized = normalizeEndpointInput(endpoint);\n this.endpoints.set(normalized.id, normalized);\n\n // Compute classification\n const classification = classifyEndpoint(normalized, {\n stripPrefixes: this.options.stripPrefixes,\n });\n this.classifications.set(normalized.id, classification);\n }\n\n /**\n * Registers multiple endpoints in batch.\n */\n public registerEndpoints(\n endpoints: readonly (EndpointAggregate | EndpointInput)[],\n ): void {\n for (const ep of endpoints) {\n this.registerEndpoint(ep);\n }\n }\n\n /**\n * Registers a schema aggregate for an endpoint.\n */\n public registerSchema(schemaAggregate: EndpointSchemaAggregate): void {\n this.schemas.set(schemaAggregate.endpointId, schemaAggregate);\n }\n\n /**\n * Registers multiple schema aggregates in batch.\n */\n public registerSchemas(\n schemaAggregates: readonly EndpointSchemaAggregate[],\n ): void {\n for (const sa of schemaAggregates) {\n this.registerSchema(sa);\n }\n }\n\n /**\n * Retrieves the classification for a registered endpoint.\n */\n public getClassification(\n endpointId: string,\n ): EndpointClassification | undefined {\n return this.classifications.get(endpointId);\n }\n\n /**\n * Discovers relationships across all registered endpoints.\n */\n public discoverRelationships(\n options?: DiscoveryEngineOptions,\n ): readonly ApiRelationship[] {\n return this.discoverRelationshipsWithMetrics(options).relationships;\n }\n\n /**\n * Discovers relationships across all registered endpoints and returns execution metrics.\n */\n public discoverRelationshipsWithMetrics(\n options?: DiscoveryEngineOptions,\n ): { relationships: readonly ApiRelationship[]; metrics: DiscoveryMetrics } {\n const startTime = performance.now();\n const opts = { ...this.options, ...options };\n const endpointList = Array.from(this.endpoints.values());\n const minConfidence = opts.minConfidence ?? 0.3;\n\n // Cache pre-computed path hierarchies for each endpoint (O(N) instead of O(N^2))\n const endpointHierarchies = new Map<string, PathResourceHierarchy>();\n for (const ep of endpointList) {\n endpointHierarchies.set(\n ep.id,\n extractPathHierarchy(ep.pathTemplate, {\n stripPrefixes: opts.stripPrefixes,\n }),\n );\n }\n\n // Cache extracted identifiers per endpoint\n const endpointIdentifiers = new Map<string, IdentifierCandidate[]>();\n for (const ep of endpointList) {\n const paramIds = extractEndpointParamIdentifiers(ep, opts);\n const schemaAggregate = this.schemas.get(ep.id);\n const schemaIds = schemaAggregate\n ? extractSchemaIdentifiers(ep.id, schemaAggregate, opts)\n : [];\n endpointIdentifiers.set(ep.id, [...paramIds, ...schemaIds]);\n }\n\n // Build resource and identifier indices to prune non-viable candidate pairs\n const endpointsByResource = new Map<string, number[]>();\n const endpointsByIdKey = new Map<string, number[]>();\n\n for (let i = 0; i < endpointList.length; i++) {\n const ep = endpointList[i]!;\n const hier = endpointHierarchies.get(ep.id)!;\n const ids = endpointIdentifiers.get(ep.id) ?? [];\n\n if (hier.primaryResource?.name) {\n const resKey = hier.primaryResource.name.toLowerCase();\n const list = endpointsByResource.get(resKey) ?? [];\n list.push(i);\n endpointsByResource.set(resKey, list);\n }\n\n const keys = extractEndpointIndexKeys(ids, hier.primaryResource?.name);\n for (const key of keys) {\n const list = endpointsByIdKey.get(key) ?? [];\n list.push(i);\n endpointsByIdKey.set(key, list);\n }\n }\n\n const extractionTimeMs = performance.now() - startTime;\n const scoringStartTime = performance.now();\n\n const newlyDiscovered = new Map<string, ApiRelationship>();\n const now = Date.now();\n let evaluatedPairs = 0;\n let evaluatedIdentifierComparisons = 0;\n\n for (let i = 0; i < endpointList.length; i++) {\n const epA = endpointList[i]!;\n const classA = this.classifications.get(epA.id);\n const idsA = endpointIdentifiers.get(epA.id) ?? [];\n const hierA = endpointHierarchies.get(epA.id)!;\n\n // Identify candidate target endpoints via index lookup\n const candidateTargets = new Set<number>();\n\n if (hierA.primaryResource?.name) {\n const resMatches = endpointsByResource.get(\n hierA.primaryResource.name.toLowerCase(),\n );\n if (resMatches) {\n for (const idx of resMatches) {\n if (idx !== i) candidateTargets.add(idx);\n }\n }\n }\n\n const keysA = extractEndpointIndexKeys(idsA, hierA.primaryResource?.name);\n for (const key of keysA) {\n const idMatches = endpointsByIdKey.get(key);\n if (idMatches) {\n for (const idx of idMatches) {\n if (idx !== i) candidateTargets.add(idx);\n }\n }\n }\n\n for (const j of candidateTargets) {\n evaluatedPairs++;\n const epB = endpointList[j]!;\n const classB = this.classifications.get(epB.id);\n const idsB = endpointIdentifiers.get(epB.id) ?? [];\n const hierB = endpointHierarchies.get(epB.id)!;\n\n // ---------------------------------------------------------------------\n // 1. Structural Hierarchy Discovery (PARENT_CHILD)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierB.nestedResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n (classA?.type === 'RESOURCE_READ' || classA?.type === 'COLLECTION_READ') &&\n epB.pathTemplate.startsWith(epA.pathTemplate) &&\n (classB?.type === 'NESTED_COLLECTION_READ' ||\n classB?.type === 'NESTED_RESOURCE_READ' ||\n (classB?.type !== 'ACTION' && hierB.nestedResource))\n ) {\n const parentParam = hierB.resourceParams.get(hierA.primaryResource.name);\n if (parentParam) {\n const parentHasParam = hierA.resourceParams.has(hierA.primaryResource.name);\n if (!parentHasParam) {\n // epA is a root collection (e.g. /users) without the required instance param,\n // so it is not the direct parent of /users/:userId/orders\n continue;\n }\n }\n\n // B has A as a parent resource!\n // e.g. A is /users/:userId, and B is /users/:userId/orders\n const relId = `rel:structural:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.45,\n description: `Path nesting: resource '${hierB.nestedResource.name}' in '${epB.pathTemplate}' is hierarchically nested under parent resource '${hierA.primaryResource.name}' in '${epA.pathTemplate}'`,\n details: {\n parentResource: hierA.primaryResource.name,\n nestedResource: hierB.nestedResource.name,\n parentPath: epA.pathTemplate,\n childPath: epB.pathTemplate,\n },\n },\n ];\n\n // If B has parameter matching A's resource\n if (parentParam) {\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight: 0.25,\n description: `Child endpoint path includes parent parameter ':${parentParam}'`,\n details: { parentParam },\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'PARENT_CHILD',\n topology: 'PARENT_TO_CHILD_PATH',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n\n // ---------------------------------------------------------------------\n // 2. Collection vs Resource Read Relationship (COLLECTION_INSTANCE)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n !hierA.nestedResource &&\n !hierB.nestedResource\n ) {\n if (\n classA?.type === 'COLLECTION_READ' &&\n classB?.type === 'RESOURCE_READ'\n ) {\n const relId = `rel:collection:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.4,\n description: `Collection-to-resource hierarchy for resource '${hierA.primaryResource.name}'`,\n details: {\n collectionPath: epA.pathTemplate,\n detailPath: epB.pathTemplate,\n resource: hierA.primaryResource.name,\n },\n },\n ];\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'COLLECTION_INSTANCE',\n topology: 'COLLECTION_TO_INSTANCE',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n }\n\n // ---------------------------------------------------------------------\n // 3. Action Dispatch Relationship (ACTION)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name &&\n classA?.type === 'RESOURCE_READ' &&\n classB?.type === 'ACTION' &&\n epB.pathTemplate.startsWith(epA.pathTemplate)\n ) {\n const relId = `rel:action:${epA.id}->${epB.id}`;\n const evidence: EvidenceRecord[] = [\n {\n kind: 'PATH_HIERARCHY',\n weight: 0.5,\n description: `Action dispatch operation '${hierB.action ?? 'action'}' executed on resource '${hierA.primaryResource.name}'`,\n details: {\n resource: hierA.primaryResource.name,\n actionVerb: hierB.action,\n instancePath: epA.pathTemplate,\n actionPath: epB.pathTemplate,\n },\n },\n ];\n\n const parentParam = hierB.resourceParams.get(hierA.primaryResource.name);\n if (parentParam) {\n evidence.push({\n kind: 'IDENTIFIER_NAME_MATCH',\n weight: 0.25,\n description: `Action endpoint path includes instance parameter ':${parentParam}'`,\n details: { parentParam },\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n if (confidence.score >= minConfidence) {\n const existing = this.relationships.get(relId);\n const status = existing ? existing.status : 'INFERRED';\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: 'ACTION',\n topology: 'ACTION_DISPATCH',\n cardinality: 'UNKNOWN',\n status,\n confidence,\n evidence,\n discoveredAt: existing ? existing.discoveredAt : now,\n updatedAt: now,\n };\n newlyDiscovered.set(relId, relationship);\n }\n }\n\n // ---------------------------------------------------------------------\n // 4. Identifier Reference Discovery (REFERENCES / Cross-Resource)\n // ---------------------------------------------------------------------\n if (\n hierA.primaryResource &&\n hierB.primaryResource &&\n hierA.primaryResource.name === hierB.primaryResource.name\n ) {\n // Operations within the same primary resource domain are governed by\n // structural hierarchy (PARENT_CHILD), collection-to-instance (COLLECTION_INSTANCE),\n // or action dispatch (ACTION). They do not create cross-resource REFERENCES.\n continue;\n }\n\n // Target of a foreign key reference must be a canonical instance read resource endpoint\n const isCanonicalTarget =\n classB?.type === 'RESOURCE_READ' ||\n classB?.type === 'NESTED_RESOURCE_READ';\n\n if (!isCanonicalTarget) {\n continue;\n }\n\n const seenMatches = new Set<string>();\n\n for (const idA of idsA) {\n for (const idB of idsB) {\n // Target identifier must be a primary key candidate of the target resource\n const isTargetPrimaryKey =\n idB.isPrimaryKeyCandidate === true ||\n idB.name.toLowerCase() === 'id' ||\n idB.name.toLowerCase() === 'uuid' ||\n (hierB.primaryResource &&\n (idB.name.toLowerCase() ===\n `${hierB.primaryResource.name.toLowerCase()}id` ||\n idB.name.toLowerCase() ===\n `${hierB.primaryResource.name.toLowerCase()}uuid`)) ||\n idB.location === 'path_param';\n\n if (!isTargetPrimaryKey) {\n continue;\n }\n\n evaluatedIdentifierComparisons++;\n const matchKey = `${idA.propertyPath}->${idB.propertyPath}`;\n if (seenMatches.has(matchKey)) continue;\n\n const resA = hierA.primaryResource?.name;\n const resB = hierB.primaryResource?.name;\n\n const matchResult = matchIdentifierCandidates(\n idA,\n idB,\n resA,\n resB,\n );\n\n if (matchResult.isMatch) {\n seenMatches.add(matchKey);\n\n const evidence: EvidenceRecord[] = [...matchResult.evidence];\n\n // Check if structural hierarchy also supports this reference\n const isStructural =\n Boolean(hierB.nestedResource) &&\n hierA.primaryResource?.name === hierB.primaryResource?.name;\n\n if (isStructural) {\n evidence.push({\n kind: 'PATH_HIERARCHY',\n weight: 0.2,\n description: `Path structure corroborates identifier reference from parent '${hierA.primaryResource?.name}' to child '${hierB.nestedResource?.name}'`,\n });\n }\n\n const confidence = computeRelationshipConfidence(evidence);\n\n if (confidence.score >= minConfidence) {\n const semantics = inferRelationshipSemantics({\n isStructuralHierarchy: false,\n hasIdentifierReference: true,\n sourceClassification: classA?.type,\n targetClassification: classB?.type,\n });\n\n // Stable relationship ID: one canonical edge per source foreign key property to target endpoint\n const relId = `rel:reference:${epA.id}->${epB.id}:${idA.propertyPath}`;\n const existingDiscovered = newlyDiscovered.get(relId);\n if (\n existingDiscovered &&\n existingDiscovered.confidence.score >= confidence.score\n ) {\n continue;\n }\n\n const existingPersisted = this.relationships.get(relId);\n const status = existingPersisted ? existingPersisted.status : 'INFERRED';\n\n const relationship: ApiRelationship = {\n id: relId,\n sourceEndpointId: epA.id,\n targetEndpointId: epB.id,\n type: semantics.type,\n topology: semantics.topology,\n cardinality: semantics.cardinality,\n status,\n confidence,\n evidence,\n sourceProperty: idA.propertyPath,\n targetProperty: idB.propertyPath,\n metadata: {\n sourceProperty: idA.propertyPath,\n targetProperty: idB.propertyPath,\n sourceName: idA.name,\n targetName: idB.name,\n sourceType: idA.type,\n targetType: idB.type,\n sourceLocation: idA.location,\n targetLocation: idB.location,\n },\n discoveredAt: existingPersisted ? existingPersisted.discoveredAt : now,\n updatedAt: now,\n };\n\n newlyDiscovered.set(relId, relationship);\n }\n }\n }\n }\n }\n }\n\n // Prune stale INFERRED relationships that are no longer supported by current observations,\n // while strictly preserving user CONFIRMED and REJECTED decisions.\n for (const [id, rel] of this.relationships.entries()) {\n if (rel.status === 'INFERRED' && !newlyDiscovered.has(id)) {\n this.relationships.delete(id);\n }\n }\n\n // Merge discovered relationships into store, keeping existing confirmed/rejected states\n for (const [id, rel] of newlyDiscovered.entries()) {\n const existing = this.relationships.get(id);\n if (existing) {\n this.relationships.set(id, {\n ...rel,\n status: existing.status, // preserve status\n discoveredAt: existing.discoveredAt,\n });\n } else {\n this.relationships.set(id, rel);\n }\n }\n\n const scoringTimeMs = performance.now() - scoringStartTime;\n const totalTimeMs = performance.now() - startTime;\n const totalPossiblePairs =\n endpointList.length * Math.max(0, endpointList.length - 1);\n const prunedPairs = Math.max(0, totalPossiblePairs - evaluatedPairs);\n\n const resultRelationships = this.getRelationships();\n\n this.lastMetrics = {\n totalEndpoints: endpointList.length,\n evaluatedPairs,\n prunedPairs,\n evaluatedIdentifierComparisons,\n discoveredRelationships: resultRelationships.length,\n extractionTimeMs,\n scoringTimeMs,\n totalTimeMs,\n };\n\n return {\n relationships: resultRelationships,\n metrics: this.lastMetrics,\n };\n }\n\n /**\n * Confirms an inferred relationship explicitly.\n */\n public confirmRelationship(id: string): ApiRelationship {\n const existing = this.relationships.get(id);\n if (!existing) {\n throw new Error(`Cannot confirm non-existent relationship: '${id}'`);\n }\n\n const updated: ApiRelationship = {\n ...existing,\n status: 'CONFIRMED',\n updatedAt: Date.now(),\n };\n this.relationships.set(id, updated);\n return updated;\n }\n\n /**\n * Rejects an inferred relationship explicitly.\n */\n public rejectRelationship(id: string): ApiRelationship {\n const existing = this.relationships.get(id);\n if (!existing) {\n throw new Error(`Cannot reject non-existent relationship: '${id}'`);\n }\n\n const updated: ApiRelationship = {\n ...existing,\n status: 'REJECTED',\n updatedAt: Date.now(),\n };\n this.relationships.set(id, updated);\n return updated;\n }\n\n /**\n * Retrieves all relationships sorted deterministically.\n */\n public getRelationships(): readonly ApiRelationship[] {\n return Array.from(this.relationships.values()).sort((a, b) => {\n // Sort by confidence score descending\n if (b.confidence.score !== a.confidence.score) {\n return b.confidence.score - a.confidence.score;\n }\n // Sort deterministically by id\n return a.id.localeCompare(b.id);\n });\n }\n\n /**\n * Retrieves a single relationship by id.\n */\n public getRelationship(id: string): ApiRelationship | undefined {\n return this.relationships.get(id);\n }\n\n /**\n * Retrieves all relationships involving a specific endpoint (either as source or target).\n */\n public getRelationshipsForEndpoint(\n endpointId: string,\n ): readonly ApiRelationship[] {\n return this.getRelationships().filter(\n (rel) =>\n rel.sourceEndpointId === endpointId ||\n rel.targetEndpointId === endpointId,\n );\n }\n\n /**\n * Clears all registered endpoints, schemas, and discovered relationships.\n */\n public clear(): void {\n this.endpoints.clear();\n this.schemas.clear();\n this.classifications.clear();\n this.relationships.clear();\n }\n}\n\n","import { singularize } from '@luxray/normalization';\nimport { extractPathHierarchy } from '@luxray/relationship-discovery';\n\n/**\n * Converts Express-style colon parameters (/users/:userId) to OpenAPI braces (/users/{userId}).\n */\nexport function toOpenApiPath(pathTemplate: string): string {\n return pathTemplate.replace(/:([a-zA-Z0-9_]+)/g, '{$1}');\n}\n\n/**\n * Extracts parameter names from an Express-style or OpenAPI path template.\n */\nexport function extractPathParameterNames(pathTemplate: string): string[] {\n const params: string[] = [];\n // Match :param\n const colonMatches = pathTemplate.matchAll(/:([a-zA-Z0-9_]+)/g);\n for (const match of colonMatches) {\n if (match[1]) params.push(match[1]);\n }\n // Match {param}\n const braceMatches = pathTemplate.matchAll(/\\{([a-zA-Z0-9_]+)\\}/g);\n for (const match of braceMatches) {\n if (match[1] && !params.includes(match[1])) params.push(match[1]);\n }\n return params;\n}\n\n/**\n * Capitalizes the first letter of a string.\n */\nfunction capitalize(str: string): string {\n if (!str) return '';\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Converts camelCase, snake_case, kebab-case to PascalCase words.\n */\nfunction toPascalCase(str: string): string {\n return str\n .replace(/[^a-zA-Z0-9]+/g, ' ')\n .split(' ')\n .filter(Boolean)\n .map((word) => capitalize(word.toLowerCase()))\n .join('');\n}\n\n/**\n * Generates a clean, deterministic operationId from method, path template, and resource semantics.\n */\nexport function generateOperationId(\n method: string,\n pathTemplate: string,\n resourceName?: string,\n): string {\n const upperMethod = method.toUpperCase();\n const hierarchy = extractPathHierarchy(pathTemplate);\n const primary = resourceName ?? hierarchy.primaryResource?.name ?? 'Resource';\n const nested = hierarchy.nestedResource?.name;\n const action = hierarchy.action;\n const isTerminalParam =\n pathTemplate.endsWith('}') || /:[a-zA-Z0-9_]+$/.test(pathTemplate);\n\n // If terminal action verb (e.g. POST /users/:id/activate)\n if (action) {\n const actionPart = toPascalCase(action);\n const primaryPart = toPascalCase(singularize(primary));\n return `${action.toLowerCase()}${primaryPart}`;\n }\n\n // Nested resource (e.g. /users/:id/orders)\n if (nested) {\n const primarySingular = toPascalCase(singularize(primary));\n const nestedPlural = toPascalCase(hierarchy.nestedResource?.rawSegment ?? nested);\n const nestedSingular = toPascalCase(singularize(nested));\n\n if (upperMethod === 'GET') {\n return isTerminalParam\n ? `get${primarySingular}${nestedSingular}ById`\n : `list${primarySingular}${nestedPlural}`;\n }\n if (upperMethod === 'POST') {\n return `create${primarySingular}${nestedSingular}`;\n }\n if (upperMethod === 'PUT' || upperMethod === 'PATCH') {\n return `update${primarySingular}${nestedSingular}ById`;\n }\n if (upperMethod === 'DELETE') {\n return `delete${primarySingular}${nestedSingular}ById`;\n }\n }\n\n // Flat resource (e.g. /users or /users/:id)\n const primaryPlural = toPascalCase(hierarchy.primaryResource?.rawSegment ?? primary);\n const primarySingular = toPascalCase(singularize(primary));\n\n switch (upperMethod) {\n case 'GET':\n return isTerminalParam ? `get${primarySingular}ById` : `list${primaryPlural}`;\n case 'POST':\n return `create${primarySingular}`;\n case 'PUT':\n return `update${primarySingular}ById`;\n case 'PATCH':\n return `patch${primarySingular}ById`;\n case 'DELETE':\n return `delete${primarySingular}ById`;\n case 'HEAD':\n return `head${primaryPlural}`;\n case 'OPTIONS':\n return `options${primaryPlural}`;\n default:\n return `${method.toLowerCase()}${primarySingular}`;\n }\n}\n\n/**\n * Derives the OpenAPI tag for an endpoint based on its primary resource.\n */\nexport function deriveEndpointTag(pathTemplate: string): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const raw = hierarchy.primaryResource?.rawSegment ?? hierarchy.primaryResource?.name;\n if (!raw) return 'Default';\n return toPascalCase(raw);\n}\n\n/**\n * Generates an informative summary for an operation.\n */\nexport function generateOperationSummary(\n method: string,\n pathTemplate: string,\n resourceName?: string,\n): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const primary = resourceName ?? hierarchy.primaryResource?.name ?? 'item';\n const nested = hierarchy.nestedResource?.name;\n const action = hierarchy.action;\n const upperMethod = method.toUpperCase();\n const isTerminalParam =\n pathTemplate.endsWith('}') || /:[a-zA-Z0-9_]+$/.test(pathTemplate);\n\n if (action) {\n return `${capitalize(action)} ${singularize(primary)}`;\n }\n\n if (nested) {\n const parentSing = singularize(primary);\n const childSing = singularize(nested);\n const childPlural =\n hierarchy.nestedResource?.pluralName ??\n (nested.endsWith('s') ? nested : `${nested}s`);\n\n if (upperMethod === 'GET') {\n return isTerminalParam\n ? `Retrieve a specific ${childSing} for a ${parentSing}`\n : `List ${childPlural} for a ${parentSing}`;\n }\n if (upperMethod === 'POST') return `Create a new ${childSing} for a ${parentSing}`;\n if (upperMethod === 'PUT' || upperMethod === 'PATCH') return `Update ${childSing} for a ${parentSing}`;\n if (upperMethod === 'DELETE') return `Delete ${childSing} for a ${parentSing}`;\n }\n\n const sing = singularize(primary);\n const plural =\n hierarchy.primaryResource?.pluralName ??\n (primary.endsWith('s') ? primary : `${primary}s`);\n\n switch (upperMethod) {\n case 'GET':\n return isTerminalParam ? `Retrieve a ${sing} by ID` : `List all ${plural}`;\n case 'POST':\n return `Create a new ${sing}`;\n case 'PUT':\n case 'PATCH':\n return `Update an existing ${sing}`;\n case 'DELETE':\n return `Delete a ${sing}`;\n default:\n return `${upperMethod} on ${primary}`;\n }\n}\n\nexport const deriveResourceTag = deriveEndpointTag;\nexport const deriveOperationSummary = generateOperationSummary;\n","import { URL } from 'node:url';\nimport type { EndpointAggregate, QueryParamMetadata } from '@luxray/shared';\nimport type { ParameterObject, SchemaObject } from '../domain/openapi-types.js';\nimport { extractPathParameterNames } from './path-converter.js';\n\nexport interface ParameterConverterOptions {\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst INTEGER_REGEX = /^-?\\d+$/;\n\n/**\n * Checks if a sample value is safe to expose in OpenAPI examples.\n * Rejects redacted tokens, JWTs, authorization headers, and secrets.\n */\nexport function isSafeExampleValue(value: unknown): boolean {\n if (value === null || value === undefined) return false;\n if (typeof value === 'boolean' || typeof value === 'number') return true;\n if (typeof value === 'string') {\n if (value.trim() === '') return false;\n if (value.includes('[REDACTED]') || value.includes('***')) return false;\n if (/^(bearer|basic)\\s+/i.test(value)) return false;\n // JWT pattern\n if (/^[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}$/.test(value)) return false;\n // Common secret patterns\n if (/^(sk_live|sk_test|api_key|token)_[a-zA-Z0-9]+$/i.test(value)) return false;\n return true;\n }\n return false;\n}\n\n/**\n * Extracts sample values corresponding specifically to paramName from sample URLs based on pathTemplate.\n */\nexport function extractParamSampleValues(\n paramName: string,\n pathTemplate: string,\n sampleUrls: readonly string[] = [],\n): string[] {\n const templateSegments = pathTemplate.split('/').filter(Boolean);\n const paramIndex = templateSegments.findIndex(\n (seg) => seg === `:${paramName}` || seg === `{${paramName}}`,\n );\n if (paramIndex === -1) return [];\n\n const samples: string[] = [];\n\n for (const urlStr of sampleUrls) {\n try {\n const url = new URL(urlStr, 'https://example.com');\n const segments = url.pathname.split('/').filter(Boolean);\n\n // 1. Direct index match if segment lengths align\n if (segments.length === templateSegments.length && segments[paramIndex]) {\n samples.push(segments[paramIndex]);\n continue;\n }\n\n // 2. Relative alignment matching adjacent static segments\n if (paramIndex > 0) {\n const prevStatic = templateSegments[paramIndex - 1];\n if (prevStatic && !prevStatic.startsWith(':') && !prevStatic.startsWith('{')) {\n const matchIdx = segments.indexOf(prevStatic);\n const nextVal = matchIdx !== -1 ? segments[matchIdx + 1] : undefined;\n if (nextVal) {\n samples.push(nextVal);\n continue;\n }\n }\n }\n\n // 3. Fallback: if paramIndex is within bounds\n const boundVal = segments[paramIndex];\n if (boundVal) {\n samples.push(boundVal);\n }\n } catch {\n // Ignore malformed URL\n }\n }\n\n return samples.filter((s): s is string => Boolean(s));\n}\n\n/**\n * Heuristically detects scalar type and format of a path parameter from actual observed samples.\n */\nexport function inferPathParameterSchema(\n paramName: string,\n pathTemplate: string,\n sampleUrls: readonly string[] = [],\n): SchemaObject {\n const samples = extractParamSampleValues(paramName, pathTemplate, sampleUrls);\n\n if (samples.length > 0) {\n if (samples.every((s) => UUID_REGEX.test(s))) {\n return { type: 'string', format: 'uuid' };\n }\n\n if (samples.every((s) => INTEGER_REGEX.test(s))) {\n return { type: 'integer' };\n }\n\n return { type: 'string' };\n }\n\n return { type: 'string' };\n}\n\n/**\n * Converts observed path parameters to OpenAPI ParameterObject array.\n * Enforces OpenAPI requirement that path parameters MUST have required: true.\n */\nexport function convertPathParameters(\n endpoint: EndpointAggregate,\n): ParameterObject[] {\n const pathTemplate = endpoint.identity?.pathname ?? '';\n const paramNames = extractPathParameterNames(pathTemplate);\n const parameters: ParameterObject[] = [];\n\n for (const name of paramNames) {\n const schema = inferPathParameterSchema(name, pathTemplate, endpoint.sampleUrls);\n const paramObj: ParameterObject = {\n name,\n in: 'path',\n required: true,\n description: `Path parameter ${name}`,\n schema,\n };\n parameters.push(paramObj);\n }\n\n return parameters;\n}\n\n/**\n * Converts QueryParamMetadata from endpoint aggregate into an OpenAPI ParameterObject.\n * Employs conservative contract semantics: observed presence does not imply contract requiredness.\n */\nfunction convertQueryParam(\n paramName: string,\n meta: QueryParamMetadata,\n totalObservations: number,\n options: ParameterConverterOptions = {},\n): ParameterObject {\n let schema: SchemaObject;\n\n if (meta.isArray) {\n const itemType = meta.types.includes('number')\n ? 'number'\n : meta.types.includes('boolean')\n ? 'boolean'\n : 'string';\n schema = {\n type: 'array',\n items: { type: itemType },\n };\n } else if (meta.types.includes('number') && meta.types.length === 1) {\n schema = { type: 'number' };\n } else if (meta.types.includes('boolean') && meta.types.length === 1) {\n schema = { type: 'boolean' };\n } else {\n schema = { type: 'string' };\n }\n\n // Contract requirement: query parameters are optional by default in REST APIs\n // Observed presence is recorded in analytical metadata\n const paramObj: ParameterObject = {\n name: paramName,\n in: 'query',\n required: false,\n description: `Query parameter ${paramName}`,\n schema,\n };\n\n if (options.includeExtensions !== false) {\n const ext = paramObj as unknown as Record<string, unknown>;\n const isAlwaysObserved = totalObservations > 0 && meta.occurrences >= totalObservations;\n ext['x-luxray-observed-presence'] = isAlwaysObserved ? 'always' : 'optional';\n ext['x-luxray-occurrences'] = meta.occurrences;\n ext['x-luxray-total-observations'] = totalObservations;\n }\n\n if (\n options.includeExamples !== false &&\n meta.sampleValues &&\n meta.sampleValues.length > 0 &&\n isSafeExampleValue(meta.sampleValues[0])\n ) {\n paramObj.example = meta.sampleValues[0];\n }\n\n return paramObj;\n}\n\n/**\n * Converts all query parameters of an endpoint aggregate to OpenAPI ParameterObjects.\n */\nexport function convertQueryParameters(\n endpoint: EndpointAggregate,\n options: ParameterConverterOptions = {},\n): ParameterObject[] {\n const parameters: ParameterObject[] = [];\n const queryParams = endpoint.queryParams ?? {};\n\n for (const [name, meta] of Object.entries(queryParams)) {\n parameters.push(convertQueryParam(name, meta, endpoint.observationCount, options));\n }\n\n return parameters.sort((a, b) => a.name.localeCompare(b.name));\n}\n\n/**\n * Extracts and combines all parameters (path and query) for an endpoint.\n */\nexport function convertEndpointParameters(\n endpoint: EndpointAggregate,\n options: ParameterConverterOptions = {},\n): ParameterObject[] {\n const pathParams = convertPathParameters(endpoint);\n const queryParams = convertQueryParameters(endpoint, options);\n return [...pathParams, ...queryParams];\n}\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n InferredUnionSchema,\n} from '@luxray/shared';\nimport type {\n OpenApiVersion,\n ReferenceObject,\n SchemaObject,\n SchemaType,\n} from '../domain/openapi-types.js';\nimport { isSafeExampleValue } from './parameter-converter.js';\n\nexport interface SchemaRefResolver {\n getRefForSchema(schema: InferredSchema): string | undefined;\n}\n\nexport interface SchemaConverterOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\nconst UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;\nconst ISO_DATETIME_REGEX =\n /^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$/i;\nconst ISO_DATE_REGEX = /^\\d{4}-\\d{2}-\\d{2}$/;\nconst EMAIL_REGEX = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst URI_REGEX = /^https?:\\/\\/[^\\s/$.?#].[^\\s]*$/i;\nconst IPV4_REGEX = /^(?:[0-9]{1,3}\\.){3}[0-9]{1,3}$/;\n\n/**\n * Detects standard OpenAPI format string for string values based on observed samples.\n */\nexport function inferStringFormat(samples: readonly unknown[] = []): string | undefined {\n const strSamples = samples.filter((s): s is string => typeof s === 'string' && s.length > 0);\n if (strSamples.length === 0) return undefined;\n\n if (strSamples.every((s) => UUID_REGEX.test(s))) return 'uuid';\n if (strSamples.every((s) => ISO_DATETIME_REGEX.test(s))) return 'date-time';\n if (strSamples.every((s) => ISO_DATE_REGEX.test(s))) return 'date';\n if (strSamples.every((s) => EMAIL_REGEX.test(s))) return 'email';\n if (strSamples.every((s) => URI_REGEX.test(s))) return 'uri';\n if (strSamples.every((s) => IPV4_REGEX.test(s))) return 'ipv4';\n\n return undefined;\n}\n\n/**\n * Converts a primitive InferredPrimitiveSchema to OpenAPI SchemaObject.\n */\nfunction convertPrimitiveSchema(\n schema: InferredPrimitiveSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n if (schema.type === 'any') {\n return isNullable && !isOpenApi31 ? { nullable: true } : {};\n }\n\n if (schema.type === 'null') {\n if (isOpenApi31) {\n return { type: 'null' };\n }\n return { nullable: true };\n }\n\n const result: SchemaObject = {};\n const baseType = schema.type as SchemaType;\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = [baseType, 'null'];\n } else {\n result.type = baseType;\n result.nullable = true;\n }\n } else {\n result.type = baseType;\n }\n\n if (schema.type === 'string') {\n const format = inferStringFormat(schema.sampleValues);\n if (format) {\n result.format = format;\n }\n } else if (schema.type === 'integer') {\n const numbers = (schema.sampleValues ?? []).filter(\n (v: unknown): v is number => typeof v === 'number',\n );\n if (numbers.length > 0 && numbers.some((n: number) => n > 2147483647 || n < -2147483648)) {\n result.format = 'int64';\n } else if (numbers.length > 0) {\n result.format = 'int32';\n }\n }\n\n if (\n options.includeExamples !== false &&\n schema.sampleValues &&\n schema.sampleValues.length > 0 &&\n isSafeExampleValue(schema.sampleValues[0])\n ) {\n result.example = schema.sampleValues[0];\n }\n\n return result;\n}\n\n/**\n * Directly converts an InferredObjectSchema properties without attempting to resolve the root schema as a $ref.\n * Enables recursive and mutually recursive schema definitions in components.\n */\nexport function convertObjectSchemaDirect(\n schema: InferredObjectSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n const result: SchemaObject = {};\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = ['object', 'null'];\n } else {\n result.type = 'object';\n result.nullable = true;\n }\n } else {\n result.type = 'object';\n }\n\n const properties: Record<string, SchemaObject | ReferenceObject> = {};\n const requiredFields: string[] = [];\n\n const fieldEntries = (Object.entries(schema.fields ?? {}) as [string, FieldMetadata][]).sort(\n ([a], [b]) => a.localeCompare(b),\n );\n\n for (const [fieldName, fieldMeta] of fieldEntries) {\n const fieldSchema =\n fieldMeta.isNullable && !fieldMeta.schema.isNullable\n ? ({ ...fieldMeta.schema, isNullable: true } as InferredSchema)\n : fieldMeta.schema;\n\n properties[fieldName] = convertSchema(fieldSchema, options);\n\n if (!fieldMeta.isOptional) {\n requiredFields.push(fieldName);\n }\n }\n\n result.properties = properties;\n if (requiredFields.length > 0) {\n result.required = requiredFields;\n }\n\n return result;\n}\n\n/**\n * Converts an InferredObjectSchema to OpenAPI SchemaObject or ReferenceObject.\n */\nfunction convertObjectSchema(\n schema: InferredObjectSchema,\n options: SchemaConverterOptions,\n): SchemaObject | ReferenceObject {\n // Check if ref resolver has an existing component reference for this schema\n if (options.refResolver) {\n const ref = options.refResolver.getRefForSchema(schema);\n if (ref) {\n return { $ref: ref };\n }\n }\n\n return convertObjectSchemaDirect(schema, options);\n}\n\n/**\n * Converts an InferredArraySchema to OpenAPI SchemaObject.\n */\nfunction convertArraySchema(\n schema: InferredArraySchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n const result: SchemaObject = {};\n\n if (isNullable) {\n if (isOpenApi31) {\n result.type = ['array', 'null'];\n } else {\n result.type = 'array';\n result.nullable = true;\n }\n } else {\n result.type = 'array';\n }\n\n result.items = convertSchema(schema.itemSchema, options);\n\n return result;\n}\n\n/**\n * Converts an InferredUnionSchema to OpenAPI SchemaObject.\n * In OpenAPI 3.0.3, eliminates invalid { type: 'null' } variants in favor of nullable: true on anyOf.\n */\nfunction convertUnionSchema(\n schema: InferredUnionSchema,\n options: SchemaConverterOptions,\n): SchemaObject {\n const isOpenApi31 = options.openApiVersion !== '3.0.3';\n const isNullable = Boolean(schema.isNullable);\n\n if (!isOpenApi31) {\n let hasNullVariant = false;\n const nonNullVariants: (SchemaObject | ReferenceObject)[] = [];\n\n for (const v of schema.variants ?? []) {\n if (v.type === 'null') {\n hasNullVariant = true;\n } else {\n nonNullVariants.push(convertSchema(v, options));\n }\n }\n\n const shouldBeNullable = isNullable || hasNullVariant;\n if (shouldBeNullable) {\n return { anyOf: nonNullVariants, nullable: true };\n }\n return { anyOf: nonNullVariants };\n }\n\n const variants = (schema.variants ?? []).map((v: InferredSchema) =>\n convertSchema(v, options),\n );\n\n // If nullable in OpenAPI 3.1, ensure null type is present\n if (isNullable) {\n const hasNull = variants.some(\n (v: SchemaObject | ReferenceObject) =>\n 'type' in v &&\n (v.type === 'null' || (Array.isArray(v.type) && v.type.includes('null'))),\n );\n if (!hasNull) {\n variants.push({ type: 'null' });\n }\n return { anyOf: variants };\n }\n\n return { anyOf: variants };\n}\n\n/**\n * Main conversion function: converts any InferredSchema to an OpenAPI SchemaObject or ReferenceObject.\n */\nexport function convertSchema(\n schema: InferredSchema,\n options: SchemaConverterOptions = {},\n): SchemaObject | ReferenceObject {\n if (!schema) {\n return {};\n }\n\n switch (schema.type) {\n case 'string':\n case 'number':\n case 'integer':\n case 'boolean':\n case 'null':\n case 'any':\n return convertPrimitiveSchema(schema, options);\n\n case 'object':\n return convertObjectSchema(schema, options);\n\n case 'array':\n return convertArraySchema(schema, options);\n\n case 'union':\n return convertUnionSchema(schema, options);\n\n default:\n return {};\n }\n}\n","import type { EndpointSchemaAggregate, InferredRequestDefinition } from '@luxray/shared';\nimport type {\n MediaTypeObject,\n OpenApiVersion,\n RequestBodyObject,\n} from '../domain/openapi-types.js';\nimport {\n convertSchema,\n type SchemaRefResolver,\n} from './schema-converter.js';\n\nexport interface RequestConverterOptions {\n readonly method?: string;\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\n/**\n * Standardizes raw media types to clean content type keys (e.g. \"application/json; charset=utf-8\" -> \"application/json\").\n */\nexport function normalizeMediaType(rawType?: string): string {\n if (!rawType) return 'application/json';\n const clean = (rawType.split(';')[0] ?? '').trim().toLowerCase();\n return clean || 'application/json';\n}\n\n/**\n * Converts InferredRequestDefinition or EndpointSchemaAggregate requests to OpenAPI RequestBodyObject.\n * Employs defensible contract semantics: request body is only marked required when mutation method,\n * zero empty body observations, and high confidence evidence exist.\n */\nexport function convertRequestBody(\n schemaAggregate: EndpointSchemaAggregate | undefined,\n options: RequestConverterOptions = {},\n): RequestBodyObject | undefined {\n if (!schemaAggregate) return undefined;\n\n const content: Record<string, MediaTypeObject> = {};\n let hasContent = false;\n\n // Primary request or multiple requests by media type\n const requests: InferredRequestDefinition[] = [];\n if (schemaAggregate.requests) {\n requests.push(...Object.values(schemaAggregate.requests));\n } else if (schemaAggregate.request) {\n requests.push(schemaAggregate.request);\n }\n\n if (requests.length === 0) return undefined;\n\n for (const reqDef of requests) {\n if (!reqDef || !reqDef.schema) continue;\n\n const mediaType = normalizeMediaType(reqDef.mediaType || reqDef.contentType);\n const schema = convertSchema(reqDef.schema, {\n openApiVersion: options.openApiVersion,\n includeExamples: options.includeExamples,\n refResolver: options.refResolver,\n });\n\n const mediaTypeObj: MediaTypeObject = {\n schema,\n };\n\n if (\n options.includeExtensions !== false &&\n reqDef.provenance?.confidence\n ) {\n (mediaTypeObj as Record<string, unknown>)['x-luxray-confidence'] =\n reqDef.provenance.confidence.score;\n (mediaTypeObj as Record<string, unknown>)['x-luxray-observations'] =\n reqDef.provenance.totalObservations;\n }\n\n content[mediaType] = mediaTypeObj;\n hasContent = true;\n }\n\n if (!hasContent) return undefined;\n\n // Defensible contract requiredness evaluation\n const upperMethod = (options.method || 'POST').toUpperCase();\n const isMutation = ['POST', 'PUT', 'PATCH'].includes(upperMethod);\n const totalObs = requests.reduce((acc, r) => acc + (r.provenance?.totalObservations ?? 0), 0);\n const emptyObs = requests.reduce((acc, r) => acc + (r.provenance?.emptyBodyObservations ?? 0), 0);\n const minConf = requests.length > 0\n ? Math.min(...requests.map((r) => r.provenance?.confidence?.score ?? 0))\n : 0;\n\n const isDefensiblyRequired = isMutation && totalObs >= 3 && emptyObs === 0 && minConf >= 0.75;\n\n const reqBodyObj: RequestBodyObject = {\n description: 'Request payload',\n required: isDefensiblyRequired,\n content,\n };\n\n if (options.includeExtensions !== false) {\n const ext = reqBodyObj as unknown as Record<string, unknown>;\n ext['x-luxray-empty-body-observations'] = emptyObs;\n ext['x-luxray-observed-presence'] = emptyObs === 0 ? 'always' : 'optional';\n }\n\n return reqBodyObj;\n}\n","import type {\n EndpointAggregate,\n EndpointSchemaAggregate,\n InferredResponseDefinition,\n} from '@luxray/shared';\nimport type {\n MediaTypeObject,\n OpenApiVersion,\n ResponseObject,\n ResponsesObject,\n} from '../domain/openapi-types.js';\nimport {\n convertSchema,\n type SchemaRefResolver,\n} from './schema-converter.js';\nimport { normalizeMediaType } from './request-converter.js';\n\nexport interface ResponseConverterOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExtensions?: boolean;\n readonly includeExamples?: boolean;\n readonly refResolver?: SchemaRefResolver;\n}\n\nconst HTTP_STATUS_DESCRIPTIONS: Record<number, string> = {\n 200: 'OK - Successful response',\n 201: 'Created - Resource created successfully',\n 202: 'Accepted - Request accepted for processing',\n 204: 'No Content - Request succeeded with no response body',\n 301: 'Moved Permanently',\n 302: 'Found',\n 304: 'Not Modified',\n 400: 'Bad Request - Client error in request parameters or body',\n 401: 'Unauthorized - Authentication credentials required or invalid',\n 403: 'Forbidden - Insufficient permissions to access resource',\n 404: 'Not Found - The requested resource does not exist',\n 405: 'Method Not Allowed',\n 409: 'Conflict - Request conflict with current state of resource',\n 422: 'Unprocessable Entity - Semantic errors in request payload',\n 429: 'Too Many Requests - Rate limit exceeded',\n 500: 'Internal Server Error',\n 502: 'Bad Gateway',\n 503: 'Service Unavailable',\n 504: 'Gateway Timeout',\n};\n\n/**\n * Returns a human-friendly description for an HTTP status code.\n */\nexport function getStatusDescription(statusCode: number): string {\n return HTTP_STATUS_DESCRIPTIONS[statusCode] ?? `HTTP ${statusCode} response`;\n}\n\n/**\n * Converts InferredResponseDefinitions and EndpointAggregate status codes into OpenAPI ResponsesObject.\n */\nexport function convertResponses(\n schemaAggregate: EndpointSchemaAggregate | undefined,\n endpointAggregate: EndpointAggregate | undefined,\n options: ResponseConverterOptions = {},\n): ResponsesObject {\n const responses: ResponsesObject = {};\n\n // First, extract schemas from EndpointSchemaAggregate if available\n const responseMap = schemaAggregate?.responses ?? {};\n const statusCodes = new Set<number>();\n\n for (const statusCodeStr of Object.keys(responseMap)) {\n const code = Number(statusCodeStr);\n if (!isNaN(code)) statusCodes.add(code);\n }\n\n // Also include status codes observed in EndpointAggregate\n if (endpointAggregate?.statusCodes) {\n for (const codeStr of Object.keys(endpointAggregate.statusCodes)) {\n const code = Number(codeStr);\n if (!isNaN(code)) statusCodes.add(code);\n }\n }\n\n // Default fallback if no status codes known\n if (statusCodes.size === 0) {\n statusCodes.add(200);\n }\n\n const sortedCodes = Array.from(statusCodes).sort((a, b) => a - b);\n\n for (const statusCode of sortedCodes) {\n const codeStr = statusCode.toString() as `${1 | 2 | 3 | 4 | 5}${number}${number}`;\n const mediaTypeDefinitions = (responseMap as Record<number, Record<string, InferredResponseDefinition>>)[statusCode] ?? {};\n const mediaTypeEntries = Object.entries(mediaTypeDefinitions) as [string, InferredResponseDefinition][];\n\n const description = getStatusDescription(statusCode);\n\n // 204 No Content has no body\n if (statusCode === 204) {\n responses[codeStr] = {\n description,\n };\n continue;\n }\n\n if (mediaTypeEntries.length === 0) {\n // Empty response or un-inferred schema\n responses[codeStr] = {\n description,\n };\n continue;\n }\n\n const content: Record<string, MediaTypeObject> = {};\n\n for (const [rawType, def] of mediaTypeEntries) {\n const mediaType = normalizeMediaType(rawType || def.mediaType || def.contentType);\n const schema = convertSchema(def.schema, {\n openApiVersion: options.openApiVersion,\n includeExamples: options.includeExamples,\n refResolver: options.refResolver,\n });\n\n const mediaTypeObj: MediaTypeObject = {\n schema,\n };\n\n if (\n options.includeExtensions !== false &&\n def.provenance?.confidence\n ) {\n (mediaTypeObj as Record<string, unknown>)['x-luxray-confidence'] =\n def.provenance.confidence.score;\n (mediaTypeObj as Record<string, unknown>)['x-luxray-observations'] =\n def.provenance.totalObservations;\n }\n\n content[mediaType] = mediaTypeObj;\n }\n\n const responseObj: ResponseObject = {\n description,\n content,\n };\n\n responses[codeStr] = responseObj;\n }\n\n return responses;\n}\n","import type { ApiRelationship, InferredSchema } from '@luxray/shared';\nimport type { LinkObject, ParameterObject } from '../domain/openapi-types.js';\n\nexport interface LinkConverterOptions {\n /** Minimum confidence score required to generate Link Object (default: 0.5) */\n readonly minConfidence?: number;\n /** Whether only CONFIRMED relationships can generate Link Objects (default: false) */\n readonly onlyConfirmed?: boolean;\n /** Whether to output Luxray analytical extensions (x-luxray-*) (default: true) */\n readonly includeExtensions?: boolean;\n}\n\nexport interface LinkValidationContext {\n readonly relationship: ApiRelationship;\n readonly targetOperationId?: string;\n readonly targetParameters?: readonly ParameterObject[];\n readonly targetParamName?: string;\n readonly sourceResponseSchema?: InferredSchema;\n readonly options?: LinkConverterOptions;\n}\n\nexport interface ConvertedLinkResult {\n readonly linkName: string;\n readonly link: LinkObject;\n}\n\n/**\n * Builds a deterministic, valid link name for OpenAPI links map.\n */\nexport function generateLinkName(\n targetOperationId: string,\n sourceProperty?: string,\n): string {\n const cleanOp = targetOperationId.replace(/[^a-zA-Z0-9]/g, '');\n const capitalizedOp = cleanOp.charAt(0).toUpperCase() + cleanOp.slice(1);\n if (sourceProperty) {\n const cleanProp = sourceProperty.replace(/[^a-zA-Z0-9]/g, '');\n const capitalizedProp = cleanProp.charAt(0).toUpperCase() + cleanProp.slice(1);\n return `${capitalizedOp}By${capitalizedProp}`;\n }\n return capitalizedOp;\n}\n\n/**\n * Validates and converts an ApiRelationship into an OpenAPI LinkObject.\n * Supports both context object signature and legacy positional parameters.\n */\nexport function convertRelationshipToLink(\n contextOrRel: LinkValidationContext | ApiRelationship,\n targetOperationId?: string,\n targetParamName?: string,\n options?: LinkConverterOptions,\n): ConvertedLinkResult | undefined {\n let ctx: LinkValidationContext;\n\n if ('relationship' in contextOrRel) {\n ctx = contextOrRel;\n } else {\n ctx = {\n relationship: contextOrRel,\n targetOperationId,\n targetParamName,\n options,\n };\n }\n\n const { relationship, sourceResponseSchema } = ctx;\n const targetOpId = ctx.targetOperationId;\n const opts = ctx.options ?? {};\n\n // 1. Target operation must exist\n if (!targetOpId) {\n return undefined;\n }\n\n // 2. Reject explicitly rejected relationships\n if (relationship.status === 'REJECTED') {\n return undefined;\n }\n\n // 3. Check confirmation constraint if enabled\n if (opts.onlyConfirmed && relationship.status !== 'CONFIRMED') {\n return undefined;\n }\n\n // 4. Check confidence threshold and evidence presence\n const minConfidence = opts.minConfidence ?? 0.5;\n if (!relationship.confidence || relationship.confidence.score < minConfidence) {\n return undefined;\n }\n\n const hasEvidence =\n (relationship.evidence && relationship.evidence.length > 0) ||\n (relationship.confidence?.reasons && relationship.confidence.reasons.length > 0);\n\n if (!hasEvidence) {\n return undefined;\n }\n\n // 5. Collection Safety: Collection responses (root array) must NOT generate misleading\n // links to arbitrary collection elements ($response.body#/items/0/id)\n if (sourceResponseSchema && sourceResponseSchema.type === 'array') {\n return undefined;\n }\n\n const sourceProp = relationship.sourceProperty;\n\n // 6. Runtime expression resolution: If source schema is known, verify sourceProperty actually exists\n if (sourceResponseSchema && sourceResponseSchema.type === 'object' && sourceProp) {\n const fields = sourceResponseSchema.fields ?? {};\n if (!fields[sourceProp]) {\n return undefined;\n }\n }\n\n // 7. Target parameter matching: Target parameter must actually exist in the target operation\n let resolvedTargetParam = ctx.targetParamName || relationship.targetProperty;\n\n if (ctx.targetParameters && ctx.targetParameters.length > 0) {\n const paramNames = ctx.targetParameters.map((p) => p.name);\n\n if (resolvedTargetParam && !paramNames.includes(resolvedTargetParam)) {\n const matched = paramNames.find(\n (p) =>\n p === sourceProp ||\n p === 'id' ||\n (sourceProp && p.toLowerCase().includes(sourceProp.toLowerCase())),\n );\n if (matched) {\n resolvedTargetParam = matched;\n } else {\n return undefined;\n }\n } else if (!resolvedTargetParam) {\n const pathParam = ctx.targetParameters.find((p) => p.in === 'path');\n if (pathParam) {\n resolvedTargetParam = pathParam.name;\n }\n }\n }\n\n const parameters: Record<string, string> = {};\n if (sourceProp && resolvedTargetParam) {\n parameters[resolvedTargetParam] = `$response.body#/${sourceProp}`;\n }\n\n const link: LinkObject = {\n operationId: targetOpId,\n description: `Discovered API relationship (${relationship.type}) with ${Math.round(\n (relationship.confidence?.score ?? 0) * 100,\n )}% confidence`,\n };\n\n if (Object.keys(parameters).length > 0) {\n link.parameters = parameters;\n }\n\n if (opts.includeExtensions !== false) {\n const extObj = link as Record<string, unknown>;\n extObj['x-luxray-relationship-id'] = relationship.id;\n extObj['x-luxray-type'] = relationship.type;\n if (relationship.topology) extObj['x-luxray-topology'] = relationship.topology;\n if (relationship.cardinality) extObj['x-luxray-cardinality'] = relationship.cardinality;\n if (relationship.confidence) extObj['x-luxray-confidence'] = relationship.confidence.score;\n }\n\n const linkName = generateLinkName(targetOpId, sourceProp);\n\n return { linkName, link };\n}\n\n/**\n * Groups discovered relationships by source endpoint ID.\n */\nexport function groupRelationshipsBySource(\n relationships: readonly ApiRelationship[] = [],\n): Map<string, ApiRelationship[]> {\n const map = new Map<string, ApiRelationship[]>();\n for (const rel of relationships) {\n if (!rel.sourceEndpointId) continue;\n const list = map.get(rel.sourceEndpointId) ?? [];\n list.push(rel);\n map.set(rel.sourceEndpointId, list);\n }\n return map;\n}\n","import type { InferredObjectSchema, InferredSchema } from '@luxray/shared';\nimport type {\n ComponentsObject,\n OpenApiVersion,\n SchemaObject,\n} from '../domain/openapi-types.js';\nimport {\n convertObjectSchemaDirect,\n type SchemaRefResolver,\n} from '../converters/schema-converter.js';\n\nexport interface ComponentRegistryOptions {\n readonly openApiVersion?: OpenApiVersion;\n readonly includeExamples?: boolean;\n}\n\n/**\n * Computes a deterministic structural signature for an InferredSchema to detect identical shapes.\n * Handles recursive and mutually recursive schemas gracefully via visited set.\n */\nexport function computeSchemaFingerprint(\n schema: InferredSchema,\n visited: Set<InferredSchema> = new Set(),\n): string {\n if (!schema) return 'empty';\n if (visited.has(schema)) return '[circular]';\n\n visited.add(schema);\n\n try {\n if (schema.type === 'object') {\n const fieldParts: string[] = [];\n const sortedKeys = Object.keys(schema.fields ?? {}).sort();\n for (const key of sortedKeys) {\n const field = schema.fields[key];\n if (!field) continue;\n const fieldSig = computeSchemaFingerprint(field.schema, visited);\n const opt = field.isOptional ? 'opt' : 'req';\n const nll = field.isNullable ? 'null' : 'notnull';\n fieldParts.push(`${key}:${opt}:${nll}:${fieldSig}`);\n }\n return `object{${fieldParts.join(';')}}`;\n }\n\n if (schema.type === 'array') {\n return `array[${computeSchemaFingerprint(schema.itemSchema, visited)}]`;\n }\n\n if (schema.type === 'union') {\n const varSigs = (schema.variants ?? [])\n .map((v) => computeSchemaFingerprint(v, visited))\n .sort()\n .join('|');\n return `union(${varSigs})`;\n }\n\n return `primitive(${schema.type}:${Boolean(schema.isNullable)})`;\n } finally {\n visited.delete(schema);\n }\n}\n\n/**\n * Manages OpenAPI components.schemas extraction, deduplication, and reference creation.\n * Preserves semantic distinction across entities (e.g. User vs Role with same shape).\n */\nexport class ComponentRegistry implements SchemaRefResolver {\n private readonly schemasByName = new Map<string, SchemaObject>();\n private readonly refBySchema = new Map<InferredSchema, string>();\n private readonly nameByEntityAndFingerprint = new Map<string, string>();\n private readonly options: ComponentRegistryOptions;\n\n constructor(options: ComponentRegistryOptions = {}) {\n this.options = options;\n }\n\n /**\n * Returns a reference path '#/components/schemas/{name}' if this schema has been registered as a component.\n */\n public getRefForSchema(schema: InferredSchema): string | undefined {\n if (!schema || schema.type !== 'object') {\n return undefined;\n }\n\n // Direct reference match\n const directRef = this.refBySchema.get(schema);\n if (directRef) {\n return directRef;\n }\n\n return undefined;\n }\n\n /**\n * Registers an object schema under a suggested base name.\n * Preserves semantic identity: only schemas with both the same suggested entity name\n * AND matching structural fingerprint share a component definition.\n */\n public registerComponent(\n suggestedName: string,\n schema: InferredObjectSchema,\n ): string {\n const fingerprint = computeSchemaFingerprint(schema);\n const entityKey = `${suggestedName}::${fingerprint}`;\n\n const existingName = this.nameByEntityAndFingerprint.get(entityKey);\n if (existingName) {\n this.refBySchema.set(schema, `#/components/schemas/${existingName}`);\n return existingName;\n }\n\n // Determine unique name\n let finalName = suggestedName.replace(/[^a-zA-Z0-9_]/g, '');\n if (!finalName) finalName = 'Schema';\n\n let counter = 1;\n let candidateName = finalName;\n while (this.schemasByName.has(candidateName)) {\n counter++;\n candidateName = `${finalName}_${counter}`;\n }\n finalName = candidateName;\n\n // Record mappings before converting so child recursive fields can find it\n this.nameByEntityAndFingerprint.set(entityKey, finalName);\n this.refBySchema.set(schema, `#/components/schemas/${finalName}`);\n\n // Convert schema properties directly (nested references resolve via this.getRefForSchema)\n const converted = convertObjectSchemaDirect(schema, {\n openApiVersion: this.options.openApiVersion,\n includeExamples: this.options.includeExamples,\n refResolver: this,\n });\n\n this.schemasByName.set(finalName, converted);\n\n return finalName;\n }\n\n /**\n * Returns all registered schema components as a record.\n */\n public getSchemas(): Record<string, SchemaObject> {\n const result: Record<string, SchemaObject> = {};\n for (const [name, schema] of this.schemasByName.entries()) {\n result[name] = schema;\n }\n return result;\n }\n\n /**\n * Total number of extracted schema components.\n */\n public get count(): number {\n return this.schemasByName.size;\n }\n\n /**\n * Builds the ComponentsObject containing schemas.\n */\n public toComponentsObject(): ComponentsObject | undefined {\n if (this.schemasByName.size === 0) {\n return undefined;\n }\n return {\n schemas: this.getSchemas(),\n };\n }\n}\n","import type { OpenApiDocument } from '../domain/openapi-types.js';\n\n/**\n * Serializes an OpenAPI document to formatted JSON.\n */\nexport function serializeToJson(doc: OpenApiDocument, indent = 2): string {\n return JSON.stringify(doc, null, indent);\n}\n\n/**\n * Escapes and quotes a YAML string scalar when necessary.\n */\nfunction formatYamlString(str: string): string {\n if (str === '') return \"''\";\n\n // Check if string needs quotes in YAML plain scalar\n const needsQuotes =\n /(?::\\s|:\\t|:$)/.test(str) ||\n /\\s#/.test(str) ||\n /[{}[\\]&*?|<>=!%@`\\n\\r\\t]/.test(str) ||\n str.startsWith(' ') ||\n str.endsWith(' ') ||\n str.startsWith('- ') ||\n str.startsWith('? ') ||\n str.startsWith(': ') ||\n str.startsWith('#') ||\n /^(true|false|null|yes|no|on|off)$/i.test(str) ||\n /^-?\\d+(?:\\.\\d+)?(?:[eE][+-]?\\d+)?$/.test(str) ||\n /^0[xob]/i.test(str);\n\n if (!needsQuotes) {\n return str;\n }\n\n // Handle multiline strings\n if (str.includes('\\n')) {\n // If double quote escaping is safe:\n return JSON.stringify(str);\n }\n\n // Use double quotes and escape backslashes and double quotes\n return JSON.stringify(str);\n}\n\n/**\n * Recursively formats a JavaScript value as YAML.\n */\nfunction dumpYamlValue(value: unknown, depth: number, indentSize: number): string {\n const currentIndent = ' '.repeat(depth * indentSize);\n\n if (value === null || value === undefined) {\n return 'null';\n }\n\n if (typeof value === 'boolean') {\n return value ? 'true' : 'false';\n }\n\n if (typeof value === 'number') {\n return Number.isFinite(value) ? value.toString() : 'null';\n }\n\n if (typeof value === 'string') {\n return formatYamlString(value);\n }\n\n if (Array.isArray(value)) {\n if (value.length === 0) {\n return '[]';\n }\n\n const lines: string[] = [];\n for (const item of value) {\n if (item === null || item === undefined || typeof item !== 'object') {\n lines.push(`${currentIndent}- ${dumpYamlValue(item, depth + 1, indentSize)}`);\n } else if (Array.isArray(item)) {\n lines.push(`${currentIndent}-`);\n lines.push(dumpYamlValue(item, depth + 1, indentSize));\n } else {\n // Object item in array\n const objLines = dumpYamlObject(item as Record<string, unknown>, depth + 1, indentSize, true);\n lines.push(objLines);\n }\n }\n return lines.join('\\n');\n }\n\n if (typeof value === 'object') {\n const obj = value as Record<string, unknown>;\n const keys = Object.keys(obj);\n if (keys.length === 0) {\n return '{}';\n }\n return dumpYamlObject(obj, depth, indentSize, false);\n }\n\n return formatYamlString(String(value));\n}\n\n/**\n * Dumps an object to YAML key-value lines.\n */\nfunction dumpYamlObject(\n obj: Record<string, unknown>,\n depth: number,\n indentSize: number,\n firstLinePrefixedDash: boolean,\n): string {\n const lines: string[] = [];\n const keys = Object.keys(obj);\n const currentIndent = ' '.repeat(depth * indentSize);\n const dashIndent = ' '.repeat(Math.max(0, (depth - 1) * indentSize));\n\n let isFirst = firstLinePrefixedDash;\n\n for (const key of keys) {\n const val = obj[key];\n const formattedKey = /^[a-zA-Z0-9_.-]+$/.test(key) ? key : formatYamlString(key);\n const prefix = isFirst ? `${dashIndent}- ` : currentIndent;\n isFirst = false;\n\n if (val === undefined) {\n continue;\n }\n\n if (val === null || typeof val !== 'object') {\n lines.push(`${prefix}${formattedKey}: ${dumpYamlValue(val, depth + 1, indentSize)}`);\n } else if (Array.isArray(val)) {\n if (val.length === 0) {\n lines.push(`${prefix}${formattedKey}: []`);\n } else {\n lines.push(`${prefix}${formattedKey}:`);\n lines.push(dumpYamlValue(val, depth + 1, indentSize));\n }\n } else {\n // Nested object\n const nestedKeys = Object.keys(val as Record<string, unknown>);\n if (nestedKeys.length === 0) {\n lines.push(`${prefix}${formattedKey}: {}`);\n } else {\n lines.push(`${prefix}${formattedKey}:`);\n lines.push(dumpYamlValue(val, depth + 1, indentSize));\n }\n }\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Standard top-level OpenAPI keys order for clean, conventional documents.\n */\nconst TOP_LEVEL_ORDER: (keyof OpenApiDocument)[] = [\n 'openapi',\n 'info',\n 'jsonSchemaDialect',\n 'servers',\n 'tags',\n 'paths',\n 'components',\n 'security',\n 'externalDocs',\n];\n\n/**\n * Serializes an OpenAPI document to clean YAML without external runtime dependencies.\n */\nexport function serializeToYaml(doc: OpenApiDocument, indent = 2): string {\n // Sort top-level keys canonically\n const orderedDoc: Record<string, unknown> = {};\n\n const docRecord = doc as unknown as Record<string, unknown>;\n\n for (const key of TOP_LEVEL_ORDER) {\n if (key in doc && docRecord[key] !== undefined) {\n orderedDoc[key] = docRecord[key];\n }\n }\n\n // Add any remaining keys (e.g. x-luxray-* extensions)\n for (const [key, value] of Object.entries(doc)) {\n if (!(key in orderedDoc) && value !== undefined) {\n orderedDoc[key] = value;\n }\n }\n\n return dumpYamlObject(orderedDoc, 0, indent, false) + '\\n';\n}\n","import type {\n ApiRelationship,\n EndpointAggregate,\n EndpointSchemaAggregate,\n InferredArraySchema,\n InferredObjectSchema,\n InferredResponseDefinition,\n} from '@luxray/shared';\nimport { singularize } from '@luxray/normalization';\nimport { extractPathHierarchy } from '@luxray/relationship-discovery';\nimport type {\n ComponentsObject,\n InfoObject,\n OpenApiDocument,\n OpenApiVersion,\n OperationObject,\n ParameterObject,\n PathItemObject,\n PathsObject,\n ServerObject,\n TagObject,\n} from '../domain/openapi-types.js';\nimport type {\n GenerationInput,\n GenerationMetrics,\n OpenApiGeneratorOptions,\n} from '../domain/generator-types.js';\nimport {\n deriveOperationSummary,\n deriveResourceTag,\n generateOperationId,\n toOpenApiPath,\n} from '../converters/path-converter.js';\nimport { convertEndpointParameters } from '../converters/parameter-converter.js';\nimport { convertRequestBody } from '../converters/request-converter.js';\nimport { convertResponses } from '../converters/response-converter.js';\nimport {\n convertRelationshipToLink,\n groupRelationshipsBySource,\n} from '../converters/link-converter.js';\nimport { ComponentRegistry } from '../components/component-registry.js';\nimport { serializeToJson, serializeToYaml } from '../serializers/serializer.js';\n\n/**\n * Capitalizes string.\n */\nfunction capitalize(str: string): string {\n if (!str) return '';\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n/**\n * Derives a clean PascalCase component schema name for an entity.\n */\nfunction deriveEntityComponentName(\n pathTemplate: string,\n method: string,\n isRequest = false,\n): string {\n const hierarchy = extractPathHierarchy(pathTemplate);\n const resource = hierarchy.nestedResource?.name ?? hierarchy.primaryResource?.name ?? 'Entity';\n const singular = capitalize(singularize(resource));\n\n if (isRequest) {\n const action = method.toUpperCase() === 'POST' ? 'Create' : 'Update';\n return `${action}${singular}Request`;\n }\n\n return singular;\n}\n\n/**\n * Core engine for generating OpenAPI 3.1 and 3.0 specification documents.\n */\nexport class OpenApiGenerator {\n private readonly options: OpenApiGeneratorOptions;\n private lastMetrics?: GenerationMetrics;\n\n constructor(options: OpenApiGeneratorOptions = {}) {\n this.options = {\n openApiVersion: options.openApiVersion ?? '3.1.0',\n includeExtensions: options.includeExtensions ?? true,\n generateLinks: options.generateLinks ?? true,\n minRelationshipConfidence: options.minRelationshipConfidence ?? 0.5,\n extractComponents: options.extractComponents ?? true,\n outputFormat: options.outputFormat ?? 'object',\n indent: options.indent ?? 2,\n ...options,\n };\n }\n\n /**\n * Generates a complete OpenAPI document object from endpoint and schema aggregates.\n */\n public generate(input: GenerationInput): OpenApiDocument {\n const startTime = Date.now();\n const version: OpenApiVersion = this.options.openApiVersion ?? '3.1.0';\n const isOpenApi31 = version !== '3.0.3';\n\n // Index schemas by endpointId\n const schemaMap = new Map<string, EndpointSchemaAggregate>();\n for (const schema of input.schemas ?? []) {\n schemaMap.set(schema.endpointId, schema);\n }\n\n // Index endpoint aggregates by identity id\n const endpointMap = new Map<string, EndpointAggregate>();\n for (const ep of input.endpoints) {\n endpointMap.set(ep.identity.id, ep);\n }\n\n // Set up component registry\n const componentRegistry = new ComponentRegistry({\n openApiVersion: version,\n includeExamples: true,\n });\n\n // Step 1: Pre-register components if enabled\n if (this.options.extractComponents !== false) {\n this.preRegisterComponents(input.endpoints, schemaMap, componentRegistry);\n }\n\n // Step 2: Build parameters and guaranteed-unique operation ID lookup\n const operationIdByEndpointId = new Map<string, string>();\n const parametersByEndpointId = new Map<string, ParameterObject[]>();\n const usedOperationIds = new Set<string>();\n\n for (const ep of input.endpoints) {\n const method = (ep.identity.method || 'GET').toUpperCase();\n const pathTemplate = ep.identity.pathname || '/';\n const baseOpId = this.options.operationIdGenerator\n ? this.options.operationIdGenerator(method, pathTemplate)\n : generateOperationId(method, pathTemplate);\n\n // Enforce strict OpenAPI requirement: operationId MUST be unique among all operations\n let opId = baseOpId;\n let counter = 1;\n while (usedOperationIds.has(opId)) {\n counter++;\n opId = `${baseOpId}_${counter}`;\n }\n usedOperationIds.add(opId);\n operationIdByEndpointId.set(ep.identity.id, opId);\n\n const params = convertEndpointParameters(ep, {\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n });\n parametersByEndpointId.set(ep.identity.id, params);\n }\n\n // Step 3: Group relationships by source\n const relationshipsBySource = this.options.generateLinks !== false\n ? groupRelationshipsBySource(input.relationships ?? [])\n : new Map<string, ApiRelationship[]>();\n\n // Step 4: Group endpoints by OpenAPI path\n const endpointsByPath = new Map<string, EndpointAggregate[]>();\n for (const ep of input.endpoints) {\n const openApiPath = toOpenApiPath(ep.identity.pathname || '/');\n const list = endpointsByPath.get(openApiPath) ?? [];\n list.push(ep);\n endpointsByPath.set(openApiPath, list);\n }\n\n // Step 5: Build PathsObject\n const paths: PathsObject = {};\n const tagsSet = new Set<string>();\n let totalOperations = 0;\n let totalParameters = 0;\n let totalLinks = 0;\n\n const sortedPaths = Array.from(endpointsByPath.keys()).sort();\n\n for (const pathKey of sortedPaths) {\n const endpoints = endpointsByPath.get(pathKey)!;\n const pathItem: PathItemObject = {};\n\n for (const ep of endpoints) {\n const method = (ep.identity.method || 'GET').toLowerCase();\n const operationId = operationIdByEndpointId.get(ep.identity.id)!;\n const schemaAggregate = schemaMap.get(ep.identity.id);\n\n const tag = deriveResourceTag(ep.identity.pathname || '/');\n tagsSet.add(tag);\n\n const summary = deriveOperationSummary(method, ep.identity.pathname || '/');\n const parameters = parametersByEndpointId.get(ep.identity.id) ?? [];\n totalParameters += parameters.length;\n\n const requestBody = convertRequestBody(schemaAggregate, {\n method,\n openApiVersion: version,\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n refResolver: this.options.extractComponents !== false ? componentRegistry : undefined,\n });\n\n const responses = convertResponses(schemaAggregate, ep, {\n openApiVersion: version,\n includeExtensions: this.options.includeExtensions,\n includeExamples: true,\n refResolver: this.options.extractComponents !== false ? componentRegistry : undefined,\n });\n\n // Discovered relationships handling\n const unsupportedRelationships: Record<string, unknown>[] = [];\n\n if (this.options.generateLinks !== false) {\n const outgoingRels = relationshipsBySource.get(ep.identity.id) ?? [];\n\n // Find source response schema for link expression verification\n const successDef =\n schemaAggregate?.responses?.[200]?.['application/json'] ??\n schemaAggregate?.responses?.[201]?.['application/json'] ??\n (schemaAggregate?.responses?.[200] ? Object.values(schemaAggregate.responses[200])[0] : undefined);\n const sourceResponseSchema = successDef?.schema;\n\n for (const rel of outgoingRels) {\n const targetOpId = operationIdByEndpointId.get(rel.targetEndpointId);\n const targetParams = parametersByEndpointId.get(rel.targetEndpointId);\n\n const linkResult = convertRelationshipToLink({\n relationship: rel,\n targetOperationId: targetOpId,\n targetParameters: targetParams,\n sourceResponseSchema,\n options: {\n minConfidence: this.options.minRelationshipConfidence,\n includeExtensions: this.options.includeExtensions,\n },\n });\n\n if (linkResult) {\n const successResponse = responses['200'] ?? responses['201'];\n if (successResponse && !('$ref' in successResponse)) {\n successResponse.links = successResponse.links ?? {};\n successResponse.links[linkResult.linkName] = linkResult.link;\n totalLinks++;\n }\n } else {\n // Retain unsupported relationships in extensions rather than discarding\n unsupportedRelationships.push({\n id: rel.id,\n type: rel.type,\n targetEndpointId: rel.targetEndpointId,\n confidence: rel.confidence?.score,\n status: rel.status,\n sourceProperty: rel.sourceProperty,\n targetProperty: rel.targetProperty,\n });\n }\n }\n }\n\n const operation: OperationObject = {\n tags: [tag],\n summary,\n operationId,\n responses,\n };\n\n if (parameters.length > 0) {\n operation.parameters = parameters;\n }\n\n if (requestBody) {\n operation.requestBody = requestBody;\n }\n\n if (this.options.includeExtensions !== false) {\n operation['x-luxray-endpoint-id'] = ep.identity.id;\n operation['x-luxray-observations'] = ep.observationCount;\n operation['x-luxray-first-observed'] = ep.firstObservedAt;\n operation['x-luxray-last-observed'] = ep.lastObservedAt;\n if (ep.latency?.avgMs !== undefined) {\n operation['x-luxray-latency-avg-ms'] = Math.round(ep.latency.avgMs * 100) / 100;\n }\n if (unsupportedRelationships.length > 0) {\n operation['x-luxray-relationships'] = unsupportedRelationships;\n }\n }\n\n (pathItem as Record<string, unknown>)[method] = operation;\n totalOperations++;\n }\n\n paths[pathKey] = pathItem;\n }\n\n // Step 6: Derive servers if not explicitly provided\n let servers: ServerObject[] | undefined = this.options.servers;\n if (!servers || servers.length === 0) {\n const origins = new Set<string>();\n for (const ep of input.endpoints) {\n if (ep.identity.origin && ep.identity.origin.startsWith('http')) {\n origins.add(ep.identity.origin);\n }\n }\n if (origins.size > 0) {\n servers = Array.from(origins).map((origin) => ({\n url: origin,\n description: 'Inferred API server origin',\n }));\n }\n }\n\n // Step 7: Build document info\n const info: InfoObject = {\n title: this.options.info?.title ?? 'Luxray Discovered API',\n version: this.options.info?.version ?? '1.0.0',\n description:\n this.options.info?.description ??\n 'Automated OpenAPI specification reverse-engineered by Luxray Traffic Intelligence.',\n ...this.options.info,\n };\n\n // Step 8: Build tags\n const tags: TagObject[] = Array.from(tagsSet)\n .sort()\n .map((tag) => ({ name: tag }));\n\n // Step 9: Build components\n let components: ComponentsObject | undefined;\n if (this.options.extractComponents !== false) {\n components = componentRegistry.toComponentsObject();\n }\n\n // Construct final document\n const document: OpenApiDocument = {\n openapi: version,\n info,\n paths,\n };\n\n if (isOpenApi31) {\n document.jsonSchemaDialect = 'https://json-schema.org/draft/2020-12/schema';\n }\n\n if (servers && servers.length > 0) {\n document.servers = servers;\n }\n\n if (tags.length > 0) {\n document.tags = tags;\n }\n\n if (components) {\n document.components = components;\n }\n\n if (this.options.includeExtensions !== false) {\n document['x-luxray-generated-at'] = Date.now();\n document['x-luxray-generator-version'] = '0.1.0';\n }\n\n const duration = Date.now() - startTime;\n this.lastMetrics = {\n totalPaths: Object.keys(paths).length,\n totalOperations,\n totalParameters,\n totalSchemas: schemaMap.size,\n totalComponents: componentRegistry.count,\n totalLinks,\n generationTimeMs: duration,\n };\n\n return document;\n }\n\n /**\n * Generates document serialized as formatted JSON string.\n */\n public generateJson(input: GenerationInput, indent?: number): string {\n const doc = this.generate(input);\n return serializeToJson(doc, indent ?? this.options.indent ?? 2);\n }\n\n /**\n * Generates document serialized as clean YAML string.\n */\n public generateYaml(input: GenerationInput, indent?: number): string {\n const doc = this.generate(input);\n return serializeToYaml(doc, indent ?? this.options.indent ?? 2);\n }\n\n /**\n * Returns generation metrics from the most recent run.\n */\n public getMetrics(): GenerationMetrics | undefined {\n return this.lastMetrics;\n }\n\n /**\n * Inspects endpoints and schemas to register entity schemas in the component registry.\n */\n private preRegisterComponents(\n endpoints: readonly EndpointAggregate[],\n schemaMap: Map<string, EndpointSchemaAggregate>,\n registry: ComponentRegistry,\n ): void {\n for (const ep of endpoints) {\n const schemaAggregate = schemaMap.get(ep.identity.id);\n if (!schemaAggregate) continue;\n\n const path = ep.identity.pathname || '/';\n const method = (ep.identity.method || 'GET').toUpperCase();\n\n // Check responses (especially 200/201)\n const resDefinitions = (schemaAggregate.responses?.[200] ?? schemaAggregate.responses?.[201]) as\n | Record<string, InferredResponseDefinition>\n | undefined;\n if (resDefinitions) {\n for (const def of Object.values(resDefinitions)) {\n if (!def.schema) continue;\n\n if (def.schema.type === 'object') {\n const componentName = deriveEntityComponentName(path, method, false);\n registry.registerComponent(componentName, def.schema as InferredObjectSchema);\n } else if (def.schema.type === 'array') {\n const itemSchema = (def.schema as InferredArraySchema).itemSchema;\n if (itemSchema && itemSchema.type === 'object') {\n const componentName = deriveEntityComponentName(path, method, false);\n registry.registerComponent(componentName, itemSchema as InferredObjectSchema);\n }\n }\n }\n }\n\n // Check request body for POST/PUT/PATCH\n if (['POST', 'PUT', 'PATCH'].includes(method)) {\n const req = schemaAggregate.request;\n if (req && req.schema && req.schema.type === 'object') {\n const reqName = deriveEntityComponentName(path, method, true);\n registry.registerComponent(reqName, req.schema as InferredObjectSchema);\n }\n }\n }\n }\n}\n","export interface JsonParseResult {\n readonly isValidJson: boolean;\n readonly isEmpty: boolean;\n readonly isNonJsonContentType: boolean;\n readonly isPayloadTooLarge: boolean;\n readonly data?: unknown;\n readonly error?: string;\n readonly rawSnippet?: string;\n}\n\n/**\n * Validates Content-Type headers and safely parses JSON payloads within strict size boundaries.\n */\nexport class ContentDetector {\n /**\n * Checks whether a Content-Type or MIME type header indicates a JSON format.\n */\n public static isJsonMimeType(contentType?: string): boolean {\n if (!contentType) return false;\n const lower = contentType.toLowerCase().split(';')[0]?.trim() ?? '';\n return (\n lower === 'application/json' ||\n lower.endsWith('+json') ||\n lower === 'text/json' ||\n lower === 'text/x-json'\n );\n }\n\n /**\n * Safely attempts to parse raw payload strings with size boundary checks.\n */\n public static parseJson(\n payload?: string | null,\n contentType?: string,\n maxPayloadSizeBytes = 5 * 1024 * 1024 // 5MB\n ): JsonParseResult {\n if (payload === null || payload === undefined || payload.trim() === '') {\n return {\n isValidJson: false,\n isEmpty: true,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n };\n }\n\n // Check payload size boundary\n const byteLength = Buffer.byteLength(payload, 'utf-8');\n if (byteLength > maxPayloadSizeBytes) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: true,\n error: `Payload size (${byteLength} bytes) exceeds limit of ${maxPayloadSizeBytes} bytes`,\n rawSnippet: payload.slice(0, 100),\n };\n }\n\n // If explicit Content-Type is provided and definitely not JSON (e.g. text/html, image/png)\n if (contentType && !this.isJsonMimeType(contentType)) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: true,\n isPayloadTooLarge: false,\n error: `Content-Type '${contentType}' is not a recognized JSON MIME type`,\n rawSnippet: payload.slice(0, 100),\n };\n }\n\n try {\n const parsed = JSON.parse(payload);\n return {\n isValidJson: true,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n data: parsed,\n rawSnippet: payload.slice(0, 100),\n };\n } catch (err) {\n return {\n isValidJson: false,\n isEmpty: false,\n isNonJsonContentType: false,\n isPayloadTooLarge: false,\n error: err instanceof Error ? err.message : String(err),\n rawSnippet: payload.slice(0, 100),\n };\n }\n }\n}\n\n","export interface NormalizedMediaType {\n readonly raw: string;\n readonly canonical: string;\n readonly isJson: boolean;\n readonly isVendorJson: boolean;\n readonly isTextual: boolean;\n readonly charset?: string;\n}\n\n/**\n * Normalizes HTTP Content-Type headers into canonical media types.\n *\n * Rules:\n * 1. Parameters (e.g. charset=utf-8, boundary=...) are stripped for grouping.\n * 2. Missing/empty Content-Type defaults to 'application/octet-stream'.\n * 3. Legacy JSON aliases (text/json, text/x-json) map to canonical 'application/json'.\n * 4. Vendor and profile-specific JSON formats (application/problem+json, application/vnd.api+json)\n * are preserved distinctly to prevent contract cross-contamination.\n * 5. Media types are normalized to lower-case.\n */\nexport class MediaTypeNormalizer {\n public static normalize(contentType?: string | null): string {\n if (!contentType || contentType.trim() === '') {\n return 'application/octet-stream';\n }\n\n const segments = contentType.split(';');\n const primary = segments[0]?.trim().toLowerCase() ?? '';\n\n if (!primary) {\n return 'application/octet-stream';\n }\n\n // Standardize legacy JSON MIME aliases\n if (primary === 'text/json' || primary === 'text/x-json') {\n return 'application/json';\n }\n\n return primary;\n }\n\n /**\n * Checks whether a media type represents standard JSON or vendor-specific structured JSON (+json).\n */\n public static isJson(contentType?: string | null): boolean {\n const canonical = this.normalize(contentType);\n return canonical === 'application/json' || canonical.endsWith('+json');\n }\n\n /**\n * Checks whether a media type is a specialized vendor-specific JSON variant.\n */\n public static isVendorJson(contentType?: string | null): boolean {\n const canonical = this.normalize(contentType);\n return canonical !== 'application/json' && canonical.endsWith('+json');\n }\n\n /**\n * Extracts charset parameter if specified in raw header.\n */\n public static extractCharset(contentType?: string | null): string | undefined {\n if (!contentType) return undefined;\n const match = /charset\\s*=\\s*[\"']?([a-zA-Z0-9_-]+)[\"']?/i.exec(contentType);\n return match ? match[1]?.toLowerCase() : undefined;\n }\n\n /**\n * Returns a structured descriptor of the media type.\n */\n public static parse(contentType?: string | null): NormalizedMediaType {\n const raw = contentType ?? '';\n const canonical = this.normalize(raw);\n const isJson = this.isJson(raw);\n const isVendorJson = this.isVendorJson(raw);\n const isTextual =\n isJson ||\n canonical.startsWith('text/') ||\n canonical === 'application/xml' ||\n canonical.endsWith('+xml');\n const charset = this.extractCharset(raw);\n\n return {\n raw,\n canonical,\n isJson,\n isVendorJson,\n isTextual,\n charset,\n };\n }\n}\n\n","import type { InferredPrimitiveSchema } from '@luxray/shared';\n\nexport interface PrimitiveInferenceResult {\n readonly isPrimitive: boolean;\n readonly type: InferredPrimitiveSchema['type'];\n}\n\n/**\n * Classifies JavaScript scalar values into strict primitive schema types.\n */\nexport class PrimitiveInferencer {\n public static infer(value: unknown): PrimitiveInferenceResult {\n if (value === null) {\n return { isPrimitive: true, type: 'null' };\n }\n\n if (typeof value === 'boolean') {\n return { isPrimitive: true, type: 'boolean' };\n }\n\n if (typeof value === 'string') {\n return { isPrimitive: true, type: 'string' };\n }\n\n if (typeof value === 'number') {\n // Distinguish integer from floating-point\n return {\n isPrimitive: true,\n type: Number.isInteger(value) ? 'integer' : 'number',\n };\n }\n\n return { isPrimitive: false, type: 'any' };\n }\n}\n\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n InferredUnionSchema,\n} from '@luxray/shared';\nimport type { SampleRedactor } from '../redactor/sample-redactor.js';\n\nexport interface MergerOptions {\n maxRetainedSampleValues?: number;\n redactor?: SampleRedactor;\n}\n\n/**\n * Deterministic schema merger combining multiple schema observations.\n * Handles optional fields, nullability, type promotions (integer -> number),\n * empty-array refinement, and union variants without data pollution.\n */\nexport class SchemaMerger {\n private readonly maxSamples: number;\n private readonly redactor?: SampleRedactor;\n\n constructor(options?: MergerOptions) {\n this.maxSamples = options?.maxRetainedSampleValues ?? 5;\n this.redactor = options?.redactor;\n }\n\n /**\n * Merges two InferredSchema trees into a single reconciled InferredSchema.\n */\n public merge(a: InferredSchema, b: InferredSchema): InferredSchema {\n // 0. If either schema is unconstrained 'any', refine to the concrete schema\n if (a.type === 'any' && b.type !== 'any') {\n return {\n ...b,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n if (b.type === 'any' && a.type !== 'any') {\n return {\n ...a,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n if (a.type === 'any' && b.type === 'any') {\n return {\n type: 'any',\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n // 1. If schemas are identical primitives\n if (a.type === b.type && this.isPrimitiveType(a.type)) {\n return this.mergePrimitives(\n a as InferredPrimitiveSchema,\n b as InferredPrimitiveSchema\n );\n }\n\n // 2. Integer and Number promotion: (integer + number -> number)\n if (\n (a.type === 'integer' && b.type === 'number') ||\n (a.type === 'number' && b.type === 'integer')\n ) {\n const samples = this.mergeSamples(\n (a as InferredPrimitiveSchema).sampleValues,\n (b as InferredPrimitiveSchema).sampleValues\n );\n return {\n type: 'number',\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n sampleValues: samples,\n };\n }\n\n // 3. Null handling with non-null types: sets isNullable = true\n if (a.type === 'null' && b.type !== 'null') {\n return { ...b, isNullable: true };\n }\n if (b.type === 'null' && a.type !== 'null') {\n return { ...a, isNullable: true };\n }\n\n // 4. Object + Object merge\n if (a.type === 'object' && b.type === 'object') {\n return this.mergeObjects(a as InferredObjectSchema, b as InferredObjectSchema);\n }\n\n // 5. Array + Array merge\n if (a.type === 'array' && b.type === 'array') {\n return this.mergeArrays(a as InferredArraySchema, b as InferredArraySchema);\n }\n\n // 6. Union handling\n if (a.type === 'union' || b.type === 'union') {\n return this.mergeUnion(a, b);\n }\n\n // 7. Conflicting incompatible types: form a new union\n return {\n type: 'union',\n variants: [a, b],\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergePrimitives(\n a: InferredPrimitiveSchema,\n b: InferredPrimitiveSchema\n ): InferredPrimitiveSchema {\n const samples = this.mergeSamples(a.sampleValues, b.sampleValues);\n return {\n type: a.type,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n sampleValues: samples,\n };\n }\n\n private mergeObjects(\n a: InferredObjectSchema,\n b: InferredObjectSchema\n ): InferredObjectSchema {\n const mergedFields: Record<string, FieldMetadata> = {};\n const allFieldNames = new Set([...Object.keys(a.fields), ...Object.keys(b.fields)]);\n\n for (const name of allFieldNames) {\n const fieldA = a.fields[name];\n const fieldB = b.fields[name];\n\n if (fieldA && fieldB) {\n // Field observed in BOTH objects\n const mergedChildSchema = this.merge(fieldA.schema, fieldB.schema);\n const occurrences = fieldA.occurrences + fieldB.occurrences;\n const totalParent =\n fieldA.totalParentObservations + fieldB.totalParentObservations;\n const isOptional = occurrences < totalParent;\n const isNullable = fieldA.isNullable || fieldB.isNullable;\n const sampleValues = this.mergeSamples(\n fieldA.sampleValues,\n fieldB.sampleValues,\n name\n );\n\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n name,\n schema: mergedChildSchema,\n isOptional,\n isNullable,\n occurrences,\n totalParentObservations: totalParent,\n sampleValues,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n } else if (fieldA) {\n // Field observed ONLY in object A -> missing in B -> marked optional\n const totalParent =\n fieldA.totalParentObservations +\n this.getParentObservationsFromSibling(b.fields);\n\n const occurrences = fieldA.occurrences;\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n ...fieldA,\n isOptional: true,\n totalParentObservations: totalParent,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field missing in sibling observation; observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n } else if (fieldB) {\n // Field observed ONLY in object B -> missing in A -> marked optional\n const totalParent =\n fieldB.totalParentObservations +\n this.getParentObservationsFromSibling(a.fields);\n\n const occurrences = fieldB.occurrences;\n const presenceRatio = occurrences / totalParent;\n const volumeFactor = Math.min(1.0, occurrences / 10);\n const parsingValidityRatio = 1.0;\n const structuralStabilityRatio = Math.round(presenceRatio * 100) / 100;\n const confidenceScore = Math.round(\n (0.4 * volumeFactor + 0.3 * parsingValidityRatio + 0.3 * structuralStabilityRatio) * 100\n ) / 100;\n const confidenceLevel =\n confidenceScore >= 0.8 && occurrences >= 10 && presenceRatio >= 0.7\n ? 'high'\n : confidenceScore >= 0.45 && occurrences >= 3\n ? 'medium'\n : 'low';\n\n mergedFields[name] = {\n ...fieldB,\n isOptional: true,\n totalParentObservations: totalParent,\n confidence: {\n score: confidenceScore,\n level: confidenceLevel,\n volumeFactor,\n parsingValidityRatio,\n structuralStabilityRatio,\n rationale: [\n `Field missing in prior observation; observed in ${occurrences} of ${totalParent} parent object(s) (${Math.round(presenceRatio * 100)}% presence).`,\n ],\n },\n };\n }\n }\n\n return {\n type: 'object',\n fields: mergedFields,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeArrays(\n a: InferredArraySchema,\n b: InferredArraySchema\n ): InferredArraySchema {\n let itemSchema: InferredSchema;\n if (a.itemSchema.type === 'any') {\n itemSchema = b.itemSchema;\n } else if (b.itemSchema.type === 'any') {\n itemSchema = a.itemSchema;\n } else {\n itemSchema = this.merge(a.itemSchema, b.itemSchema);\n }\n\n return {\n type: 'array',\n itemSchema,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeUnion(a: InferredSchema, b: InferredSchema): InferredUnionSchema {\n let existingVariants: InferredSchema[] =\n a.type === 'union' ? [...(a as InferredUnionSchema).variants] : [a];\n\n const toMergeVariants: InferredSchema[] =\n b.type === 'union' ? [...(b as InferredUnionSchema).variants] : [b];\n\n for (const toMerge of toMergeVariants) {\n // If toMerge is uninformative 'any' and we already have concrete variants, do not add 'any'\n if (toMerge.type === 'any' && existingVariants.some((v) => v.type !== 'any')) {\n continue;\n }\n\n // If existingVariants has only 'any' and toMerge is concrete, replace 'any'\n if (\n existingVariants.length === 1 &&\n existingVariants[0]?.type === 'any' &&\n toMerge.type !== 'any'\n ) {\n existingVariants = [toMerge];\n continue;\n }\n\n let mergedIntoExisting = false;\n for (let i = 0; i < existingVariants.length; i++) {\n const variant = existingVariants[i]!;\n if (\n variant.type === toMerge.type ||\n (variant.type === 'integer' && toMerge.type === 'number') ||\n (variant.type === 'number' && toMerge.type === 'integer')\n ) {\n existingVariants[i] = this.merge(variant, toMerge);\n mergedIntoExisting = true;\n break;\n }\n }\n if (!mergedIntoExisting) {\n existingVariants.push(toMerge);\n }\n }\n\n return {\n type: 'union',\n variants: existingVariants,\n isNullable: a.isNullable || b.isNullable,\n isOptional: a.isOptional || b.isOptional,\n };\n }\n\n private mergeSamples(\n a?: readonly unknown[],\n b?: readonly unknown[],\n fieldName?: string\n ): readonly unknown[] {\n const seen = new Set<unknown>();\n const result: unknown[] = [];\n\n const addSamples = (arr?: readonly unknown[]) => {\n if (!arr) return;\n for (const item of arr) {\n if (result.length >= this.maxSamples) return;\n const sanitized = this.redactor\n ? this.redactor.sanitizeSampleValue(fieldName, item)\n : item;\n const serialized =\n typeof sanitized === 'object' ? JSON.stringify(sanitized) : sanitized;\n if (!seen.has(serialized)) {\n seen.add(serialized);\n result.push(sanitized);\n }\n }\n };\n\n addSamples(a);\n addSamples(b);\n\n return result;\n }\n\n private getParentObservationsFromSibling(fields: Record<string, FieldMetadata>): number {\n const values = Object.values(fields);\n if (values.length === 0) return 1;\n let maxParent = 1;\n for (const f of values) {\n if (f.totalParentObservations > maxParent) {\n maxParent = f.totalParentObservations;\n }\n }\n return maxParent;\n }\n\n private isPrimitiveType(type: string): boolean {\n return (\n type === 'string' ||\n type === 'number' ||\n type === 'integer' ||\n type === 'boolean' ||\n type === 'null' ||\n type === 'any'\n );\n }\n}\n","export interface RedactionOptions {\n /**\n * Additional regex patterns or string names indicating sensitive fields.\n */\n readonly sensitiveFieldPatterns?: readonly (RegExp | string)[];\n\n /**\n * Additional regex patterns indicating sensitive string values (e.g. tokens, keys).\n */\n readonly sensitiveValuePatterns?: readonly RegExp[];\n\n /**\n * Placeholder string for redacted values (default: '[REDACTED]').\n */\n readonly redactionMask?: string;\n\n /**\n * Custom hook for redaction decisions.\n */\n readonly customRedactor?: (fieldName: string | undefined, value: unknown) => unknown;\n}\n\nconst DEFAULT_SENSITIVE_FIELD_NAMES: readonly RegExp[] = [\n /password/i,\n /passphrase/i,\n /(?:^|[-_])passwd(?:$|[-_])/i,\n /(?:^|[-_])pwd(?:$|[-_])/i,\n /secret/i,\n /token/i,\n /authorization/i,\n /(?:^|[-_])auth(?:$|[-_])/i,\n /bearer/i,\n /api[-_]?key/i,\n /cookie/i,\n /set[-_]?cookie/i,\n /session/i,\n /session[-_]?id/i,\n /jwt/i,\n /private[-_]?key/i,\n /(?:^|[-_])ssn(?:$|[-_])/i,\n /social[-_]?sec(urity)?/i,\n /credit[-_]?card/i,\n /card[-_]?(?:num(?:ber)?|no)/i,\n /cvv/i,\n /cvc/i,\n /(?:^|[-_])pin(?:$|[-_])/i,\n /access[-_]?key/i,\n /client[-_]?secret/i,\n];\n\nconst DEFAULT_SENSITIVE_VALUE_PATTERNS: readonly RegExp[] = [\n // JWT tokens: 3 base64 segments\n /^ey[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}\\.[A-Za-z0-9_-]{10,}$/,\n // Bearer authentication tokens\n /^Bearer\\s+[A-Za-z0-9\\-._~+/]+=*$/i,\n // Basic authentication credentials\n /^Basic\\s+[A-Za-z0-9+/=]{8,}$/i,\n // Stripe API keys (sk_live_..., pk_test_...)\n /^(?:sk|pk)_(?:test|live)_[0-9a-zA-Z]{24,}$/,\n // GitHub access tokens (ghp_..., gho_..., etc.)\n /^gh[pousr]_[0-9a-zA-Z]{36,}$/,\n // AWS Access Key ID\n /^(?:AKIA|ABIA|ACCA|ASIA)[0-9A-Z]{16}$/,\n // Private key blocks\n /-----BEGIN\\s+(?:RSA\\s+)?PRIVATE\\s+KEY-----/i,\n // Credit card number pattern (13-19 digits with optional hyphens/spaces)\n /^(?:\\d{4}[-\\s]?){3}\\d{1,4}$/,\n];\n\n/**\n * Defensive heuristic credential and PII redaction for sample values and payload snippets.\n *\n * Design constraints:\n * - Operates under a fail-closed policy: unexpected errors result in redaction rather than raw data emission.\n * - Preserves structural AST schema inference (types, nullability, optionality) while masking retained sample values.\n * - Does not claim absolute zero-leak protection against arbitrary custom obfuscation; provides defense-in-depth.\n */\nexport class SampleRedactor {\n private readonly fieldPatterns: readonly RegExp[];\n private readonly valuePatterns: readonly RegExp[];\n private readonly redactionMask: string;\n private readonly customRedactor?: (fieldName: string | undefined, value: unknown) => unknown;\n\n constructor(options?: RedactionOptions) {\n this.redactionMask = options?.redactionMask ?? '[REDACTED]';\n this.customRedactor = options?.customRedactor;\n\n const extraFields = (options?.sensitiveFieldPatterns ?? []).map((p) =>\n typeof p === 'string' ? new RegExp(p, 'i') : p\n );\n this.fieldPatterns = [...DEFAULT_SENSITIVE_FIELD_NAMES, ...extraFields];\n\n this.valuePatterns = [\n ...DEFAULT_SENSITIVE_VALUE_PATTERNS,\n ...(options?.sensitiveValuePatterns ?? []),\n ];\n }\n\n /**\n * Checks whether a field name denotes sensitive content.\n */\n public isSensitiveFieldName(name?: string): boolean {\n if (!name) return false;\n return this.fieldPatterns.some((regex) => regex.test(name));\n }\n\n /**\n * Checks whether a value matches known credential or token formats.\n */\n public isSensitiveValue(value: unknown): boolean {\n if (typeof value !== 'string') return false;\n const trimmed = value.trim();\n return this.valuePatterns.some((regex) => regex.test(trimmed));\n }\n\n /**\n * Returns a sanitized sample value. If sensitive or on failure, fails closed with redaction mask.\n */\n public sanitizeSampleValue(fieldName: string | undefined, value: unknown): unknown {\n try {\n if (this.customRedactor) {\n const custom = this.customRedactor(fieldName, value);\n if (custom !== value) {\n return custom;\n }\n }\n\n if (this.isSensitiveFieldName(fieldName) || this.isSensitiveValue(value)) {\n return this.redactionMask;\n }\n\n return value;\n } catch {\n // Fail closed on any redaction error\n return this.redactionMask;\n }\n }\n\n /**\n * Redacts sensitive information from raw request/response payloads before storing sample snippets.\n * Fails closed if any parsing or traversal error occurs.\n */\n public sanitizePayloadString(\n rawPayload?: string | null,\n maxSnippetLength = 100\n ): string {\n if (!rawPayload || rawPayload.trim() === '') {\n return '';\n }\n\n try {\n // Attempt JSON parsing and recursive structural redaction\n const parsed = JSON.parse(rawPayload);\n const visited = new Set<unknown>();\n const sanitized = this.redactObjectRecursive(parsed, undefined, visited);\n const stringified = JSON.stringify(sanitized);\n return stringified.length > maxSnippetLength\n ? stringified.slice(0, maxSnippetLength)\n : stringified;\n } catch {\n // Non-JSON or malformed payload: apply regex-based token & credential mask\n try {\n let sanitized = rawPayload\n .replace(/(Bearer\\s+)[A-Za-z0-9\\-._~+/]+=*/gi, `$1${this.redactionMask}`)\n .replace(/(Basic\\s+)[A-Za-z0-9+/=]+/gi, `$1${this.redactionMask}`)\n .replace(\n /([\"']?(?:password|token|secret|apiKey|api_key|access_key)[\"']?\\s*[:=]\\s*[\"']?)[^\"',}\\s]+/gi,\n `$1${this.redactionMask}`\n );\n\n return sanitized.length > maxSnippetLength\n ? sanitized.slice(0, maxSnippetLength)\n : sanitized;\n } catch {\n // Complete fail-closed fallback\n return this.redactionMask;\n }\n }\n }\n\n private redactObjectRecursive(\n val: unknown,\n keyName?: string,\n visited = new Set<unknown>()\n ): unknown {\n if (val === null || val === undefined) return val;\n\n // Check custom redactor\n if (this.customRedactor) {\n try {\n const custom = this.customRedactor(keyName, val);\n if (custom !== val) return custom;\n } catch {\n return this.redactionMask;\n }\n }\n\n // Direct field name or value match\n if (this.isSensitiveFieldName(keyName) || this.isSensitiveValue(val)) {\n return this.redactionMask;\n }\n\n // Circular reference protection\n if (typeof val === 'object') {\n if (visited.has(val)) {\n return '[CIRCULAR]';\n }\n visited.add(val);\n }\n\n if (Array.isArray(val)) {\n return val.map((item) => this.redactObjectRecursive(item, keyName, visited));\n }\n\n if (typeof val === 'object') {\n const obj = val as Record<string, unknown>;\n const result: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(obj)) {\n result[k] = this.redactObjectRecursive(v, k, visited);\n }\n return result;\n }\n\n return val;\n }\n}\n","import type {\n FieldMetadata,\n InferredArraySchema,\n InferredObjectSchema,\n InferredPrimitiveSchema,\n InferredSchema,\n} from '@luxray/shared';\nimport { PrimitiveInferencer } from './primitive-inferencer.js';\nimport { SchemaMerger } from '../merger/schema-merger.js';\nimport { SampleRedactor, type RedactionOptions } from '../redactor/sample-redactor.js';\n\nexport interface ValueInferencerOptions {\n maxNestingDepth?: number;\n maxArraySamples?: number;\n maxRetainedSampleValues?: number;\n redaction?: RedactionOptions;\n redactor?: SampleRedactor;\n}\n\n/**\n * Infers an InferredSchema Intermediate Representation (IR) from any valid JavaScript value.\n * Protects against deep recursion, unbounded arrays, circular structures, and credential leakage.\n */\nexport class ValueInferencer {\n private readonly maxDepth: number;\n private readonly maxArraySamples: number;\n private readonly maxSamples: number;\n private readonly merger: SchemaMerger;\n private readonly redactor: SampleRedactor;\n\n constructor(options?: ValueInferencerOptions) {\n this.maxDepth = options?.maxNestingDepth ?? 20;\n this.maxArraySamples = options?.maxArraySamples ?? 50;\n this.maxSamples = options?.maxRetainedSampleValues ?? 5;\n this.redactor = options?.redactor ?? new SampleRedactor(options?.redaction);\n this.merger = new SchemaMerger({\n maxRetainedSampleValues: this.maxSamples,\n redactor: this.redactor,\n });\n }\n\n /**\n * Recursively infers the schema of any JavaScript value.\n */\n public infer(value: unknown, depth = 0, fieldName?: string): InferredSchema {\n // 1. Guard against unbounded recursion\n if (depth >= this.maxDepth) {\n return { type: 'any' };\n }\n\n // 2. Primitive inference\n const prim = PrimitiveInferencer.infer(value);\n if (prim.isPrimitive) {\n if (prim.type === 'null') {\n return { type: 'null', isNullable: true, sampleValues: [null] };\n }\n\n const sanitizedSample = this.redactor.sanitizeSampleValue(fieldName, value);\n return {\n type: prim.type,\n sampleValues: [sanitizedSample],\n } as InferredPrimitiveSchema;\n }\n\n // 3. Array inference\n if (Array.isArray(value)) {\n return this.inferArray(value, depth, fieldName);\n }\n\n // 4. Object inference\n if (typeof value === 'object' && value !== null) {\n return this.inferObject(value as Record<string, unknown>, depth);\n }\n\n return { type: 'any' };\n }\n\n private inferArray(arr: unknown[], depth: number, fieldName?: string): InferredArraySchema {\n if (arr.length === 0) {\n return {\n type: 'array',\n itemSchema: { type: 'any' },\n };\n }\n\n // Bound array sample size to avoid O(N) traversal on huge lists\n const sampleLimit = Math.min(arr.length, this.maxArraySamples);\n let unifiedItemSchema: InferredSchema = this.infer(arr[0], depth + 1, fieldName);\n\n for (let i = 1; i < sampleLimit; i++) {\n const currentItemSchema = this.infer(arr[i], depth + 1, fieldName);\n unifiedItemSchema = this.merger.merge(unifiedItemSchema, currentItemSchema);\n }\n\n return {\n type: 'array',\n itemSchema: unifiedItemSchema,\n };\n }\n\n private inferObject(\n obj: Record<string, unknown>,\n depth: number\n ): InferredObjectSchema {\n const fields: Record<string, FieldMetadata> = {};\n\n for (const [key, val] of Object.entries(obj)) {\n const childSchema = this.infer(val, depth + 1, key);\n const isNull = val === null;\n\n fields[key] = {\n name: key,\n schema: childSchema,\n isOptional: false,\n isNullable: isNull || Boolean(childSchema.isNullable),\n occurrences: 1,\n totalParentObservations: 1,\n sampleValues: this.extractSampleValue(val, key),\n confidence: {\n score: 0.7,\n level: 'medium',\n volumeFactor: 0.1,\n parsingValidityRatio: 1.0,\n structuralStabilityRatio: 1.0,\n rationale: ['Field observed in 1 of 1 parent object(s) (100% presence).'],\n },\n };\n }\n\n return {\n type: 'object',\n fields,\n };\n }\n\n private extractSampleValue(val: unknown, fieldName?: string): readonly unknown[] {\n if (val === null || val === undefined) return [null];\n\n const sanitized = this.redactor.sanitizeSampleValue(fieldName, val);\n if (sanitized !== val) {\n return [sanitized];\n }\n\n if (typeof val === 'object') {\n const snippet = JSON.stringify(val);\n return [snippet.length > 80 ? snippet.slice(0, 80) + '...' : snippet];\n }\n return [val];\n }\n}\n","import type {\n InferredArraySchema,\n InferredObjectSchema,\n InferredSchema,\n InferredUnionSchema,\n SchemaConfidence,\n} from '@luxray/shared';\n\nexport interface ConfidenceInput {\n readonly totalObservations: number;\n readonly validJsonObservations: number;\n readonly emptyBodyObservations: number;\n readonly nonJsonObservations: number;\n readonly truncatedObservations?: number;\n readonly schema?: InferredSchema;\n readonly hasInferredItemSchema?: boolean;\n}\n\n/**\n * Calculates deterministic evidentiary confidence ratings separating parsing validity from structural stability.\n *\n * Mathematical Model:\n * 1. Volume Factor (S in [0, 1]):\n * S = min(1.0, N_valid / 10). Reaches saturation at 10 or more valid observations.\n * 2. Parsing Validity Ratio (V in [0, 1]):\n * V = N_valid / N_total. Measures the proportion of successfully parsed JSON observations vs noise/truncation.\n * 3. Structural Stability Ratio (H in [0.1, 1.0]):\n * Measures contract convergence and absence of conflicting polymorphic variants.\n * - Single type / uniform object: H = 1.0 (or 0.5 + 0.5 * requiredFieldRatio)\n * - Union with K variants: H = max(0.2, 1.0 - (K - 1) * 0.25)\n * - Unconstrained any: H = 0.1\n * 4. Composite Score:\n * Score = round(0.40 * S + 0.30 * V + 0.30 * H, 2)\n *\n * Tier Boundaries:\n * - 'high': Score >= 0.80 AND N_valid >= 10 AND V >= 0.85 AND H >= 0.70.\n * (Heterogeneous schemas with H < 0.70 are strictly capped at 'medium' or 'low').\n * - 'medium': Score >= 0.45 AND N_valid >= 3.\n * - 'low': Score < 0.45 OR N_valid < 3.\n */\nexport class ConfidenceEvaluator {\n public static evaluate(input: ConfidenceInput): SchemaConfidence {\n const {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations = 0,\n schema,\n } = input;\n\n if (totalObservations === 0) {\n return {\n score: 0.0,\n level: 'low',\n volumeFactor: 0.0,\n parsingValidityRatio: 0.0,\n structuralStabilityRatio: 0.0,\n rationale: ['No observations recorded yet.'],\n };\n }\n\n const rationale: string[] = [];\n\n // Special clean empty responses (e.g. HTTP 204 No Content)\n if (validJsonObservations === 0 && emptyBodyObservations > 0) {\n const emptyRatio = emptyBodyObservations / totalObservations;\n const sEmpty = Math.min(1.0, emptyBodyObservations / 5);\n const score = Math.round(sEmpty * emptyRatio * 100) / 100;\n const level =\n score >= 0.75 && emptyBodyObservations >= 5 && emptyRatio >= 0.85\n ? 'high'\n : score >= 0.35 && emptyBodyObservations >= 2\n ? 'medium'\n : 'low';\n\n rationale.push(\n `Consistently empty body: ${emptyBodyObservations} empty observation(s) across ${totalObservations} transaction(s).`\n );\n if (emptyRatio === 1.0) {\n rationale.push('Payload is 100% consistently empty.');\n }\n return {\n score,\n level,\n volumeFactor: Math.round(sEmpty * 100) / 100,\n parsingValidityRatio: Math.round(emptyRatio * 100) / 100,\n structuralStabilityRatio: 1.0,\n rationale,\n };\n }\n\n const volumeFactor = Math.min(1.0, validJsonObservations / 10);\n const parsingValidityRatio = validJsonObservations / totalObservations;\n const structuralStabilityRatio = this.calculateStructuralStability(schema);\n\n // Multiplicative evidentiary model: volumeFactor gates structural & parsing validity\n const score =\n Math.round(\n volumeFactor *\n (0.50 * parsingValidityRatio + 0.50 * structuralStabilityRatio) *\n 100\n ) / 100;\n\n rationale.push(\n `Observation volume: ${validJsonObservations} valid payload(s) across ${totalObservations} transaction(s) (volume factor: ${volumeFactor.toFixed(2)}).`\n );\n\n if (validJsonObservations >= 10) {\n rationale.push('Sufficient sample size (>= 10) observed.');\n } else if (validJsonObservations < 3) {\n rationale.push('Low sample size (< 3); schema optionality and variants may be incomplete.');\n }\n\n if (nonJsonObservations > 0 || truncatedObservations > 0) {\n const noise = nonJsonObservations + truncatedObservations;\n const noisePercent = Math.round((noise / totalObservations) * 100);\n rationale.push(\n `${noise} unparseable, truncated, or non-JSON observation(s) recorded (${noisePercent}% noise ratio).`\n );\n }\n\n if (structuralStabilityRatio >= 0.85) {\n rationale.push('High structural stability: schema demonstrates consistent field and type structures.');\n } else if (structuralStabilityRatio < 0.6) {\n rationale.push(\n `Low structural stability (${structuralStabilityRatio.toFixed(2)}): schema contains polymorphic variants or high field variance.`\n );\n }\n\n // Determine Tier with strict evidentiary constraints\n let level: 'low' | 'medium' | 'high';\n if (\n score >= 0.75 &&\n validJsonObservations >= 10 &&\n parsingValidityRatio >= 0.85 &&\n structuralStabilityRatio >= 0.7\n ) {\n level = 'high';\n } else if (score >= 0.35 && validJsonObservations >= 3) {\n level = 'medium';\n } else {\n level = 'low';\n }\n\n return {\n score,\n level,\n volumeFactor: Math.round(volumeFactor * 100) / 100,\n parsingValidityRatio: Math.round(parsingValidityRatio * 100) / 100,\n structuralStabilityRatio: Math.round(structuralStabilityRatio * 100) / 100,\n rationale,\n };\n }\n\n private static calculateStructuralStability(schema?: InferredSchema): number {\n if (!schema) return 0.5;\n\n switch (schema.type) {\n case 'any':\n return 0.1;\n\n case 'union': {\n const variants = (schema as InferredUnionSchema).variants;\n const count = variants.length;\n if (count <= 1) return 1.0;\n // Each additional conflicting variant penalizes stability by 0.25\n return Math.max(0.2, 1.0 - (count - 1) * 0.25);\n }\n\n case 'object': {\n const fields = Object.values((schema as InferredObjectSchema).fields);\n if (fields.length === 0) return 0.8;\n const requiredCount = fields.filter((f) => !f.isOptional).length;\n const requiredRatio = requiredCount / fields.length;\n return Math.round((0.5 + 0.5 * requiredRatio) * 100) / 100;\n }\n\n case 'array': {\n const itemSchema = (schema as InferredArraySchema).itemSchema;\n if (itemSchema.type === 'any') return 0.5;\n if (itemSchema.type === 'union') {\n return this.calculateStructuralStability(itemSchema);\n }\n return 1.0;\n }\n\n case 'string':\n case 'number':\n case 'integer':\n case 'boolean':\n case 'null':\n return 1.0;\n\n default:\n return 0.5;\n }\n }\n}\n","import type {\n CapturedTransaction,\n EndpointSchemaAggregate,\n InferredRequestDefinition,\n InferredResponseDefinition,\n InferredSchema,\n} from '@luxray/shared';\nimport type { EndpointNormalizer } from '@luxray/normalization';\nimport { ContentDetector } from '../parser/content-detector.js';\nimport { MediaTypeNormalizer } from '../parser/media-type-normalizer.js';\nimport { ValueInferencer } from '../inferencer/value-inferencer.js';\nimport { SchemaMerger } from '../merger/schema-merger.js';\nimport { SampleRedactor, type RedactionOptions } from '../redactor/sample-redactor.js';\nimport { ConfidenceEvaluator } from '../provenance/confidence-evaluator.js';\n\nexport interface SchemaInferenceEngineOptions {\n normalizer?: EndpointNormalizer;\n maxPayloadSizeBytes?: number;\n maxNestingDepth?: number;\n maxArraySamples?: number;\n maxRetainedSampleValues?: number;\n maxRetainedTransactions?: number;\n redaction?: RedactionOptions;\n redactor?: SampleRedactor;\n}\n\nexport function normalizeMediaType(contentType?: string | null): string {\n return MediaTypeNormalizer.normalize(contentType);\n}\n\nfunction getHeader(headers: Record<string, string> | undefined, name: string): string | undefined {\n if (!headers) return undefined;\n const target = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === target) {\n return v;\n }\n }\n return undefined;\n}\n\n/**\n * Hardened engine that ingests captured HTTP transactions, infers request and response schemas,\n * groups responses by status code and normalized media type, redacts credentials, handles body truncation,\n * and derives evidentiary confidence ratings.\n */\nexport class SchemaInferenceEngine {\n private readonly normalizer?: EndpointNormalizer;\n private readonly maxPayloadSizeBytes: number;\n private readonly maxRetainedSamples: number;\n private readonly maxRetainedTransactions: number;\n private readonly redactor: SampleRedactor;\n private readonly inferencer: ValueInferencer;\n private readonly merger: SchemaMerger;\n private readonly aggregates = new Map<string, EndpointSchemaAggregate>();\n\n constructor(options?: SchemaInferenceEngineOptions) {\n this.normalizer = options?.normalizer;\n this.maxPayloadSizeBytes = options?.maxPayloadSizeBytes ?? 5 * 1024 * 1024;\n this.maxRetainedSamples = options?.maxRetainedSampleValues ?? 5;\n this.maxRetainedTransactions = options?.maxRetainedTransactions ?? 100;\n this.redactor = options?.redactor ?? new SampleRedactor(options?.redaction);\n this.inferencer = new ValueInferencer({\n maxNestingDepth: options?.maxNestingDepth,\n maxArraySamples: options?.maxArraySamples,\n maxRetainedSampleValues: options?.maxRetainedSampleValues,\n redactor: this.redactor,\n });\n this.merger = new SchemaMerger({\n maxRetainedSampleValues: options?.maxRetainedSampleValues,\n redactor: this.redactor,\n });\n }\n\n /**\n * Infers schema IR from any in-memory JavaScript data value.\n */\n public inferFromValue(value: unknown, fieldName?: string): InferredSchema {\n return this.inferencer.infer(value, 0, fieldName);\n }\n\n /**\n * Parses and infers schema IR from raw JSON string content.\n */\n public inferFromJson(rawJson: string, contentType?: string): InferredSchema | null {\n const parseResult = ContentDetector.parseJson(\n rawJson,\n contentType,\n this.maxPayloadSizeBytes\n );\n if (!parseResult.isValidJson) {\n return null;\n }\n return this.inferencer.infer(parseResult.data);\n }\n\n /**\n * Reconciles two schemas into a unified, backward-compatible schema.\n */\n public mergeSchemas(a: InferredSchema, b: InferredSchema): InferredSchema {\n return this.merger.merge(a, b);\n }\n\n /**\n * Ingests a CapturedTransaction and updates request/response schemas for the corresponding endpoint.\n */\n public ingestTransaction(\n transaction: CapturedTransaction,\n explicitEndpointId?: string\n ): EndpointSchemaAggregate {\n const endpointId = this.resolveEndpointId(transaction, explicitEndpointId);\n const txTime = transaction.timing?.startTime ?? Date.now();\n\n let aggregate = this.aggregates.get(endpointId);\n if (!aggregate) {\n aggregate = {\n endpointId,\n requests: {},\n responses: {},\n lastUpdatedAt: txTime,\n };\n }\n\n // 1. Process Request Payload\n const updatedRequests = { ...(aggregate.requests ?? {}) };\n const rawReqBody = transaction.request.postData;\n const rawReqContentType =\n getHeader(transaction.request.headers, 'content-type') ?? 'application/json';\n const reqMediaType = MediaTypeNormalizer.normalize(rawReqContentType);\n\n const existingReq = updatedRequests[reqMediaType] ?? aggregate.request;\n const updatedReq = this.processRequest(\n transaction,\n existingReq,\n rawReqContentType,\n reqMediaType,\n txTime\n );\n\n if (updatedReq) {\n updatedRequests[reqMediaType] = updatedReq;\n }\n\n // Primary request: prefer application/json if present, otherwise updatedReq\n const primaryRequest =\n updatedRequests['application/json'] ??\n updatedReq ??\n aggregate.request;\n\n // 2. Process Response Payload\n // Deep clone response structure: Record<number, Record<string, InferredResponseDefinition>>\n const updatedResponses: Record<number, Record<string, InferredResponseDefinition>> = {};\n for (const [codeStr, mediaMap] of Object.entries(aggregate.responses)) {\n updatedResponses[Number(codeStr)] = { ...mediaMap };\n }\n\n if (transaction.response) {\n const statusCode = transaction.response.status;\n const rawRespContentType =\n transaction.response.mimeType ??\n getHeader(transaction.response.headers, 'content-type') ??\n 'application/json';\n const respMediaType = MediaTypeNormalizer.normalize(rawRespContentType);\n\n if (!updatedResponses[statusCode]) {\n updatedResponses[statusCode] = {};\n }\n\n const existingResponse = updatedResponses[statusCode]![respMediaType];\n const updatedResp = this.processResponse(\n transaction,\n existingResponse,\n rawRespContentType,\n respMediaType,\n txTime\n );\n\n if (updatedResp) {\n updatedResponses[statusCode]![respMediaType] = updatedResp;\n }\n }\n\n const updatedAggregate: EndpointSchemaAggregate = {\n endpointId,\n request: primaryRequest,\n requests: updatedRequests,\n responses: updatedResponses,\n lastUpdatedAt: Math.max(aggregate.lastUpdatedAt, txTime),\n };\n\n this.aggregates.set(endpointId, updatedAggregate);\n return updatedAggregate;\n }\n\n /**\n * Retrieves an endpoint schema aggregate by ID.\n */\n public getAggregate(endpointId: string): EndpointSchemaAggregate | undefined {\n return this.aggregates.get(endpointId);\n }\n\n /**\n * Convenience helper to retrieve a response definition by status code and optional media type.\n * If mediaType is omitted, returns 'application/json' if present, or the first available representation.\n */\n public getResponse(\n endpointId: string,\n statusCode: number,\n contentType?: string\n ): InferredResponseDefinition | undefined {\n const agg = this.getAggregate(endpointId);\n if (!agg) return undefined;\n const statusMap = agg.responses[statusCode];\n if (!statusMap) return undefined;\n\n if (contentType) {\n const norm = MediaTypeNormalizer.normalize(contentType);\n return statusMap[norm];\n }\n\n return statusMap['application/json'] ?? Object.values(statusMap)[0];\n }\n\n /**\n * Returns all stored endpoint schema aggregates.\n */\n public getAllAggregates(): readonly EndpointSchemaAggregate[] {\n return Array.from(this.aggregates.values());\n }\n\n /**\n * Clears all in-memory aggregates.\n */\n public clear(): void {\n this.aggregates.clear();\n }\n\n private resolveEndpointId(\n transaction: CapturedTransaction,\n explicitEndpointId?: string\n ): string {\n if (explicitEndpointId) {\n return explicitEndpointId;\n }\n\n if (this.normalizer) {\n return this.normalizer.normalize(\n transaction.request.url,\n transaction.request.method\n ).identity.id;\n }\n\n try {\n const parsed = new URL(transaction.request.url);\n return `${transaction.request.method.toUpperCase()} ${parsed.pathname}`;\n } catch {\n // Strip query parameters to avoid retaining query credentials\n const pathOnly = transaction.request.url.split('?')[0] ?? transaction.request.url;\n return `${transaction.request.method.toUpperCase()} ${pathOnly}`;\n }\n }\n\n private processRequest(\n transaction: CapturedTransaction,\n existing: InferredRequestDefinition | undefined,\n contentType: string,\n mediaType: string,\n txTime: number\n ): InferredRequestDefinition | undefined {\n const rawBody = transaction.request.postData;\n const txId = transaction.id;\n\n if (rawBody === undefined || rawBody === null || rawBody.trim() === '') {\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const emptyBodyObservations = existing.provenance.emptyBodyObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n emptyBodyObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n return undefined;\n }\n\n const parseResult = ContentDetector.parseJson(\n rawBody,\n contentType,\n this.maxPayloadSizeBytes\n );\n\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n\n if (parseResult.isValidJson) {\n const inferred = this.inferencer.infer(parseResult.data);\n\n if (existing) {\n const mergedSchema = this.merger.merge(existing.schema, inferred);\n const samplePayloads = existing.provenance.samplePayloads.includes(sanitizedSnippet)\n ? existing.provenance.samplePayloads\n : [...existing.provenance.samplePayloads, sanitizedSnippet].slice(-this.maxRetainedSamples);\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n\n const totalObservations = existing.provenance.totalObservations + 1;\n const validJsonObservations = existing.provenance.validJsonObservations + 1;\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: mergedSchema,\n });\n\n return {\n contentType: existing.contentType || contentType,\n mediaType: existing.mediaType || mediaType,\n schema: mergedSchema,\n provenance: {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n firstObservedAt: Math.min(existing.provenance.firstObservedAt, txTime),\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n transactionIds,\n samplePayloads,\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n schema: inferred,\n });\n\n return {\n contentType,\n mediaType,\n schema: inferred,\n provenance: {\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n // Invalid JSON, payload too large, or non-JSON content type\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n private processResponse(\n transaction: CapturedTransaction,\n existing: InferredResponseDefinition | undefined,\n contentType: string,\n mediaType: string,\n txTime: number\n ): InferredResponseDefinition | undefined {\n if (!transaction.response) return undefined;\n\n const statusCode = transaction.response.status;\n const rawBody = transaction.response.body;\n const isTruncated = Boolean(transaction.response.bodyTruncated);\n const txId = transaction.id;\n\n // 1. Guard against truncated bodies: Never infer partial bodies as complete schemas\n if (isTruncated) {\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const truncatedObservations = (existing.provenance.truncatedObservations ?? 0) + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n truncatedObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n truncatedObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n truncatedObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: sanitizedSnippet ? [sanitizedSnippet] : [],\n confidence,\n },\n };\n }\n\n // 2. Empty response body (e.g. 204 No Content, 304 Not Modified)\n if (rawBody === undefined || rawBody === null || rawBody.trim() === '') {\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const emptyBodyObservations = existing.provenance.emptyBodyObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n emptyBodyObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 1,\n nonJsonObservations: 0,\n schema: { type: 'null', isNullable: true },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'null', isNullable: true },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 1,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [],\n confidence,\n },\n };\n }\n\n // 3. Normal Non-Empty Response Body\n const parseResult = ContentDetector.parseJson(\n rawBody,\n contentType,\n this.maxPayloadSizeBytes\n );\n\n const sanitizedSnippet = this.redactor.sanitizePayloadString(rawBody, 100);\n\n if (parseResult.isValidJson) {\n const inferred = this.inferencer.infer(parseResult.data);\n\n if (existing) {\n const mergedSchema = this.merger.merge(existing.schema, inferred);\n const samplePayloads = existing.provenance.samplePayloads.includes(sanitizedSnippet)\n ? existing.provenance.samplePayloads\n : [...existing.provenance.samplePayloads, sanitizedSnippet].slice(-this.maxRetainedSamples);\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n\n const totalObservations = existing.provenance.totalObservations + 1;\n const validJsonObservations = existing.provenance.validJsonObservations + 1;\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: mergedSchema,\n });\n\n return {\n statusCode,\n contentType: existing.contentType || contentType,\n mediaType: existing.mediaType || mediaType,\n schema: mergedSchema,\n provenance: {\n totalObservations,\n validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations: existing.provenance.nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n firstObservedAt: Math.min(existing.provenance.firstObservedAt, txTime),\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n transactionIds,\n samplePayloads,\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n schema: inferred,\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: inferred,\n provenance: {\n totalObservations: 1,\n validJsonObservations: 1,\n emptyBodyObservations: 0,\n nonJsonObservations: 0,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n // 4. Invalid JSON, payload too large, or non-JSON content type (e.g. text/html)\n if (existing) {\n const totalObservations = existing.provenance.totalObservations + 1;\n const nonJsonObservations = existing.provenance.nonJsonObservations + 1;\n const transactionIds = this.appendTransactionId(existing.provenance.transactionIds, txId);\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations,\n validJsonObservations: existing.provenance.validJsonObservations,\n emptyBodyObservations: existing.provenance.emptyBodyObservations,\n nonJsonObservations,\n truncatedObservations: existing.provenance.truncatedObservations,\n schema: existing.schema,\n });\n\n return {\n ...existing,\n provenance: {\n ...existing.provenance,\n totalObservations,\n nonJsonObservations,\n transactionIds,\n lastObservedAt: Math.max(existing.provenance.lastObservedAt, txTime),\n confidence,\n },\n };\n }\n\n const confidence = ConfidenceEvaluator.evaluate({\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n schema: { type: 'any' },\n });\n\n return {\n statusCode,\n contentType,\n mediaType,\n schema: { type: 'any' },\n provenance: {\n totalObservations: 1,\n validJsonObservations: 0,\n emptyBodyObservations: 0,\n nonJsonObservations: 1,\n firstObservedAt: txTime,\n lastObservedAt: txTime,\n transactionIds: [txId],\n samplePayloads: [sanitizedSnippet],\n confidence,\n },\n };\n }\n\n private appendTransactionId(list: readonly string[], newId: string): readonly string[] {\n if (list.includes(newId)) return list;\n const updated = [...list, newId];\n if (updated.length > this.maxRetainedTransactions) {\n return updated.slice(-this.maxRetainedTransactions);\n }\n return updated;\n }\n}\n","import type {\n AgentArchitecture,\n AgentPlatform,\n ExplorationJobType,\n ExplorationTask,\n ExplorationTaskScope,\n LoginResponse,\n RegisterAgentResponse,\n} from '@luxray/shared';\n\n/**\n * Minimal HTTP client for the Luxray API.\n *\n * Kept separate from the CLI entry point so the authentication and\n * registration flows can be tested without spawning a process or a server.\n * `fetch` is injected for exactly that reason.\n */\n\nexport interface HttpResponseLike {\n readonly ok: boolean;\n readonly status: number;\n text(): Promise<string>;\n json(): Promise<unknown>;\n}\n\nexport interface RequestOptionsLike {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n}\n\nexport type FetchLike = (url: string, init: RequestOptionsLike) => Promise<HttpResponseLike>;\n\nexport class LuxrayApiError extends Error {\n constructor(\n public readonly status: number,\n message: string,\n ) {\n super(message);\n this.name = 'LuxrayApiError';\n }\n}\n\nexport interface RegisterAgentPayload {\n readonly name: string;\n readonly platform: AgentPlatform | string;\n readonly arch: AgentArchitecture | string;\n readonly version: string;\n readonly metadata?: Record<string, unknown>;\n}\n\nfunction normalizeBaseUrl(apiUrl: string): string {\n return apiUrl.replace(/\\/+$/, '');\n}\n\nasync function postJson<T>(\n fetchImpl: FetchLike,\n url: string,\n body: unknown,\n accessToken?: string,\n): Promise<T> {\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n if (accessToken) {\n headers['Authorization'] = `Bearer ${accessToken}`;\n }\n\n let response: HttpResponseLike;\n try {\n response = await fetchImpl(url, {\n method: 'POST',\n headers,\n body: JSON.stringify(body),\n });\n } catch (err) {\n throw new LuxrayApiError(0, `Could not reach ${url}: ${(err as Error).message}`);\n }\n\n if (!response.ok) {\n let detail = '';\n try {\n detail = (await response.text()).trim();\n } catch {\n // A failure to read the error body must not hide the status code.\n }\n throw new LuxrayApiError(\n response.status,\n `HTTP ${response.status}${detail ? `: ${detail}` : ''}`,\n );\n }\n\n return (await response.json()) as T;\n}\n\n/**\n * Exchanges user credentials for a short-lived access token.\n * This is the only way the CLI obtains authority to act on a workspace.\n */\nexport function login(\n fetchImpl: FetchLike,\n apiUrl: string,\n email: string,\n password: string,\n): Promise<LoginResponse> {\n return postJson<LoginResponse>(fetchImpl, `${normalizeBaseUrl(apiUrl)}/v1/auth/login`, {\n email,\n password,\n });\n}\n\n/**\n * Registers a local agent. The workspace is part of the URL and is authorized\n * by the bearer token; it is deliberately NOT sent in the body (the API\n * rejects unknown body properties).\n */\nexport function registerAgent(\n fetchImpl: FetchLike,\n apiUrl: string,\n workspaceId: string,\n accessToken: string,\n payload: RegisterAgentPayload,\n): Promise<RegisterAgentResponse> {\n return postJson<RegisterAgentResponse>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/v1/workspaces/${encodeURIComponent(workspaceId)}/agents/register`,\n payload,\n accessToken,\n );\n}\n\nexport interface CreateAgentTaskPayload {\n readonly startUrl: string;\n readonly jobType?: ExplorationJobType;\n readonly name?: string;\n readonly scope?: ExplorationTaskScope;\n readonly maxAttempts?: number;\n}\n\n/**\n * Asks the control plane to run a URL the operator typed in the terminal.\n *\n * Authenticated with the agent token rather than a user session: the machine\n * issuing the command may not have one, and the task it creates is leased to\n * that same agent in the same request.\n */\nexport function createAgentExplorationTask(\n fetchImpl: FetchLike,\n apiUrl: string,\n agentToken: string,\n payload: CreateAgentTaskPayload,\n): Promise<{ task: ExplorationTask }> {\n return postJson<{ task: ExplorationTask }>(\n fetchImpl,\n `${normalizeBaseUrl(apiUrl)}/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Aa,IAAI,eAAe,CAAC,KAAK,CAAC;MACzC;IACF;AAEA,UAAM,WAAW,OAAO,OAAO,OAAO,KAAK,MAAM,CAAC,IAAI;AAEtD,WAAO;MACL,QAAQ;MACR;MACA,UAAAA;MACA;MACA;MACA;MACA;MACA,UAAU;MACV;MACA;;EAEJ;;;;AC/FK,IAAM,mBAAmB;AAGzB,IAAM,aACX;AAGK,IAAM,qBACX;AAGK,IAAM,aAAa;AAGnB,IAAM,kBAAkB;AAGxB,IAAM,iBAAiB;AAGvB,IAAM,oBAAoB;AAG1B,IAAM,aAAa;AAGnB,IAAM,eAAe;AAGrB,IAAM,gBAAgB;;;AC5BtB,IAAM,wBAAwB,oBAAI,IAAY;;EAEnD;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD;AAKK,SAAU,wBAAwB,SAAe;AACrD,QAAM,QAAQ,QAAQ,YAAW;AACjC,MAAI,sBAAsB,IAAI,KAAK,GAAG;AACpC,WAAO;EACT;AAEA,MAAI,cAAc,KAAK,OAAO,GAAG;AAC/B,WAAO;EACT;AAEA,MAAI,sBAAsB,KAAK,OAAO,GAAG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,CAAC;AAChB,CAAC;","names":["os","existsSync","readFileSync","mkdir","dirname","join","os","resolve","join","join","resolve","result","createHash","join","join","mkdir","writeFile","join","result","path","resolve","chromium","result","errorMessage","resolve","clampInt","writeFile","join","hostname","result","isSuccess","statusCodes","primarySingular","URL","UUID_REGEX","URL","UUID_REGEX","result","result","capitalize","document","path","result","result","score","level","confidence","sanitizedSnippet","document","join","writeFile","join","createHash","resolve","path","existsSync","readFileSync","mkdir","dirname","platform","arch","join","hostname","result"]}
|