@contentrain/mcp 1.8.0 → 1.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/README.md +5 -1
  2. package/dist/{annotations-BFJbfSKe.mjs → annotations-DSzewhL4.mjs} +42 -20
  3. package/dist/annotations-DSzewhL4.mjs.map +1 -0
  4. package/dist/{apply-manager-BRmB27H5.mjs → apply-manager-BnPbPXFG.mjs} +1 -1
  5. package/dist/{apply-manager-BRmB27H5.mjs.map → apply-manager-BnPbPXFG.mjs.map} +1 -1
  6. package/dist/{astro-parser-B-nLl0zE.mjs → astro-parser-BVoGjA6M.mjs} +3 -3
  7. package/dist/{astro-parser-B-nLl0zE.mjs.map → astro-parser-BVoGjA6M.mjs.map} +1 -1
  8. package/dist/availability-Bj9zOfEn.mjs +47 -0
  9. package/dist/availability-Bj9zOfEn.mjs.map +1 -0
  10. package/dist/{branch-lifecycle-7dQoF22r.d.mts → branch-lifecycle-AwBJIheA.d.mts} +1 -1
  11. package/dist/{branch-lifecycle-7dQoF22r.d.mts.map → branch-lifecycle-AwBJIheA.d.mts.map} +1 -1
  12. package/dist/{compiler-k4yttlzM.mjs → compiler-BZXAN4Ir.mjs} +2 -2
  13. package/dist/{compiler-k4yttlzM.mjs.map → compiler-BZXAN4Ir.mjs.map} +1 -1
  14. package/dist/{compiler-sfc.cjs-D0d_OicF.mjs → compiler-sfc.cjs-tFlmtjrJ.mjs} +2 -2
  15. package/dist/{compiler-sfc.cjs-D0d_OicF.mjs.map → compiler-sfc.cjs-tFlmtjrJ.mjs.map} +1 -1
  16. package/dist/{content-manager-DqDLSNQ-.d.mts → content-manager-BExZy6Eu.d.mts} +2 -2
  17. package/dist/{content-manager-DqDLSNQ-.d.mts.map → content-manager-BExZy6Eu.d.mts.map} +1 -1
  18. package/dist/core/apply-manager.mjs +1 -1
  19. package/dist/core/config.d.mts +1 -1
  20. package/dist/core/content-manager.d.mts +1 -1
  21. package/dist/core/context.d.mts +1 -1
  22. package/dist/core/contracts/index.d.mts +1 -1
  23. package/dist/core/doctor.mjs +2 -2
  24. package/dist/core/graph-builder.mjs +2 -2
  25. package/dist/core/model-manager.d.mts +1 -1
  26. package/dist/core/ops/index.d.mts +2 -2
  27. package/dist/core/overlay-reader.d.mts +1 -1
  28. package/dist/core/overlay-reader.mjs +1 -1
  29. package/dist/core/scan-config.mjs +1 -1
  30. package/dist/core/scanner.mjs +3 -3
  31. package/dist/core/validator/index.d.mts +1 -1
  32. package/dist/core/validator/index.mjs +1 -1
  33. package/dist/{detect-eWS6lvoH.mjs → detect-wVSI9VuY.mjs} +1 -1
  34. package/dist/{detect-eWS6lvoH.mjs.map → detect-wVSI9VuY.mjs.map} +1 -1
  35. package/dist/{doctor-qiUKCy9b.mjs → doctor-BTToHt0y.mjs} +2 -2
  36. package/dist/{doctor-qiUKCy9b.mjs.map → doctor-BTToHt0y.mjs.map} +1 -1
  37. package/dist/git/branch-lifecycle.d.mts +1 -1
  38. package/dist/git/transaction.d.mts +1 -1
  39. package/dist/{graph-builder-DXv2JEp-.mjs → graph-builder-CRUX_8mA.mjs} +2 -2
  40. package/dist/{graph-builder-DXv2JEp-.mjs.map → graph-builder-CRUX_8mA.mjs.map} +1 -1
  41. package/dist/index-6yasXNLQ.d.mts +2 -0
  42. package/dist/index.mjs +10 -10
  43. package/dist/{node-DN9hZeil.mjs → node-wC-z3NoZ.mjs} +1 -1
  44. package/dist/{node-DN9hZeil.mjs.map → node-wC-z3NoZ.mjs.map} +1 -1
  45. package/dist/{overlay-reader-CUs9jgqk.mjs → overlay-reader-BOb105gS.mjs} +1 -1
  46. package/dist/{overlay-reader-CUs9jgqk.mjs.map → overlay-reader-BOb105gS.mjs.map} +1 -1
  47. package/dist/{paths-C3xNyc7z.mjs → paths-BU6E-oDs.mjs} +1 -1
  48. package/dist/{paths-C3xNyc7z.mjs.map → paths-BU6E-oDs.mjs.map} +1 -1
  49. package/dist/providers/github/index.d.mts +1 -1
  50. package/dist/providers/github/index.mjs +32 -9
  51. package/dist/providers/github/index.mjs.map +1 -1
  52. package/dist/providers/gitlab/index.d.mts +1 -1
  53. package/dist/providers/gitlab/index.mjs +36 -11
  54. package/dist/providers/gitlab/index.mjs.map +1 -1
  55. package/dist/providers/local/index.d.mts +2 -2
  56. package/dist/providers/local/index.d.mts.map +1 -1
  57. package/dist/{scan-config-jC6XmiqF.mjs → scan-config-BGUflS8t.mjs} +1 -1
  58. package/dist/{scan-config-jC6XmiqF.mjs.map → scan-config-BGUflS8t.mjs.map} +1 -1
  59. package/dist/{scanner-DKMwc03k.mjs → scanner-VOwrKLGC.mjs} +6 -6
  60. package/dist/{scanner-DKMwc03k.mjs.map → scanner-VOwrKLGC.mjs.map} +1 -1
  61. package/dist/server/http/index.d.mts +11 -1
  62. package/dist/server/http/index.d.mts.map +1 -1
  63. package/dist/server/http/index.mjs +20 -12
  64. package/dist/server/http/index.mjs.map +1 -1
  65. package/dist/{server-DZBcZWhE.d.mts → server-B1KfvywF.d.mts} +25 -10
  66. package/dist/server-B1KfvywF.d.mts.map +1 -0
  67. package/dist/{server-tTuinKHD.mjs → server-B6_fzRmK.mjs} +47 -18
  68. package/dist/{server-tTuinKHD.mjs.map → server-B6_fzRmK.mjs.map} +1 -1
  69. package/dist/server.d.mts +2 -2
  70. package/dist/server.mjs +11 -11
  71. package/dist/{source-map-generator-BWDva49I.mjs → source-map-generator-BIEiz3If.mjs} +1 -1
  72. package/dist/{source-map-generator-BWDva49I.mjs.map → source-map-generator-BIEiz3If.mjs.map} +1 -1
  73. package/dist/{svelte-parser-Dr9mmZuk.mjs → svelte-parser-Bll-1SK0.mjs} +3 -3
  74. package/dist/{svelte-parser-Dr9mmZuk.mjs.map → svelte-parser-Bll-1SK0.mjs.map} +1 -1
  75. package/dist/templates/index.mjs +1 -1
  76. package/dist/{templates-VrLVqfe5.mjs → templates-D6EllixQ.mjs} +1 -1
  77. package/dist/{templates-VrLVqfe5.mjs.map → templates-D6EllixQ.mjs.map} +1 -1
  78. package/dist/tools/annotations.d.mts +3 -0
  79. package/dist/tools/annotations.d.mts.map +1 -1
  80. package/dist/tools/annotations.mjs +1 -1
  81. package/dist/tools/availability.d.mts +36 -0
  82. package/dist/tools/availability.d.mts.map +1 -0
  83. package/dist/tools/availability.mjs +2 -0
  84. package/dist/{tsx-parser-CQc6nr-o.mjs → tsx-parser-B_aI_C2r.mjs} +1 -1
  85. package/dist/{tsx-parser-CQc6nr-o.mjs.map → tsx-parser-B_aI_C2r.mjs.map} +1 -1
  86. package/dist/tsx-parser-ChduVwKJ.mjs +2 -0
  87. package/dist/util/detect.mjs +1 -1
  88. package/dist/{validator-Z3DGNWQ6.mjs → validator-8vaPxSba.mjs} +1 -1
  89. package/dist/{validator-Z3DGNWQ6.mjs.map → validator-8vaPxSba.mjs.map} +1 -1
  90. package/dist/{vue-parser-COgjArqv.mjs → vue-parser-COig4Y1a.mjs} +3 -3
  91. package/dist/{vue-parser-COgjArqv.mjs.map → vue-parser-COig4Y1a.mjs.map} +1 -1
  92. package/package.json +10 -4
  93. package/dist/annotations-BFJbfSKe.mjs.map +0 -1
  94. package/dist/index-D0wQJSgs.d.mts +0 -2
  95. package/dist/server-DZBcZWhE.d.mts.map +0 -1
  96. package/dist/tsx-parser-BOMZE_yQ.mjs +0 -2
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["listBranchesOp","getDefaultBranchOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp"],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/apply-plan.ts","../../../src/providers/gitlab/branch-ops.ts","../../../src/providers/gitlab/reader.ts","../../../src/providers/gitlab/provider.ts","../../../src/providers/gitlab/factory.ts","../../../src/providers/gitlab/types.ts"],"sourcesContent":["import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitLabProvider.\n *\n * GitLab over REST has no working tree, so local worktree features,\n * source-file access and AST scans are unavailable. Push, merge and\n * branch-protection detection all work over the API. GitLab enforces\n * merges through merge requests, so `pullRequestFallback` is `true` —\n * `mergeBranch` opens an MR and auto-accepts it to match GitHub's\n * `repos.merge` semantics while still leaving an audit trail.\n */\nexport const GITLAB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\ntype CommitActionType = 'create' | 'update' | 'delete'\n\ninterface CommitAction {\n action: CommitActionType\n filePath: string\n content?: string\n encoding?: 'text' | 'base64'\n}\n\n/**\n * Apply a plan to a GitLab repository as a single atomic commit via the\n * Commits API. High-level flow:\n *\n * 1. Check whether the target branch exists. If it does not, GitLab's\n * `startBranch` option forks a new branch from `input.base` (or the\n * project's default branch) as part of the same commit.\n * 2. For each `FileChange`, figure out the right GitLab action verb\n * (`create` vs `update` vs `delete`) by probing the path against the\n * resolved ref. GitLab validates this server-side and returns a 400\n * for mismatches — we avoid the round trip by getting it right up\n * front.\n * 3. POST `/repository/commits` once with the full action set. No\n * working tree, no multi-call tree-assembly dance — GitLab exposes\n * a richer primitive than the GitHub Git Data API for this case.\n *\n * The commit is durable as soon as the call returns; GitLab's ref\n * update happens inside the same request.\n */\nexport async function applyPlanToGitLab(\n client: GitLabClient,\n project: ProjectRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const branchExists = await branchHasRef(client, project, input.branch)\n // Invariant: fork from the Contentrain content-tracking branch, not\n // the repo's default branch. See ApplyPlanInput.base docstring in\n // @contentrain/types.\n const baseBranch = input.base ?? CONTENTRAIN_BRANCH\n\n // Actions are computed against the HEAD of the feature branch when it\n // exists, otherwise against the fork point (baseBranch). GitLab\n // treats `create` / `update` / `delete` as a strict check against the\n // path's existence at that ref.\n const refForActionResolution = branchExists ? input.branch : baseBranch\n const rawActions = await Promise.all(\n input.changes.map(change => resolveAction(client, project, refForActionResolution, change)),\n )\n const actions = rawActions.filter((a): a is CommitAction => a !== null)\n\n if (actions.length === 0) {\n // Nothing to apply. Callers don't generally build empty plans, but\n // if they do we short-circuit before touching the API.\n throw new Error('applyPlanToGitLab: plan contained no applicable actions')\n }\n\n const options: Record<string, unknown> = {\n authorName: input.author.name,\n authorEmail: input.author.email,\n }\n if (!branchExists) {\n options.startBranch = baseBranch\n }\n\n const response = await client.Commits.create(\n project.projectId,\n input.branch,\n input.message,\n actions,\n options,\n )\n\n // Gitbeaker's generic-heavy response type widens string fields to\n // `string | Camelize<…>` — at runtime they are always strings under\n // the default (non-camelize) response mode we use. Cast narrows the\n // shape we actually touch.\n const commit = response as {\n id: string\n message?: string\n author_name?: string\n author_email?: string\n created_at?: string\n }\n const commitTimestamp = toIsoTimestamp(commit.created_at) ?? new Date().toISOString()\n return {\n sha: commit.id,\n message: commit.message ?? input.message,\n author: {\n name: commit.author_name ?? input.author.name,\n email: commit.author_email ?? input.author.email,\n },\n timestamp: commitTimestamp,\n }\n}\n\nasync function resolveAction(\n client: GitLabClient,\n project: ProjectRef,\n ref: string,\n change: FileChange,\n): Promise<CommitAction | null> {\n const filePath = resolveRepoPath(project.contentRoot, change.path)\n const exists = await fileExistsAtRef(client, project, filePath, ref)\n\n if (change.content === null) {\n // Filter out deletes against non-existent files — GitLab returns\n // 400 otherwise. The plan author asked us to \"make this file not\n // exist\", which is already satisfied.\n if (!exists) return null\n return { action: 'delete', filePath }\n }\n\n return {\n action: exists ? 'update' : 'create',\n filePath,\n content: change.content,\n encoding: 'text',\n }\n}\n\nasync function branchHasRef(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n): Promise<boolean> {\n try {\n await client.Branches.show(project.projectId, branch)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\nasync function fileExistsAtRef(\n client: GitLabClient,\n project: ProjectRef,\n filePath: string,\n ref: string,\n): Promise<boolean> {\n try {\n await client.RepositoryFiles.show(project.projectId, filePath, ref)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\n\nfunction toIsoTimestamp(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const date = new Date(raw)\n if (Number.isNaN(date.getTime())) return null\n return date.toISOString()\n}\n\n","import type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * Branch / merge / diff helpers backed by the GitLab REST API.\n *\n * Pure functions so they can be composed into `GitLabProvider` or used\n * standalone. 404s collapse to empty-ish results where that matches\n * the `RepoProvider` contract (missing branch prefix → `[]`).\n *\n * Merge semantics: GitLab does not expose a direct branch-to-branch\n * merge endpoint. Every merge flows through a merge request, so\n * `mergeBranch` opens an MR and immediately accepts it. The resulting\n * `MergeResult` mirrors GitHub's `repos.merge` return shape — callers\n * see the same `{ merged, sha, pullRequestUrl }` envelope either way,\n * with the MR URL available for audit.\n */\n\nexport async function getDefaultBranch(\n client: GitLabClient,\n project: ProjectRef,\n): Promise<string> {\n const p = await client.Projects.show(project.projectId) as { default_branch?: string }\n return p.default_branch ?? 'main'\n}\n\nexport async function listBranches(\n client: GitLabClient,\n project: ProjectRef,\n prefix?: string,\n): Promise<Branch[]> {\n // Gitbeaker's `all` supports a `search` string (substring match). For\n // Contentrain's `cr/*` naming the substring case is equivalent to a\n // prefix because the slug never appears anywhere except at the start.\n // Server-side filter + client-side prefix enforcement keeps us\n // correct even if the substring coincidence breaks someday.\n const options: Record<string, unknown> = {\n perPage: 100,\n maxPages: 10,\n }\n if (prefix) options.search = prefix\n\n const rawBranches = await client.Branches.all(project.projectId, options)\n const branches = Array.isArray(rawBranches) ? rawBranches : []\n\n return branches\n .filter((b: { name: string }) => !prefix || b.name.startsWith(prefix))\n .map((b: { name: string, commit: { id: string }, protected?: boolean }) => ({\n name: b.name,\n sha: b.commit.id,\n protected: b.protected ?? false,\n }))\n}\n\nexport async function createBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n await client.Branches.create(project.projectId, name, fromRef)\n}\n\nexport async function deleteBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n): Promise<void> {\n await client.Branches.remove(project.projectId, name)\n}\n\nexport async function getBranchDiff(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.Repositories.compare(\n project.projectId,\n base,\n branch,\n { straight: false },\n )\n const diffs = Array.isArray(response.diffs) ? response.diffs : []\n return diffs.map((d: { new_path: string, old_path: string, new_file?: boolean, deleted_file?: boolean }) => ({\n path: d.new_file ? d.new_path : d.old_path,\n status: d.deleted_file ? 'removed' : d.new_file ? 'added' : 'modified',\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult> {\n // 1. Open MR — GitLab rejects create when source === target or when\n // an MR is already open for this pair. Let the error propagate in\n // those cases; the caller retries or surfaces the message.\n const mr = await client.MergeRequests.create(\n project.projectId,\n branch,\n into,\n `[contentrain] merge ${branch} → ${into}`,\n { removeSourceBranch: false },\n )\n\n // 2. Accept the MR immediately. `shouldRemoveSourceBranch: false` keeps\n // GitLab's async server-side deletion out of the accept call — the\n // explicit cleanup below owns it, so the outcome is deterministic and\n // reported via `MergeResult.remote`.\n const accepted = await client.MergeRequests.accept(\n project.projectId,\n (mr as { iid: number }).iid,\n { shouldRemoveSourceBranch: false, squash: false },\n )\n\n const mergeSha = (accepted as { merge_commit_sha?: string | null, sha?: string | null }).merge_commit_sha\n ?? (accepted as { sha?: string | null }).sha\n ?? null\n const webUrl = (mr as { web_url?: string }).web_url ?? null\n const merged = mergeSha !== null\n\n // 3. Best-effort source-branch cleanup so merged cr/* branches don't\n // pile up on the remote. Opt out per call with\n // `removeSourceBranch: false` (e.g. a driver that owns cleanup\n // separately). Never throws — the merge itself already succeeded.\n let remote: MergeResult['remote']\n if (merged && opts?.removeSourceBranch !== false) {\n try {\n await deleteBranch(client, project, branch)\n remote = { deleted: true }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n remote = /404|not found/i.test(message)\n ? { deleted: false, skipped: 'not-found' }\n : { deleted: false, warning: `Could not delete \"${branch}\": ${message}` }\n }\n }\n\n return { merged, sha: mergeSha, pullRequestUrl: webUrl, ...(remote ? { remote } : {}) }\n}\n\nexport async function isMerged(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n // compare(from=into, to=branch) — commits list is empty when branch\n // is fully contained in into (i.e. already merged).\n const response = await client.Repositories.compare(\n project.projectId,\n into,\n branch,\n { straight: false },\n )\n const commits = Array.isArray(response.commits) ? response.commits : []\n return commits.length === 0\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabReader — `RepoReader` backed by the GitLab REST API.\n *\n * File reads go through `RepositoryFiles.showRaw`, which returns the\n * file content as UTF-8 text (or a `Blob` on browser/edge runtimes we\n * decode with `.text()`). Directory listings go through\n * `Repositories.allRepositoryTrees`. `fileExists` tries the file\n * endpoint first and falls back to a tree listing so directories\n * resolve to `true` as well — matching LocalReader / GitHubReader.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. Callers should always pass the explicit `contentrain`\n * tracking branch; GitLab's default resolution is the project's\n * default branch, which is usually wrong for Contentrain flows.\n */\nexport class GitLabReader implements RepoReader {\n constructor(\n private readonly client: GitLabClient,\n private readonly project: ProjectRef,\n ) {}\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n const raw = await this.client.RepositoryFiles.showRaw(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n if (typeof raw === 'string') return raw\n // Browser / edge runtimes return a Blob; decode as UTF-8.\n return (raw as Blob).text()\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n {\n path: repoPath,\n ref: resolvedRef,\n perPage: 100,\n recursive: false,\n },\n )\n return Array.isArray(entries) ? entries.map(e => e.name) : []\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n\n // 1. Try as a file — cheap and most common case for Contentrain.\n try {\n await this.client.RepositoryFiles.show(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n return true\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // 2. Fall back to a tree listing — directories and empty dirs show\n // up here. Any non-404 result means the path resolves.\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n { path: repoPath, ref: resolvedRef, perPage: 1 },\n )\n return Array.isArray(entries) && entries.length > 0\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n\n private async resolveDefaultRef(): Promise<string> {\n const project = await this.client.Projects.show(this.project.projectId) as { default_branch?: string }\n return project.default_branch ?? 'main'\n }\n}\n\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitLab } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITLAB_CAPABILITIES } from './capabilities.js'\nimport type { GitLabClient } from './client.js'\nimport { GitLabReader } from './reader.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabProvider — `RepoProvider` backed by the gitbeaker-driven GitLab\n * REST API.\n *\n * Transport-agnostic: the provider only talks to a `GitLabClient`\n * (a `@gitbeaker/rest` `Gitlab` instance). `createGitLabProvider` in\n * `factory.ts` wraps the dynamic import so consumers never touch\n * `@gitbeaker/rest` directly unless they want to.\n *\n * Capability gaps versus `GitHubProvider`: none — both providers\n * expose the same set. GitLab's merge flow routes through an MR under\n * the hood, but `mergeBranch` presents the same `MergeResult` shape.\n */\nexport class GitLabProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITLAB_CAPABILITIES\n private readonly reader: GitLabReader\n\n constructor(\n private readonly client: GitLabClient,\n public readonly project: ProjectRef,\n ) {\n this.reader = new GitLabReader(client, project)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitLab(this.client, this.project, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.project, prefix)\n }\n async createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? await getDefaultBranchOp(this.client, this.project)\n await createBranchOp(this.client, this.project, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.project, name)\n }\n async getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? await getDefaultBranchOp(this.client, this.project)\n return getBranchDiffOp(this.client, this.project, branch, resolved)\n }\n mergeBranch(branch: string, into: string, opts?: { removeSourceBranch?: boolean }): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.project, branch, into, opts)\n }\n async isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? await getDefaultBranchOp(this.client, this.project)\n return isMergedOp(this.client, this.project, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.project)\n }\n}\n","import type { GitLabClient } from './client.js'\nimport { GitLabProvider } from './provider.js'\nimport type { GitLabAuth, ProjectRef } from './types.js'\n\n/**\n * Create a gitbeaker-backed `GitLabClient` from an auth configuration.\n *\n * The `@gitbeaker/rest` module is imported dynamically so it stays a\n * pure optional peer dependency — self-hosted MCP on stdio runs fine\n * without it. If the module is not installed, the import throws with\n * a helpful hint pointing the operator at the peer dependency.\n *\n * Supported auth types: `pat`, `oauth`, `job`. All three are thin\n * wrappers over gitbeaker's `token`, `oauthToken`, and `jobToken`\n * constructor options.\n */\nexport async function createGitLabClient(\n auth: GitLabAuth,\n host?: string,\n): Promise<GitLabClient> {\n let GitlabCtor: typeof import('@gitbeaker/rest').Gitlab\n try {\n ({ Gitlab: GitlabCtor } = await import('@gitbeaker/rest'))\n } catch (error) {\n throw new Error(\n '@gitbeaker/rest is required for the GitLabProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @gitbeaker/rest.',\n { cause: error },\n )\n }\n\n const config: Record<string, unknown> = host ? { host } : {}\n switch (auth.type) {\n case 'pat':\n config.token = auth.token\n break\n case 'oauth':\n config.oauthToken = auth.oauthToken\n break\n case 'job':\n config.jobToken = auth.jobToken\n break\n default: {\n const { type } = auth as { type: string }\n throw new Error(`Unsupported GitLab auth type: \"${type}\"`)\n }\n }\n\n return new GitlabCtor(config) as GitLabClient\n}\n\n/**\n * Factory for the full provider — instantiates a gitbeaker client and\n * wraps it in a `GitLabProvider`. Consumers who already hold a\n * gitbeaker instance (HTTP server injecting shared clients, tests,\n * etc.) should instantiate `GitLabProvider` directly instead.\n */\nexport async function createGitLabProvider(\n opts: { auth: GitLabAuth, project: ProjectRef },\n): Promise<GitLabProvider> {\n const client = await createGitLabClient(opts.auth, opts.project.host)\n return new GitLabProvider(client, opts.project)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitLab project.\n *\n * `projectId` accepts the numeric project ID or a URL-encoded path\n * (`namespace/project`). Gitbeaker URL-encodes string paths internally,\n * so either form is fine.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain sits under `apps/web/.contentrain/` it holds that\n * prefix. All reader/writer paths are joined against it.\n *\n * `host` points at a self-hosted GitLab instance. Leave undefined to\n * use `https://gitlab.com` (gitbeaker's default).\n */\nexport interface ProjectRef {\n projectId: string | number\n contentRoot?: string\n host?: string\n}\n\n/**\n * Authentication options for the GitLab provider.\n *\n * - `pat` — personal access token with the `api` scope. Simplest for\n * self-hosted MCP or CI runners.\n * - `oauth` — OAuth2 token. Used when the runner is driven by a GitLab\n * OAuth flow.\n * - `job` — CI job token (`CI_JOB_TOKEN`). Scoped to the running\n * pipeline; useful for pipeline-driven content updates.\n */\nexport type GitLabAuth =\n | { type: 'pat', token: string }\n | { type: 'oauth', oauthToken: string }\n | { type: 'job', jobToken: string }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITLAB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,sBAA4C;CACvD,eAAe;CACf,YAAY;CACZ,aAAa;CACb,YAAY;CACZ,kBAAkB;CAClB,qBAAqB;CACrB,SAAS;CACV;;;;;;;;;;;;;;;;;;;;;;ACcD,eAAsB,kBACpB,QACA,SACA,OACiB;CACjB,MAAM,eAAe,MAAM,aAAa,QAAQ,SAAS,MAAM,OAAO;CAItE,MAAM,aAAa,MAAM,QAAQ;CAMjC,MAAM,yBAAyB,eAAe,MAAM,SAAS;C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Q,KAAK,QAAQ;;;;;;;;;;;;;;;;;ACpExD,eAAsB,mBACpB,MACA,MACuB;CACvB,IAAI;AACJ,KAAI;AACF,GAAC,CAAE,QAAQ,cAAe,MAAM,OAAO;UAChC,OAAO;AACd,QAAM,IAAI,MACR,0IAEA,EAAE,OAAO,OAAO,CACjB;;CAGH,MAAM,SAAkC,OAAO,EAAE,MAAM,GAAG,EAAE;AAC5D,SAAQ,KAAK,MAAb;EACE,KAAK;AACH,UAAO,QAAQ,KAAK;AACpB;EACF,KAAK;AACH,UAAO,aAAa,KAAK;AACzB;EACF,KAAK;AACH,UAAO,WAAW,KAAK;AACvB;EACF,SAAS;GACP,MAAM,EAAE,SAAS;AACjB,SAAM,IAAI,MAAM,kCAAkC,KAAK,GAAG;;;AAI9D,QAAO,IAAI,WAAW,OAAO;;;;;;;;AAS/B,eAAsB,qBACpB,MACyB;AAEzB,QAAO,IAAI,eADI,MAAM,mBAAmB,KAAK,MAAM,KAAK,QAAQ,KAAK,EACnC,KAAK,QAAQ;;;;;ACtBjD,MAAa,wBAAsC;CACjD,MAAM;CACN,OAAO;CACR"}
1
+ {"version":3,"file":"index.mjs","names":["listBranchesOp","getDefaultBranchOp","createBranchOp","deleteBranchOp","getBranchDiffOp","mergeBranchOp","isMergedOp"],"sources":["../../../src/providers/gitlab/capabilities.ts","../../../src/providers/gitlab/apply-plan.ts","../../../src/providers/gitlab/branch-ops.ts","../../../src/providers/gitlab/reader.ts","../../../src/providers/gitlab/provider.ts","../../../src/providers/gitlab/factory.ts","../../../src/providers/gitlab/types.ts"],"sourcesContent":["import type { ProviderCapabilities } from '../../core/contracts/index.js'\n\n/**\n * Capability set for GitLabProvider.\n *\n * GitLab over REST has no working tree, so local worktree features,\n * source-file access and AST scans are unavailable. Push, merge and\n * branch-protection detection all work over the API. GitLab enforces\n * merges through merge requests, so `pullRequestFallback` is `true` —\n * `mergeBranch` opens an MR and auto-accepts it to match GitHub's\n * `repos.merge` semantics while still leaving an audit trail.\n */\nexport const GITLAB_CAPABILITIES: ProviderCapabilities = {\n localWorktree: false,\n sourceRead: false,\n sourceWrite: false,\n pushRemote: true,\n branchProtection: true,\n pullRequestFallback: true,\n astScan: false,\n}\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { ApplyPlanInput, Commit, FileChange } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\ntype CommitActionType = 'create' | 'update' | 'delete'\n\ninterface CommitAction {\n action: CommitActionType\n filePath: string\n content?: string\n encoding?: 'text' | 'base64'\n}\n\n/**\n * Apply a plan to a GitLab repository as a single atomic commit via the\n * Commits API. High-level flow:\n *\n * 1. Check whether the target branch exists. If it does not, GitLab's\n * `startBranch` option forks a new branch from `input.base` (or the\n * project's default branch) as part of the same commit.\n * 2. For each `FileChange`, figure out the right GitLab action verb\n * (`create` vs `update` vs `delete`) by probing the path against the\n * resolved ref. GitLab validates this server-side and returns a 400\n * for mismatches — we avoid the round trip by getting it right up\n * front.\n * 3. POST `/repository/commits` once with the full action set. No\n * working tree, no multi-call tree-assembly dance — GitLab exposes\n * a richer primitive than the GitHub Git Data API for this case.\n *\n * The commit is durable as soon as the call returns; GitLab's ref\n * update happens inside the same request.\n */\nexport async function applyPlanToGitLab(\n client: GitLabClient,\n project: ProjectRef,\n input: ApplyPlanInput,\n): Promise<Commit> {\n const branchExists = await branchHasRef(client, project, input.branch)\n // Invariant: fork from the Contentrain content-tracking branch, not\n // the repo's default branch. See ApplyPlanInput.base docstring in\n // @contentrain/types.\n const baseBranch = input.base ?? CONTENTRAIN_BRANCH\n\n // Actions are computed against the HEAD of the feature branch when it\n // exists, otherwise against the fork point (baseBranch). GitLab\n // treats `create` / `update` / `delete` as a strict check against the\n // path's existence at that ref.\n const refForActionResolution = branchExists ? input.branch : baseBranch\n const rawActions = await Promise.all(\n input.changes.map(change => resolveAction(client, project, refForActionResolution, change)),\n )\n const actions = rawActions.filter((a): a is CommitAction => a !== null)\n\n if (actions.length === 0) {\n // Nothing to apply. Callers don't generally build empty plans, but\n // if they do we short-circuit before touching the API.\n throw new Error('applyPlanToGitLab: plan contained no applicable actions')\n }\n\n const options: Record<string, unknown> = {\n authorName: input.author.name,\n authorEmail: input.author.email,\n }\n if (!branchExists) {\n options.startBranch = baseBranch\n }\n\n const response = await client.Commits.create(\n project.projectId,\n input.branch,\n input.message,\n actions,\n options,\n )\n\n // Gitbeaker's generic-heavy response type widens string fields to\n // `string | Camelize<…>` — at runtime they are always strings under\n // the default (non-camelize) response mode we use. Cast narrows the\n // shape we actually touch.\n const commit = response as {\n id: string\n message?: string\n author_name?: string\n author_email?: string\n created_at?: string\n }\n const commitTimestamp = toIsoTimestamp(commit.created_at) ?? new Date().toISOString()\n return {\n sha: commit.id,\n message: commit.message ?? input.message,\n author: {\n name: commit.author_name ?? input.author.name,\n email: commit.author_email ?? input.author.email,\n },\n timestamp: commitTimestamp,\n }\n}\n\nasync function resolveAction(\n client: GitLabClient,\n project: ProjectRef,\n ref: string,\n change: FileChange,\n): Promise<CommitAction | null> {\n const filePath = resolveRepoPath(project.contentRoot, change.path)\n const exists = await fileExistsAtRef(client, project, filePath, ref)\n\n if (change.content === null) {\n // Filter out deletes against non-existent files — GitLab returns\n // 400 otherwise. The plan author asked us to \"make this file not\n // exist\", which is already satisfied.\n if (!exists) return null\n return { action: 'delete', filePath }\n }\n\n return {\n action: exists ? 'update' : 'create',\n filePath,\n content: change.content,\n encoding: 'text',\n }\n}\n\nasync function branchHasRef(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n): Promise<boolean> {\n try {\n await client.Branches.show(project.projectId, branch)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\nasync function fileExistsAtRef(\n client: GitLabClient,\n project: ProjectRef,\n filePath: string,\n ref: string,\n): Promise<boolean> {\n try {\n await client.RepositoryFiles.show(project.projectId, filePath, ref)\n return true\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n}\n\n\nfunction toIsoTimestamp(raw: unknown): string | null {\n if (typeof raw !== 'string') return null\n const date = new Date(raw)\n if (Number.isNaN(date.getTime())) return null\n return date.toISOString()\n}\n\n","import { CONTENTRAIN_BRANCH } from '@contentrain/types'\nimport type { Branch, FileDiff, MergeResult } from '../../core/contracts/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * Branch / merge / diff helpers backed by the GitLab REST API.\n *\n * Pure functions so they can be composed into `GitLabProvider` or used\n * standalone. 404s collapse to empty-ish results where that matches\n * the `RepoProvider` contract (missing branch prefix → `[]`).\n *\n * Merge semantics: GitLab does not expose a direct branch-to-branch\n * merge endpoint. Every merge flows through a merge request, so\n * `mergeBranch` opens an MR and immediately accepts it. The resulting\n * `MergeResult` mirrors GitHub's `repos.merge` return shape — callers\n * see the same `{ merged, sha, pullRequestUrl }` envelope either way,\n * with the MR URL available for audit.\n */\n\nexport async function getDefaultBranch(\n client: GitLabClient,\n project: ProjectRef,\n): Promise<string> {\n const p = await client.Projects.show(project.projectId) as { default_branch?: string }\n return p.default_branch ?? 'main'\n}\n\nexport async function listBranches(\n client: GitLabClient,\n project: ProjectRef,\n prefix?: string,\n): Promise<Branch[]> {\n // Gitbeaker's `all` supports a `search` string (substring match). For\n // Contentrain's `cr/*` naming the substring case is equivalent to a\n // prefix because the slug never appears anywhere except at the start.\n // Server-side filter + client-side prefix enforcement keeps us\n // correct even if the substring coincidence breaks someday.\n const options: Record<string, unknown> = {\n perPage: 100,\n maxPages: 10,\n }\n if (prefix) options.search = prefix\n\n const rawBranches = await client.Branches.all(project.projectId, options)\n const branches = Array.isArray(rawBranches) ? rawBranches : []\n\n return branches\n .filter((b: { name: string }) => !prefix || b.name.startsWith(prefix))\n .map((b: { name: string, commit: { id: string }, protected?: boolean }) => ({\n name: b.name,\n sha: b.commit.id,\n protected: b.protected ?? false,\n }))\n}\n\nexport async function createBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n fromRef: string,\n): Promise<void> {\n await client.Branches.create(project.projectId, name, fromRef)\n}\n\nexport async function deleteBranch(\n client: GitLabClient,\n project: ProjectRef,\n name: string,\n): Promise<void> {\n await client.Branches.remove(project.projectId, name)\n}\n\nexport async function getBranchDiff(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n base: string,\n): Promise<FileDiff[]> {\n const response = await client.Repositories.compare(\n project.projectId,\n base,\n branch,\n { straight: false },\n )\n const diffs = Array.isArray(response.diffs) ? response.diffs : []\n return diffs.map((d: { new_path: string, old_path: string, new_file?: boolean, deleted_file?: boolean }) => ({\n path: d.new_file ? d.new_path : d.old_path,\n status: d.deleted_file ? 'removed' : d.new_file ? 'added' : 'modified',\n before: null,\n after: null,\n }))\n}\n\nexport async function mergeBranch(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult> {\n // 1. Open MR — GitLab rejects create when source === target or when\n // an MR is already open for this pair. Let the error propagate in\n // those cases; the caller retries or surfaces the message.\n const mr = await client.MergeRequests.create(\n project.projectId,\n branch,\n into,\n `[contentrain] merge ${branch} → ${into}`,\n { removeSourceBranch: false },\n )\n\n // 2. Accept the MR immediately. `shouldRemoveSourceBranch: false` keeps\n // GitLab's async server-side deletion out of the accept call — the\n // explicit cleanup below owns it, so the outcome is deterministic and\n // reported via `MergeResult.remote`.\n const accepted = await client.MergeRequests.accept(\n project.projectId,\n (mr as { iid: number }).iid,\n { shouldRemoveSourceBranch: false, squash: false },\n )\n\n const mergeSha = (accepted as { merge_commit_sha?: string | null, sha?: string | null }).merge_commit_sha\n ?? (accepted as { sha?: string | null }).sha\n ?? null\n const webUrl = (mr as { web_url?: string }).web_url ?? null\n const merged = mergeSha !== null\n\n // 3. Source-branch cleanup — OPT-IN (`removeSourceBranch: true`). Like git\n // and GitLab's own merge, `mergeBranch` leaves the source alone by\n // default. Even when opted in, a long-lived branch is NEVER deleted:\n // not the merge target (`into`), not the `contentrain` content branch,\n // not the project's default branch. Mirrors the LocalProvider guard;\n // defends against head/base confusion and contentrain↔default flows.\n // Never throws — the merge itself already succeeded.\n const remote = merged ? await cleanupSourceBranch(client, project, branch, into, opts) : undefined\n\n return { merged, sha: mergeSha, pullRequestUrl: webUrl, ...(remote ? { remote } : {}) }\n}\n\n/**\n * Opt-in ({@link mergeBranch} `removeSourceBranch: true`) deletion of the\n * merged source branch, with the same guard as the GitHub provider and the\n * LocalProvider: never delete the merge target, the `contentrain` content\n * branch, or the project default branch — even when opted in. Fail-safe\n * skips the delete if the default branch cannot be resolved. Never throws.\n */\nasync function cleanupSourceBranch(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n opts?: { removeSourceBranch?: boolean },\n): Promise<MergeResult['remote'] | undefined> {\n if (opts?.removeSourceBranch !== true) return undefined\n\n if (branch === into || branch === CONTENTRAIN_BRANCH) {\n return { deleted: false, skipped: 'protected' }\n }\n try {\n if (branch === await getDefaultBranch(client, project)) {\n return { deleted: false, skipped: 'protected' }\n }\n } catch {\n return { deleted: false, skipped: 'protected' }\n }\n\n try {\n await deleteBranch(client, project, branch)\n return { deleted: true }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error)\n return /404|not found/i.test(message)\n ? { deleted: false, skipped: 'not-found' }\n : { deleted: false, warning: `Could not delete \"${branch}\": ${message}` }\n }\n}\n\nexport async function isMerged(\n client: GitLabClient,\n project: ProjectRef,\n branch: string,\n into: string,\n): Promise<boolean> {\n // compare(from=into, to=branch) — commits list is empty when branch\n // is fully contained in into (i.e. already merged).\n const response = await client.Repositories.compare(\n project.projectId,\n into,\n branch,\n { straight: false },\n )\n const commits = Array.isArray(response.commits) ? response.commits : []\n return commits.length === 0\n}\n","import type { RepoReader } from '../../core/contracts/index.js'\nimport { isNotFoundError, resolveRepoPath } from '../shared/index.js'\nimport type { GitLabClient } from './client.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabReader — `RepoReader` backed by the GitLab REST API.\n *\n * File reads go through `RepositoryFiles.showRaw`, which returns the\n * file content as UTF-8 text (or a `Blob` on browser/edge runtimes we\n * decode with `.text()`). Directory listings go through\n * `Repositories.allRepositoryTrees`. `fileExists` tries the file\n * endpoint first and falls back to a tree listing so directories\n * resolve to `true` as well — matching LocalReader / GitHubReader.\n *\n * `ref` is forwarded verbatim and may be a branch name, tag name or\n * commit SHA. Callers should always pass the explicit `contentrain`\n * tracking branch; GitLab's default resolution is the project's\n * default branch, which is usually wrong for Contentrain flows.\n */\nexport class GitLabReader implements RepoReader {\n constructor(\n private readonly client: GitLabClient,\n private readonly project: ProjectRef,\n ) {}\n\n async readFile(path: string, ref?: string): Promise<string> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n const raw = await this.client.RepositoryFiles.showRaw(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n if (typeof raw === 'string') return raw\n // Browser / edge runtimes return a Blob; decode as UTF-8.\n return (raw as Blob).text()\n }\n\n async listDirectory(path: string, ref?: string): Promise<string[]> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n {\n path: repoPath,\n ref: resolvedRef,\n perPage: 100,\n recursive: false,\n },\n )\n return Array.isArray(entries) ? entries.map(e => e.name) : []\n } catch (error) {\n if (isNotFoundError(error)) return []\n throw error\n }\n }\n\n async fileExists(path: string, ref?: string): Promise<boolean> {\n const repoPath = resolveRepoPath(this.project.contentRoot, path)\n const resolvedRef = ref ?? await this.resolveDefaultRef()\n\n // 1. Try as a file — cheap and most common case for Contentrain.\n try {\n await this.client.RepositoryFiles.show(\n this.project.projectId,\n repoPath,\n resolvedRef,\n )\n return true\n } catch (error) {\n if (!isNotFoundError(error)) throw error\n }\n\n // 2. Fall back to a tree listing — directories and empty dirs show\n // up here. Any non-404 result means the path resolves.\n try {\n const entries = await this.client.Repositories.allRepositoryTrees(\n this.project.projectId,\n { path: repoPath, ref: resolvedRef, perPage: 1 },\n )\n return Array.isArray(entries) && entries.length > 0\n } catch (error) {\n if (isNotFoundError(error)) return false\n throw error\n }\n }\n\n private async resolveDefaultRef(): Promise<string> {\n const project = await this.client.Projects.show(this.project.projectId) as { default_branch?: string }\n return project.default_branch ?? 'main'\n }\n}\n\n","import type {\n ApplyPlanInput,\n Branch,\n Commit,\n FileDiff,\n MergeResult,\n ProviderCapabilities,\n RepoProvider,\n} from '../../core/contracts/index.js'\nimport { applyPlanToGitLab } from './apply-plan.js'\nimport {\n createBranch as createBranchOp,\n deleteBranch as deleteBranchOp,\n getBranchDiff as getBranchDiffOp,\n getDefaultBranch as getDefaultBranchOp,\n isMerged as isMergedOp,\n listBranches as listBranchesOp,\n mergeBranch as mergeBranchOp,\n} from './branch-ops.js'\nimport { GITLAB_CAPABILITIES } from './capabilities.js'\nimport type { GitLabClient } from './client.js'\nimport { GitLabReader } from './reader.js'\nimport type { ProjectRef } from './types.js'\n\n/**\n * GitLabProvider — `RepoProvider` backed by the gitbeaker-driven GitLab\n * REST API.\n *\n * Transport-agnostic: the provider only talks to a `GitLabClient`\n * (a `@gitbeaker/rest` `Gitlab` instance). `createGitLabProvider` in\n * `factory.ts` wraps the dynamic import so consumers never touch\n * `@gitbeaker/rest` directly unless they want to.\n *\n * Capability gaps versus `GitHubProvider`: none — both providers\n * expose the same set. GitLab's merge flow routes through an MR under\n * the hood, but `mergeBranch` presents the same `MergeResult` shape.\n */\nexport class GitLabProvider implements RepoProvider {\n readonly capabilities: ProviderCapabilities = GITLAB_CAPABILITIES\n private readonly reader: GitLabReader\n\n constructor(\n private readonly client: GitLabClient,\n public readonly project: ProjectRef,\n ) {\n this.reader = new GitLabReader(client, project)\n }\n\n readFile(path: string, ref?: string): Promise<string> {\n return this.reader.readFile(path, ref)\n }\n listDirectory(path: string, ref?: string): Promise<string[]> {\n return this.reader.listDirectory(path, ref)\n }\n fileExists(path: string, ref?: string): Promise<boolean> {\n return this.reader.fileExists(path, ref)\n }\n\n applyPlan(input: ApplyPlanInput): Promise<Commit> {\n return applyPlanToGitLab(this.client, this.project, input)\n }\n\n listBranches(prefix?: string): Promise<Branch[]> {\n return listBranchesOp(this.client, this.project, prefix)\n }\n async createBranch(name: string, fromRef?: string): Promise<void> {\n const resolved = fromRef ?? await getDefaultBranchOp(this.client, this.project)\n await createBranchOp(this.client, this.project, name, resolved)\n }\n deleteBranch(name: string): Promise<void> {\n return deleteBranchOp(this.client, this.project, name)\n }\n async getBranchDiff(branch: string, base?: string): Promise<FileDiff[]> {\n const resolved = base ?? await getDefaultBranchOp(this.client, this.project)\n return getBranchDiffOp(this.client, this.project, branch, resolved)\n }\n mergeBranch(branch: string, into: string, opts?: { removeSourceBranch?: boolean }): Promise<MergeResult> {\n return mergeBranchOp(this.client, this.project, branch, into, opts)\n }\n async isMerged(branch: string, into?: string): Promise<boolean> {\n const resolved = into ?? await getDefaultBranchOp(this.client, this.project)\n return isMergedOp(this.client, this.project, branch, resolved)\n }\n getDefaultBranch(): Promise<string> {\n return getDefaultBranchOp(this.client, this.project)\n }\n}\n","import type { GitLabClient } from './client.js'\nimport { GitLabProvider } from './provider.js'\nimport type { GitLabAuth, ProjectRef } from './types.js'\n\n/**\n * Create a gitbeaker-backed `GitLabClient` from an auth configuration.\n *\n * The `@gitbeaker/rest` module is imported dynamically so it stays a\n * pure optional peer dependency — self-hosted MCP on stdio runs fine\n * without it. If the module is not installed, the import throws with\n * a helpful hint pointing the operator at the peer dependency.\n *\n * Supported auth types: `pat`, `oauth`, `job`. All three are thin\n * wrappers over gitbeaker's `token`, `oauthToken`, and `jobToken`\n * constructor options.\n */\nexport async function createGitLabClient(\n auth: GitLabAuth,\n host?: string,\n): Promise<GitLabClient> {\n let GitlabCtor: typeof import('@gitbeaker/rest').Gitlab\n try {\n ({ Gitlab: GitlabCtor } = await import('@gitbeaker/rest'))\n } catch (error) {\n throw new Error(\n '@gitbeaker/rest is required for the GitLabProvider but could not be loaded. '\n + 'Install it as a peer dependency: pnpm add @gitbeaker/rest.',\n { cause: error },\n )\n }\n\n const config: Record<string, unknown> = host ? { host } : {}\n switch (auth.type) {\n case 'pat':\n config.token = auth.token\n break\n case 'oauth':\n config.oauthToken = auth.oauthToken\n break\n case 'job':\n config.jobToken = auth.jobToken\n break\n default: {\n const { type } = auth as { type: string }\n throw new Error(`Unsupported GitLab auth type: \"${type}\"`)\n }\n }\n\n return new GitlabCtor(config) as GitLabClient\n}\n\n/**\n * Factory for the full provider — instantiates a gitbeaker client and\n * wraps it in a `GitLabProvider`. Consumers who already hold a\n * gitbeaker instance (HTTP server injecting shared clients, tests,\n * etc.) should instantiate `GitLabProvider` directly instead.\n */\nexport async function createGitLabProvider(\n opts: { auth: GitLabAuth, project: ProjectRef },\n): Promise<GitLabProvider> {\n const client = await createGitLabClient(opts.auth, opts.project.host)\n return new GitLabProvider(client, opts.project)\n}\n","import type { CommitAuthor } from '../../core/contracts/index.js'\n\n/**\n * A reference to a GitLab project.\n *\n * `projectId` accepts the numeric project ID or a URL-encoded path\n * (`namespace/project`). Gitbeaker URL-encodes string paths internally,\n * so either form is fine.\n *\n * `contentRoot` is the repo-relative directory prefix where Contentrain\n * content lives. For a flat content repo it stays `''`; for a monorepo\n * where Contentrain sits under `apps/web/.contentrain/` it holds that\n * prefix. All reader/writer paths are joined against it.\n *\n * `host` points at a self-hosted GitLab instance. Leave undefined to\n * use `https://gitlab.com` (gitbeaker's default).\n */\nexport interface ProjectRef {\n projectId: string | number\n contentRoot?: string\n host?: string\n}\n\n/**\n * Authentication options for the GitLab provider.\n *\n * - `pat` — personal access token with the `api` scope. Simplest for\n * self-hosted MCP or CI runners.\n * - `oauth` — OAuth2 token. Used when the runner is driven by a GitLab\n * OAuth flow.\n * - `job` — CI job token (`CI_JOB_TOKEN`). Scoped to the running\n * pipeline; useful for pipeline-driven content updates.\n */\nexport type GitLabAuth =\n | { type: 'pat', token: string }\n | { type: 'oauth', oauthToken: string }\n | { type: 'job', jobToken: string }\n\n/** Default author used when a call does not provide one. */\nexport const DEFAULT_GITLAB_AUTHOR: CommitAuthor = {\n name: 'Contentrain',\n email: 'ai@contentrain.io',\n}\n"],"mappings":";;;;;;;;;;;;;AAYA,MAAa,sBAA4C;CACvD,eAAe;CACf,YAAY;CACZ,aAAa;CACb,YAAY;CACZ,kBAAkB;CAClB,qBAAqB;CACrB,SAAS;CACV;;;;;;;;;;;;;;;;;;;;;;ACcD,eAAsB,kBACpB,QACA,SACA,OACiB;CACjB,MAAM,eAAe,MAAM,aAAa,QAAQ,SAAS,MAAM,OAAO;CAItE,MAAM,aAAa,MAAM,QAAQ;CAMjC,MAAM,yBAAyB,eAAe,MAAM,SAAS;CAI7D,MAAM,WAHa,MAAM,QAAQ,IAC/B,MAAM,QAAQ,KAAI,WAAU,cAAc,QAAQ,SAAS,wBAAwB,OAAO,CAAC,CAC5F,EAC0B,QAAQ,MAAyB,MAAM,KAAK;AAEvE,KAAI,QAAQ,WAAW,EAGrB,OAAM,IAAI,MAAM,0DAA0D;CAG5E,MAAM,UAAmC;EACvC,YAAY,MAAM,OAAO;EACzB,aAAa,MAAM,OAAO;EAC3B;AACD,KAAI,CAAC,aACH,SAAQ,cAAc;CAexB,MAAM,SAZW,MAAM,OAAO,QAAQ,OACpC,QAAQ,WACR,MAAM,QACN,MAAM,SACN,SACA,QACD;CAaD,MAAM,kBAAkB,eAAe,OAAO,WAAW,qBAAI,IAAI,MAAM,EAAC,aAAa;AACrF,QAAO;EACL,KAAK,OAAO;EACZ,SAAS,OAAO,WAAW,MAAM;EACjC,QAAQ;GACN,MAAM,OAAO,eAAe,MAAM,OAAO;GACzC,OAAO,OAAO,gBAAgB,MAAM,OAAO;GAC5C;EACD,WAAW;EACZ;;AAGH,eAAe,cACb,QACA,SACA,KACA,QAC8B;CAC9B,MAAM,WAAW,gBAAgB,QAAQ,aAAa,OAAO,KAAK;CAClE,MAAM,S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AAW,KAAK;AACvB;EACF,SAAS;GACP,MAAM,EAAE,SAAS;AACjB,SAAM,IAAI,MAAM,kCAAkC,KAAK,GAAG;;;AAI9D,QAAO,IAAI,WAAW,OAAO;;;;;;;;AAS/B,eAAsB,qBACpB,MACyB;AAEzB,QAAO,IAAI,eADI,MAAM,mBAAmB,KAAK,MAAM,KAAK,QAAQ,KAAK,EACnC,KAAK,QAAQ;;;;;ACtBjD,MAAa,wBAAsC;CACjD,MAAM;CACN,OAAO;CACR"}
@@ -1,4 +1,4 @@
1
- import { a as FileChange, c as MergeResult, d as RepoReader, i as CommitAuthor, l as ProviderCapabilities, n as Branch, o as FileDiff, r as Commit, u as RepoProvider } from "../../index-D0wQJSgs.mjs";
1
+ import { a as FileChange, c as MergeResult, d as RepoReader, i as CommitAuthor, l as ProviderCapabilities$1, n as Branch, o as FileDiff, r as Commit, u as RepoProvider } from "../../index-6yasXNLQ.mjs";
2
2
  import { SyncResult, WorkflowMode } from "@contentrain/types";
3
3
 
4
4
  //#region src/providers/local/types.d.ts
@@ -66,7 +66,7 @@ interface LocalApplyResult extends Commit {
66
66
  */
67
67
  declare class LocalProvider implements RepoProvider {
68
68
  readonly projectRoot: string;
69
- readonly capabilities: ProviderCapabilities;
69
+ readonly capabilities: ProviderCapabilities$1;
70
70
  private readonly reader;
71
71
  constructor(projectRoot: string);
72
72
  readFile(path: string, ref?: string): Promise<string>;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/providers/local/types.ts","../../../src/providers/local/provider.ts","../../../src/providers/local/reader.ts"],"mappings":";;;;;UAIiB,kBAAA;EACf,IAAA;EACA,KAAA;EACA,MAAA;EACA,OAAA;AAAA;;;;;;AAYF;;;;UAAiB,mBAAA;EAYL;EAVV,MAAA;EAY+B;EAV/B,OAAA,EAAS,UAAA;EAFT;EAIA,OAAA;EAFS;EAIT,MAAA,GAAS,YAAA;EAAT;EAEA,IAAA;EAAA;EAEA,OAAA,GAAU,kBAAA;EAAA;EAEV,gBAAA,GAAmB,YAAA;AAAA;AAAA,UAGJ,gBAAA,SAAyB,MAAA;EAHT;AAGjC;;;;;EAOE,cAAA;EAEA;EAAA,IAAA,GAAO,UAAA;EAEP;EAAA,OAAA;AAAA;;;;;AA5CF;;;;;;;;;;AAgBA;;;cCqBa,aAAA,YAAyB,YAAA;EAAA,SAIR,WAAA;EAAA,SAHnB,YAAA,EAAc,oBAAA;EAAA,iBACN,MAAA;cAEW,WAAA;EAI5B,QAAA,CAAS,IAAA,UAAc,GAAA,YAAe,OAAA;EAItC,aAAA,CAAc,IAAA,UAAc,GAAA,YAAe,OAAA;EAI3C,UAAA,CAAW,IAAA,UAAc,GAAA,YAAe,OAAA;EAIlC,SAAA,CAAU,KAAA,EAAO,mBAAA,GAAsB,OAAA,CAAQ,gBAAA;EA2BrD,YAAA,CAAa,MAAA,YAAkB,OAAA,CAAQ,MAAA;EAIjC,YAAA,CAAa,IAAA,UAAc,OAAA,YAAmB,OAAA;EAKpD,YAAA,CAAa,IAAA,WAAe,OAAA;EAI5B,aAAA,CAAc,MAAA,UAAgB,IAAA,YAAgB,OAAA,CAAQ,QAAA;EAKtD,WAAA,CAAY,MAAA,UAAgB,IAAA,WAAe,OAAA,CAAQ,WAAA;EAInD,QAAA,CAAS,MAAA,UAAgB,IAAA,YAAgB,OAAA;EAKzC,gBAAA,CAAA,GAAoB,OAAA;AAAA;;;;;;AD/GtB;;;;;;;;cEWa,WAAA,YAAuB,UAAA;EAAA,SACN,WAAA;cAAA,WAAA;EAEtB,QAAA,CAAS,IAAA,UAAc,IAAA,YAAgB,OAAA;EAIvC,aAAA,CAAc,IAAA,UAAc,IAAA,YAAgB,OAAA;EAQ5C,UAAA,CAAW,IAAA,UAAc,IAAA,YAAgB,OAAA;AAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/providers/local/types.ts","../../../src/providers/local/provider.ts","../../../src/providers/local/reader.ts"],"mappings":";;;;;UAIiB,kBAAA;EACf,IA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Ac,IAAA,UAAc,IAAA,YAAgB,OAAA;EAQ5C,UAAA,CAAW,IAAA,UAAc,IAAA,YAAgB,OAAA;AAAA"}
@@ -156,4 +156,4 @@ async function discoverFiles(projectRoot, options) {
156
156
  //#endregion
157
157
  export { classifyFile as a, autoDetectSourceDirs as i, SCAN_EXTENSIONS as n, discoverFiles as o, SCAN_IGNORE_DIRS as r, MAX_SCAN_FILES as t };
158
158
 
159
- //# sourceMappingURL=scan-config-jC6XmiqF.mjs.map
159
+ //# sourceMappingURL=scan-config-BGUflS8t.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"scan-config-jC6XmiqF.mjs","names":[],"sources":["../src/core/scan-config.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises'\nimport { join, extname, basename } from 'node:path'\nimport { pathExists } from '../util/fs.js'\n\n// ─── Shared Scan Constants ───\n\n/** File extensions to scan across all JS/TS ecosystem projects */\nexport const SCAN_EXTENSIONS = new Set([\n '.tsx', '.jsx', '.vue', '.ts', '.js', '.mjs', '.astro', '.svelte',\n])\n\n/** Directory names to always exclude from scanning */\nexport const SCAN_IGNORE_DIRS = new Set([\n // Package managers / deps\n 'node_modules', '.pnpm',\n // Build outputs\n 'dist', 'build', 'out', '.output',\n // Framework caches\n '.nuxt', '.next', '.svelte-kit', '.expo', '.turbo', '.parcel-cache', '.vercel', '.netlify',\n // Test / coverage\n 'coverage', '__tests__', '__mocks__',\n // VCS / IDE\n '.git', '.vscode', '.idea',\n // Contentrain\n '.contentrain',\n])\n\n/** Max files per scan operation */\nexport const MAX_SCAN_FILES = 500\n\n/** File patterns to skip regardless of extension */\nconst SKIP_FILE_RE = /\\.(test|spec)\\.[^.]+$|\\.d\\.ts$|\\.min\\.[^.]+$/\n\n// ─── File Classification ───\n// Covers: React, Next.js, Nuxt, Vue, Astro, SvelteKit, Remix,\n// React Native/Expo, NestJS, Express, Fastify, Koa, Hapi\n\n/** Directories that represent entry points / pages / screens */\nconst PAGE_DIR_NAMES = new Set([\n // Frontend routing\n 'pages', 'routes', 'screens', 'views',\n // Backend entry points\n 'controllers', 'handlers', 'resolvers',\n])\n\n/** Directories that represent reusable components / modules */\nconst COMPONENT_DIR_NAMES = new Set([\n // UI components\n 'components', 'ui', 'widgets', 'elements',\n // Feature modules\n 'features', 'modules',\n // Backend services\n 'services', 'providers',\n // Shared / common\n 'shared', 'common',\n])\n\n/** Directories that represent layouts / templates */\nconst LAYOUT_DIR_NAMES = new Set([\n 'layouts', 'templates',\n])\n\n/** Next.js App Router special files that are page-like */\nconst NEXTJS_PAGE_FILES = new Set([\n 'page.tsx', 'page.jsx', 'page.ts', 'page.js',\n 'layout.tsx', 'layout.jsx', 'layout.ts', 'layout.js',\n 'error.tsx', 'error.jsx',\n 'loading.tsx', 'loading.jsx',\n 'not-found.tsx', 'not-found.jsx',\n])\n\n/** Classify a file into page/component/layout/other based on path heuristics */\nexport function classifyFile(relPath: string): 'page' | 'component' | 'layout' | 'other' {\n const parts = relPath.split('/')\n const fileName = parts[parts.length - 1] ?? ''\n\n // Next.js App Router: files in app/ with special names are pages\n if (parts.includes('app') && NEXTJS_PAGE_FILES.has(fileName)) {\n return fileName.startsWith('layout') ? 'layout' : 'page'\n }\n\n // Check directory names in path (check layout first — more specific)\n for (const part of parts) {\n const lower = part.toLowerCase()\n if (LAYOUT_DIR_NAMES.has(lower)) return 'layout'\n if (PAGE_DIR_NAMES.has(lower)) return 'page'\n if (COMPONENT_DIR_NAMES.has(lower)) return 'component'\n }\n\n return 'other'\n}\n\n// ─── Source Directory Detection ───\n\n/** Common source directories across all JS/TS project types */\nconst AUTO_DETECT_DIRS = [\n // Standard source\n 'src', 'app', 'lib',\n // Frontend specific\n 'pages', 'components', 'layouts', 'views',\n // Mobile\n 'screens',\n // Backend\n 'modules', 'routes', 'controllers', 'services',\n // Shared\n 'features', 'shared', 'common',\n // Hooks / composables\n 'hooks', 'composables',\n // Stores\n 'stores',\n]\n\n/** Auto-detect which source directories exist in the project */\nexport async function autoDetectSourceDirs(projectRoot: string): Promise<string[]> {\n const found: string[] = []\n for (const dir of AUTO_DETECT_DIRS) {\n if (await pathExists(join(projectRoot, dir))) {\n found.push(dir)\n }\n }\n return found.length > 0 ? found : ['.']\n}\n\n// ─── File Discovery ───\n\nexport interface DiscoverFilesOptions {\n paths?: string[]\n include?: string[]\n exclude?: string[]\n}\n\n/**\n * Discover source files matching scan criteria.\n * Returns relative paths (relative to projectRoot).\n */\nexport async function discoverFiles(\n projectRoot: string,\n options?: DiscoverFilesOptions,\n): Promise<string[]> {\n const extensions = options?.include\n ? new Set(options.include.map(e => e.startsWith('.') ? e : `.${e}`))\n : SCAN_EXTENSIONS\n const extraExcludes = new Set(options?.exclude ?? [])\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n\n const files: string[] = []\n\n for (const dir of scanDirs) {\n const absDir = join(projectRoot, dir)\n if (!(await pathExists(absDir))) continue\n\n let entries: string[]\n try {\n entries = await readdir(absDir, { recursive: true }) as unknown as string[]\n } catch {\n continue\n }\n\n for (const entry of entries) {\n if (files.length >= MAX_SCAN_FILES) break\n\n const fileName = basename(entry)\n\n // Check if any path segment is excluded\n const pathSegments = entry.split('/')\n if (pathSegments.some(seg => SCAN_IGNORE_DIRS.has(seg) || extraExcludes.has(seg))) continue\n\n // Check extension\n if (!extensions.has(extname(fileName))) continue\n\n // Skip test/spec/declaration/minified files\n if (SKIP_FILE_RE.test(fileName)) continue\n\n files.push(join(dir, entry))\n }\n\n if (files.length >= MAX_SCAN_FILES) break\n }\n\n return files.toSorted((a, b) => a.localeCompare(b)).slice(0, MAX_SCAN_FILES)\n}\n"],"mappings":";;;;;AAOA,MAAa,kBAAkB,IAAI,IAAI;CACrC;CAAQ;CAAQ;CAAQ;CAAO;CAAO;CAAQ;CAAU;CACzD,CAAC;;AAGF,MAAa,mBAAmB,IAAI,IAAI;CAEtC;CAAgB;CAEhB;CAAQ;CAAS;CAAO;CAExB;CAAS;CAAS;CAAe;CAAS;CAAU;CAAiB;CAAW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,QAAQ,CAAC,IAAI;;;;;;AAezC,eAAsB,cACpB,aACA,SACmB;CACnB,MAAM,aAAa,SAAS,UACxB,IAAI,IAAI,QAAQ,QAAQ,KAAI,MAAK,EAAE,WAAW,IAAI,GAAG,IAAI,IAAI,IAAI,CAAC,GAClE;CACJ,MAAM,gBAAgB,IAAI,IAAI,SAAS,WAAW,EAAE,CAAC;CACrD,MAAM,WAAW,SAAS,SAAS,MAAM,qBAAqB,YAAY;CAE1E,MAAM,QAAkB,EAAE;AAE1B,MAAK,MAAM,OAAO,UAAU;EAC1B,MAAM,SAAS,KAAK,aAAa,IAAI;AACrC,MAAI,CAAE,MAAM,WAAW,OAAO,CAAG;EAEjC,IAAI;AACJ,MAAI;AACF,aAAU,MAAM,QAAQ,QAAQ,EAAE,WAAW,MAAM,CAAC;UAC9C;AACN;;AAGF,OAAK,MAAM,SAAS,SAAS;AAC3B,OAAI,MAAM,UAAA,IAA0B;GAEpC,MAAM,WAAW,SAAS,MAAM;AAIhC,OADqB,MAAM,MAAM,IAAI,CACpB,MAAK,QAAO,iBAAiB,IAAI,IAAI,IAAI,cAAc,IAAI,IAAI,CAAC,CAAE;AAGnF,OAAI,CAAC,WAAW,IAAI,QAAQ,SAAS,CAAC,CAAE;AAGxC,OAAI,aAAa,KAAK,SAAS,CAAE;AAEjC,SAAM,KAAK,KAAK,KAAK,MAAM,CAAC;;AAG9B,MAAI,MAAM,UAAA,IAA0B;;AAGtC,QAAO,MAAM,UAAU,GAAG,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC,MAAM,GAAA,IAAkB"}
1
+ {"version":3,"file":"scan-config-BGUflS8t.mjs","names":[],"sources":["../src/core/scan-config.ts"],"sourcesContent":["import { readdir } from 'node:fs/promises'\nimport { join, extname, basename } from 'node:path'\nimport { pathExists } from '../util/fs.js'\n\n// ─── Shared Scan Constants ───\n\n/** File extensions to scan across all JS/TS ecosystem projects */\nexport const SCAN_EXTENSIONS = new Set([\n '.tsx', '.jsx', '.vue', '.ts', '.js', '.mjs', '.astro', '.svelte',\n])\n\n/** Directory names to always exclude from scanning */\nexport const SCAN_IGNORE_DIRS = new Set([\n // Package managers / deps\n 'node_modules', '.pnpm',\n // Build outputs\n 'dist', 'build', 'out', '.output',\n // Framework caches\n '.nuxt', '.next', '.svelte-kit', '.expo', '.turbo', '.parcel-cache', '.vercel', '.netlify',\n // Test / coverage\n 'coverage', '__tests__', '__mocks__',\n // VCS / IDE\n '.git', '.vscode', '.idea',\n // Contentrain\n '.contentrain',\n])\n\n/** Max files per scan operation */\nexport const MAX_SCAN_FILES = 500\n\n/** File patterns to skip regardless of extension */\nconst SKIP_FILE_RE = /\\.(test|spec)\\.[^.]+$|\\.d\\.ts$|\\.min\\.[^.]+$/\n\n// ─── File Classification ───\n// Covers: React, Next.js, Nuxt, Vue, Astro, SvelteKit, Remix,\n// React Native/Expo, NestJS, Express, Fastify, Koa, Hapi\n\n/** Directories that represent entry points / pages / screens */\nconst PAGE_DIR_NAMES = new Set([\n // Frontend routing\n 'pages', 'routes', 'screens', 'views',\n // Backend entry points\n 'controllers', 'handlers', 'resolvers',\n])\n\n/** Directories that represent reusable components / modules */\nconst COMPONENT_DIR_NAMES = new Set([\n // UI components\n 'components', 'ui', 'widgets', 'elements',\n // Feature modules\n 'features', 'modules',\n // Backend services\n 'services', 'providers',\n // Shared / common\n 'shared', 'common',\n])\n\n/** Directories that represent layouts / templates */\nconst LAYOUT_DIR_NAMES = new Set([\n 'layouts', 'templates',\n])\n\n/** Next.js App Router special files that are page-like */\nconst NEXTJS_PAGE_FILES = new Set([\n 'page.tsx', 'page.jsx', 'page.ts', 'page.js',\n 'layout.tsx', 'layout.jsx', 'layout.ts', 'layout.js',\n 'error.tsx', 'error.jsx',\n 'loading.tsx', 'loading.jsx',\n 'not-found.tsx', 'not-found.jsx',\n])\n\n/** Classify a file into page/component/layout/other based on path heuristics */\nexport function classifyFile(relPath: string): 'page' | 'component' | 'layout' | 'other' {\n const parts = relPath.split('/')\n const fileName = parts[parts.length - 1] ?? ''\n\n // Next.js App Router: files in app/ with special names are pages\n if (parts.includes('app') && NEXTJS_PAGE_FILES.has(fileName)) {\n return fileName.startsWith('layout') ? 'layout' : 'page'\n }\n\n // Check directory names in path (check layout first — more specific)\n for (const part of parts) {\n const lower = part.toLowerCase()\n if (LAYOUT_DIR_NAMES.has(lower)) return 'layout'\n if (PAGE_DIR_NAMES.has(lower)) return 'page'\n if (COMPONENT_DIR_NAMES.has(lower)) return 'component'\n }\n\n return 'other'\n}\n\n// ─── Source Directory Detection ───\n\n/** Common source directories across all JS/TS project types */\nconst AUTO_DETECT_DIRS = [\n // Standard source\n 'src', 'app', 'lib',\n // Frontend specific\n 'pages', 'components', 'layouts', 'views',\n // Mobile\n 'screens',\n // Backend\n 'modules', 'routes', 'controllers', 'services',\n // Shared\n 'features', 'shared', 'common',\n // Hooks / composables\n 'hooks', 'composables',\n // Stores\n 'stores',\n]\n\n/** Auto-detect which source directories exist in the project */\nexport async function autoDetectSourceDirs(projectRoot: string): Promise<string[]> {\n const found: string[] = []\n for (const dir of AUTO_DETECT_DIRS) {\n if (await pathExists(join(projectRoot, dir))) {\n found.push(dir)\n }\n }\n return found.length > 0 ? found : ['.']\n}\n\n// ─── File Discovery ───\n\nexport interface DiscoverFilesOptions {\n paths?: string[]\n include?: string[]\n exclude?: string[]\n}\n\n/**\n * Discover source files matching scan criteria.\n * Returns relative paths (relative to projectRoot).\n */\nexport async function discoverFiles(\n projectRoot: string,\n options?: DiscoverFilesOptions,\n): Promise<string[]> {\n const extensions = options?.include\n ? new Set(options.include.map(e => e.startsWith('.') ? e : `.${e}`))\n : SCAN_EXTENSIONS\n const extraExcludes = new Set(options?.exclude ?? [])\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n\n const files: string[] = []\n\n for (const dir of scanDirs) {\n const absDir = join(projectRoot, dir)\n if (!(await pathExists(absDir))) continue\n\n let entries: string[]\n try {\n entries = await readdir(absDir, { recursive: true }) as unknown as string[]\n } catch {\n continue\n }\n\n for (const entry of entries) {\n if (files.length >= MAX_SCAN_FILES) break\n\n const fileName = basename(entry)\n\n // Check if any path segment is excluded\n const pathSegments = entry.split('/')\n if (pathSegments.some(seg => SCAN_IGNORE_DIRS.has(seg) || extraExcludes.has(seg))) continue\n\n // Check extension\n if (!extensions.has(extname(fileName))) continue\n\n // Skip test/spec/declaration/minified files\n if (SKIP_FILE_RE.test(fileName)) continue\n\n files.push(join(dir, entry))\n }\n\n if (files.length >= MAX_SCAN_FILES) break\n }\n\n return files.toSorted((a, b) => a.localeCompare(b)).slice(0, MAX_SCAN_FILES)\n}\n"],"mappings":";;;;;AAOA,MAAa,kBAAkB,IAAI,IAAI;CACrC;CAAQ;CAAQ;CAAQ;CAAO;CAAO;CAAQ;CAAU;CACzD,CAAC;;AAGF,MAAa,mBAAmB,IAAI,IAAI;CAEtC;CAAgB;CAEhB;CAAQ;CAAS;CAAO;CAExB;CAAS;CAAS;CAAe;CAAS;CAAU;CAAiB;CAAW;CAEhF;CAAY;CAAa;CAEzB;CAAQ;CAAW;CAEnB;CACD,CAAC;;AAGF,MAAa,iBAAiB;;AAG9B,MAAM,eAAe;;AAOrB,MAAM,iBAAiB,IAAI,IAAI;CAE7B;CAAS;CAAU;CAAW;CAE9B;CAAe;CAAY;CAC5B,CAAC;;AAGF,MAAM,sBAAsB,IAAI,IAAI;CAElC;CAAc;CAAM;CAAW;CAE/B;CAAY;CAEZ;CAAY;CAEZ;CAAU;CACX,CAAC;;AAGF,MAAM,mBAAmB,IAAI,IAAI,CAC/B,WAAW,YACZ,CAAC;;AAGF,MAAM,oBAAoB,IAAI,IAAI;CAChC;CAAY;CAAY;CAAW;CACnC;CAAc;CAAc;CAAa;CACzC;CAAa;CACb;CAAe;CACf;CAAiB;CAClB,CAAC;;AAGF,SAAgB,aAAa,SAA4D;CACvF,MAAM,QAAQ,QAAQ,MAAM,IAAI;CAChC,MAAM,WAAW,MAAM,MAAM,SAAS,MAAM;AAG5C,KAAI,MA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IhC,OADqB,MAAM,MAAM,IAAI,CACpB,MAAK,QAAO,iBAAiB,IAAI,IAAI,IAAI,cAAc,IAAI,IAAI,CAAC,CAAE;AAGnF,OAAI,CAAC,WAAW,IAAI,QAAQ,SAAS,CAAC,CAAE;AAGxC,OAAI,aAAa,KAAK,SAAS,CAAE;AAEjC,SAAM,KAAK,KAAK,KAAK,MAAM,CAAC;;AAG9B,MAAI,MAAM,UAAA,IAA0B;;AAGtC,QAAO,MAAM,UAAU,GAAG,MAAM,EAAE,cAAc,EAAE,CAAC,CAAC,MAAM,GAAA,IAAkB"}
@@ -1,6 +1,6 @@
1
1
  import { o as readText } from "./fs-DLbVB-Ek.mjs";
2
- import { i as autoDetectSourceDirs, o as discoverFiles } from "./scan-config-jC6XmiqF.mjs";
3
- import { t as parseTsx } from "./tsx-parser-CQc6nr-o.mjs";
2
+ import { i as autoDetectSourceDirs, o as discoverFiles } from "./scan-config-BGUflS8t.mjs";
3
+ import { t as parseTsx } from "./tsx-parser-B_aI_C2r.mjs";
4
4
  import { extname, join } from "node:path";
5
5
  //#region src/core/ast-scanner/pre-filter.ts
6
6
  const PURE_NUMBER_RE = /^-?\d+(\.\d+)?$/;
@@ -273,7 +273,7 @@ const ASTRO_EXTENSIONS = new Set([".astro"]);
273
273
  */
274
274
  async function loadVueParser() {
275
275
  try {
276
- return (await import("./vue-parser-COgjArqv.mjs")).parseVue;
276
+ return (await import("./vue-parser-COig4Y1a.mjs")).parseVue;
277
277
  } catch {
278
278
  return;
279
279
  }
@@ -284,7 +284,7 @@ async function loadVueParser() {
284
284
  */
285
285
  async function loadSvelteParser() {
286
286
  try {
287
- return (await import("./svelte-parser-Dr9mmZuk.mjs")).parseSvelte;
287
+ return (await import("./svelte-parser-Bll-1SK0.mjs")).parseSvelte;
288
288
  } catch {
289
289
  return;
290
290
  }
@@ -295,7 +295,7 @@ async function loadSvelteParser() {
295
295
  */
296
296
  async function loadAstroParser() {
297
297
  try {
298
- return (await import("./astro-parser-B-nLl0zE.mjs")).parseAstro;
298
+ return (await import("./astro-parser-BVoGjA6M.mjs")).parseAstro;
299
299
  } catch {
300
300
  return;
301
301
  }
@@ -601,4 +601,4 @@ async function scanSummary(projectRoot, options) {
601
601
  //#endregion
602
602
  export { scanSummary as n, scanCandidates as t };
603
603
 
604
- //# sourceMappingURL=scanner-DKMwc03k.mjs.map
604
+ //# sourceMappingURL=scanner-VOwrKLGC.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"scanner-DKMwc03k.mjs","names":[],"sources":["../src/core/ast-scanner/pre-filter.ts","../src/core/ast-scanner/index.ts","../src/core/scanner.ts"],"sourcesContent":["import type { ExtractedString } from './types.js'\n\n// ─── Pre-filter Result ───\n\nexport interface PreFilterResult {\n /** Strings that passed the pre-filter (candidates for agent) */\n candidates: ExtractedString[]\n /** Total number of strings removed by shouldSkip */\n skipped: number\n /** Total number of strings removed by low content score */\n lowConfidence: number\n /** Breakdown: skip reason → count */\n skipReasons: Record<string, number>\n}\n\n// ─── Value-based regexes ───\n\nconst PURE_NUMBER_RE = /^-?\\d+(\\.\\d+)?$/\nconst HEX_COLOR_RE = /^#[0-9a-f]{3,8}$/i\nconst FILE_EXT_RE = /\\.(png|jpg|jpeg|gif|svg|webp|ico|css|scss|less|js|ts|tsx|jsx|json|md|html|xml|yaml|yml|woff|woff2|ttf|eot|mp4|webm|mp3|wav|pdf)$/i\nconst SVG_PATH_DATA_RE = /^[Mm][\\d\\s.,LHVCSQTAZlhvcsqtazmMzZ-]+$/\nconst SVG_VIEWBOX_RE = /^\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?$/\nconst I18N_KEY_RE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$/\nconst TECHNICAL_IDENTIFIER_RE = /^[_a-z][a-z0-9_-]*$/\nconst ERROR_CODE_RE = /^[A-Z][A-Z0-9_]+$/\nconst PLACEHOLDER_RE = /^\\{\\d+\\}$|^\\.{2,}$/\nconst CAMEL_CASE_RE = /^[a-z]+[A-Z]/\nconst LOCALE_CODE_RE = /^[a-z]{2}[-_][A-Z]{2}$/\nconst DIMENSION_RE = /^\\d+[x×]\\d+$/\nconst REPEAT_CHAR_RE = /^(.)\\1{3,}$/\nconst MIME_TYPE_RE = /^(application|text|image|audio|video|multipart|font)\\/[\\w.+-]+$/\nconst PASCAL_CASE_RE = /^[A-Z][a-z]+[A-Z]/\n\nconst HTML_TARGETS = new Set(['_blank', '_self', '_parent', '_top'])\n\n// ─── URL / path detection (consolidated from legacy isNonContent) ───\n\nfunction isURLLike(str: string): boolean {\n if (/^(https?|ftp|file|mailto|data):/.test(str)) return true\n if (/^(\\.\\.?\\/|\\/|[A-Za-z]:\\\\)/.test(str)) return true\n if (/^['\"]?[@a-z][\\w-]*/.test(str.toLowerCase()) && !str.includes(' ') && (str.includes('/') || str.includes('.'))) {\n return true\n }\n return false\n}\n\n// ─── CSS / Tailwind detection ───\n\nconst TAILWIND_SEGMENT_RE = /^(?:bg-|text-|border-|flex|grid|p-|px-|py-|pt-|pb-|pl-|pr-|m-|mx-|my-|mt-|mb-|ml-|mr-|rounded|shadow|w-|h-|min-|max-|gap-|space-|items-|justify-|self-|overflow-|z-|opacity-|transition|duration-|ease-|animate-|font-|leading-|tracking-|decoration-|underline|line-through|uppercase|lowercase|capitalize|truncate|whitespace-|break-|sr-only|not-sr-only|hover:|focus:|active:|disabled:|dark:|sm:|md:|lg:|xl:|2xl:|group-|peer-|ring-|outline-|divide-|table-|col-|row-|aspect-|object-|inset-|top-|right-|bottom-|left-|translate-|rotate-|scale-|skew-|origin-|cursor-|select-|resize-|fill-|stroke-|block|inline|absolute|relative|fixed|sticky|static|float-|clear-|isolate|visible|invisible|grow|shrink|basis-|order-|place-)/\n\nfunction isCssClassList(value: string): boolean {\n const segments = value.trim().split(/\\s+/)\n if (segments.length < 2) return false\n let matched = 0\n for (const seg of segments) {\n if (TAILWIND_SEGMENT_RE.test(seg)) matched++\n }\n return matched / segments.length >= 0.5\n}\n\nfunction isSingleCssUtility(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.includes(' ')) return false\n return TAILWIND_SEGMENT_RE.test(trimmed)\n}\n\n// ─── SVG technical attributes ───\n\nconst SVG_TECHNICAL_ATTRIBUTES = new Set([\n 'd', 'viewBox', 'points', 'transform', 'pathLength',\n 'xmlns', 'preserveAspectRatio',\n 'stroke-linecap', 'stroke-linejoin', 'stroke-width',\n 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit',\n 'fill-rule', 'clip-rule',\n])\n\nconst SVG_GRAPHIC_ELEMENTS = new Set([\n 'svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon',\n 'ellipse', 'g', 'defs', 'use', 'symbol', 'clipPath', 'mask',\n 'pattern', 'linearGradient', 'radialGradient', 'stop',\n 'marker', 'animate', 'animateTransform', 'image',\n])\n\n// ─── Known function names ───\n\nconst I18N_FUNCTIONS = new Set([\n 't', '$t', 'i18n', 'translate', 'formatMessage', 'msg',\n])\n\nconst EMIT_FUNCTIONS = new Set([\n 'emit', '$emit',\n])\n\n// ─── Translatable attribute whitelist (i18next-cli compatible + extended) ───\n\nconst TRANSLATABLE_ATTRIBUTES = new Set([\n // Standard HTML content attributes\n 'title', 'alt', 'placeholder', 'label', 'summary', 'caption',\n 'abbr', 'accesskey', 'content', 'description',\n // ARIA content\n 'aria-label', 'aria-description', 'aria-placeholder',\n 'aria-roledescription', 'aria-valuetext',\n // React Native accessibility (equivalent to aria-label)\n 'accessibilityLabel', 'accessibilityHint', 'accessibilityValue',\n // Common component content props\n 'heading', 'subheading', 'message', 'hint', 'tooltip',\n 'helper-text', 'error-message', 'success-message',\n 'confirm-text', 'cancel-text', 'empty-text', 'loading-text',\n 'no-data-text', 'no-results-text',\n])\n\n// ─── Translatable object property whitelist (i18next-cli compatible) ───\n\nconst TRANSLATABLE_PROPERTIES = new Set([\n 'label', 'title', 'description', 'text', 'message', 'placeholder',\n 'caption', 'summary', 'heading', 'subheading', 'subtitle', 'tooltip',\n 'hint', 'helpText', 'errorMessage', 'successMessage', 'name',\n])\n\n// ─── shouldSkip: Binary non-content detection ───\n\n/**\n * Determines if a string is definitely NOT user-visible content.\n * Returns skip reason if it should be filtered, null if it should proceed to scoring.\n *\n * Conservative for template_text/jsx_text (tag-between text is almost always content).\n * Aggressive for everything else (technical tokens, config values, framework artifacts).\n */\nexport function shouldSkip(str: ExtractedString): string | null {\n // ── Context-based rules (AST-determined, 100% accurate) ──\n\n if (str.context === 'import_path') return 'import_path'\n if (str.context === 'type_annotation') return 'type_annotation'\n if (str.context === 'css_class') return 'css_class'\n if (str.context === 'css_utility_call') return 'css_utility_call'\n if (str.context === 'console_call') return 'console_call'\n if (str.context === 'test_assertion') return 'test_assertion'\n if (str.context === 'switch_case') return 'switch_case'\n\n const v = str.value\n\n // ── Value-based rules (structural patterns) ──\n\n if (v.length <= 1) return 'single_char'\n if (/^\\s+$/.test(v)) return 'whitespace'\n if (PURE_NUMBER_RE.test(v)) return 'pure_number'\n if (HEX_COLOR_RE.test(v)) return 'hex_color'\n if (FILE_EXT_RE.test(v)) return 'file_extension'\n if (v.startsWith('--')) return 'cli_flag'\n\n // ── i18n key paths (checked before URL — both contain dots, but i18n keys are more specific) ──\n\n if (I18N_KEY_RE.test(v)) return 'i18n_key'\n\n // ── MIME types (checked before URL — both contain slash, MIME is more specific) ──\n\n if (MIME_TYPE_RE.test(v)) return 'mime_type'\n\n // ── URL/path patterns ──\n\n if (isURLLike(v)) return 'url_path'\n\n // ── CSS patterns ──\n\n if (isCssClassList(v)) return 'css_class_list'\n if (isSingleCssUtility(v)) return 'css_utility_token'\n\n // ── SVG patterns ──\n\n if (v.length > 3 && SVG_PATH_DATA_RE.test(v)) return 'svg_path_data'\n if (SVG_VIEWBOX_RE.test(v)) return 'svg_viewbox'\n if (str.parentProperty !== undefined && SVG_TECHNICAL_ATTRIBUTES.has(str.parentProperty)) return 'svg_technical_attr'\n if (str.context === 'template_attribute' && SVG_GRAPHIC_ELEMENTS.has(str.parent)) return 'svg_element_attr'\n\n // ── Framework event patterns ──\n\n if (v.startsWith('update:')) return 'vue_emit_event'\n\n // ── Placeholder / interpolation ──\n\n if (PLACEHOLDER_RE.test(v)) return 'placeholder'\n\n // ── Structural value patterns (100% non-content) ──\n\n if (LOCALE_CODE_RE.test(v)) return 'locale_code'\n if (DIMENSION_RE.test(v)) return 'dimension'\n if (REPEAT_CHAR_RE.test(v)) return 'repeat_chars'\n if (HTML_TARGETS.has(v)) return 'html_target'\n\n // ── Known function argument detection ──\n\n if (str.context === 'function_argument' && I18N_FUNCTIONS.has(str.parent)) {\n // i18n function args: filter lowercase identifiers (namespace/key), keep sentences\n if (/^[a-z][a-z0-9_.-]*$/.test(v)) return 'i18n_function_arg'\n }\n\n if (str.context === 'function_argument' && EMIT_FUNCTIONS.has(str.parent)) {\n return 'emit_event_arg'\n }\n\n // ── CRITICAL: Technical identifier detection (i18next-cli proven pattern) ──\n // Single lowercase ASCII word/kebab-case/snake_case < 30 chars → technical token\n // EXEMPT: template_text and jsx_text (tag-between text IS content, even lowercase)\n\n if (str.context !== 'template_text' && str.context !== 'jsx_text') {\n if (TECHNICAL_IDENTIFIER_RE.test(v) && v.length < 30) {\n return 'technical_identifier'\n }\n }\n\n // ── Error codes (SCREAMING_SNAKE_CASE with underscores) ──\n\n if (ERROR_CODE_RE.test(v) && v.includes('_') && v.length > 3) {\n return 'error_code'\n }\n\n return null\n}\n\n// ─── calculateContentScore: 0-1 confidence scoring ───\n\n/**\n * Calculates a content confidence score (0-1) for a string that passed shouldSkip.\n * Uses AST context metadata (our advantage over offset-based tools) combined with\n * value-based signals proven by i18next-cli.\n *\n * Base score: 0.5. Boosted/penalized by context and value characteristics.\n */\nexport function calculateContentScore(str: ExtractedString): number {\n let score = 0.5\n\n // ── Context signals (AST metadata advantage) ──\n\n // Template/JSX text = almost certainly user-visible content\n if (str.context === 'template_text' || str.context === 'jsx_text') {\n score += 0.3\n }\n\n // Content-bearing attribute (title, alt, placeholder, aria-label, etc.)\n if (str.context === 'template_attribute' || str.context === 'jsx_attribute') {\n if (str.parentProperty && TRANSLATABLE_ATTRIBUTES.has(str.parentProperty)) {\n score += 0.2\n } else {\n score -= 0.2 // Unknown/technical attribute\n }\n }\n\n // Content-bearing object property (message, label, description, etc.)\n if (str.context === 'object_property') {\n if (str.parentProperty && TRANSLATABLE_PROPERTIES.has(str.parentProperty)) {\n score += 0.25\n }\n }\n\n // ── Value signals (i18next-cli proven heuristics) ──\n\n // Multi-word strings are more likely content\n const wordCount = str.value.split(/\\s+/).length\n if (wordCount >= 3) score += 0.2\n else if (wordCount === 2) score += 0.1\n\n // Terminal punctuation suggests a sentence\n if (/[.!?:;]$/.test(str.value)) score += 0.1\n\n // Non-ASCII characters (Turkish, Chinese, Arabic, etc.) → almost certainly content\n if (/[\\u0080-\\uFFFF]/.test(str.value)) score += 0.15\n\n // Capitalized first letter with lowercase body (Dashboard, Kaydet, Settings)\n if (/^[A-Z]/.test(str.value) && /[a-z]/.test(str.value)) score += 0.1\n\n // camelCase → probably a technical identifier\n if (CAMEL_CASE_RE.test(str.value)) score -= 0.3\n\n // PascalCase with internal uppercase (PhGameController, GameCard) → likely component/icon name\n // Does NOT match single-uppercase words (Dashboard, Karadeniz, Settings)\n if (PASCAL_CASE_RE.test(str.value) && !str.value.includes(' ')) score -= 0.25\n\n // Short ALL-CAPS (TRY, GET, USD) → likely code/abbreviation, not content\n // In template_text the +0.3 context boost keeps real labels like \"FAQ\" above threshold\n if (/^[A-Z]{2,5}$/.test(str.value)) score -= 0.15\n\n // Contains slash without spaces → path-like\n if (str.value.includes('/') && !str.value.includes(' ')) score -= 0.2\n\n return Math.max(0, Math.min(1, score))\n}\n\n// ─── Public API ───\n\n/**\n * Two-phase pre-filter:\n * 1. shouldSkip(): Binary removal of definite non-content\n * 2. calculateContentScore(): 0-1 confidence scoring for ambiguous strings\n *\n * Returns candidates that passed both phases, with content scores attached.\n */\nexport function applyPreFilter(\n strings: ExtractedString[],\n minScore: number = 0.4,\n): PreFilterResult {\n const candidates: ExtractedString[] = []\n const skipReasons: Record<string, number> = {}\n let skipped = 0\n let lowConfidence = 0\n\n for (const str of strings) {\n // Phase 1: Binary skip\n const skipReason = shouldSkip(str)\n if (skipReason) {\n skipped++\n skipReasons[skipReason] = (skipReasons[skipReason] ?? 0) + 1\n continue\n }\n\n // Phase 2: Content scoring\n const contentScore = calculateContentScore(str)\n if (contentScore < minScore) {\n lowConfidence++\n skipReasons['low_confidence'] = (skipReasons['low_confidence'] ?? 0) + 1\n continue\n }\n\n // Attach score to the extraction for downstream use\n ;(str as ExtractedString & { contentScore: number }).contentScore = contentScore\n candidates.push(str)\n }\n\n return { candidates, skipped, lowConfidence, skipReasons }\n}\n","import type { ExtractedString } from './types.js'\nimport { applyPreFilter } from './pre-filter.js'\nimport { parseTsx } from './tsx-parser.js'\n\n// ─── Extension sets ───\n\nconst TSX_EXTENSIONS = new Set(['.tsx', '.jsx', '.ts', '.js', '.mjs'])\nconst VUE_EXTENSIONS = new Set(['.vue'])\nconst SVELTE_EXTENSIONS = new Set(['.svelte'])\nconst ASTRO_EXTENSIONS = new Set(['.astro'])\n\n// ─── Lazy-loaded parsers ───\n\n/**\n * Lazily import vue-parser. Returns undefined if not available\n * (@vue/compiler-sfc is an optional dependency).\n */\nasync function loadVueParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]> | ExtractedString[]) | undefined> {\n try {\n const mod = await import('./vue-parser.js')\n return mod.parseVue\n } catch {\n return undefined\n }\n}\n\n/**\n * Lazily import svelte-parser. Returns undefined if not available\n * (svelte is an optional dependency).\n */\nasync function loadSvelteParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]>) | undefined> {\n try {\n const mod = await import('./svelte-parser.js')\n return mod.parseSvelte\n } catch {\n return undefined\n }\n}\n\n/**\n * Lazily import astro-parser. Returns undefined if not available\n * (@astrojs/compiler is an optional dependency).\n */\nasync function loadAstroParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]>) | undefined> {\n try {\n const mod = await import('./astro-parser.js')\n return mod.parseAstro\n } catch {\n return undefined\n }\n}\n\n// ─── Regex fallback for unknown extensions ───\n\nconst SURROUNDING_MAX = 120\n\n/**\n * Minimal regex-based extractor for file types without AST parsers.\n * Extracts quoted strings and tag text — conservative, low accuracy.\n * Used as fallback when dedicated parsers are unavailable.\n */\nfunction extractWithRegex(content: string, _filePath: string): ExtractedString[] {\n const lines = content.split('\\n')\n const results: ExtractedString[] = []\n\n // Simple quoted string extraction\n const stringRe = /(['\"`])(?:(?!\\1|\\\\).|\\\\.)*?\\1/g\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n const trimmed = line.trim()\n\n // Skip comments, imports\n if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*')) continue\n if (/^\\s*(import|export)\\s/.test(line)) continue\n\n let match: RegExpExecArray | null\n stringRe.lastIndex = 0\n\n while ((match = stringRe.exec(line)) !== null) {\n // Remove surrounding quotes\n const raw = match[0]\n const value = raw.slice(1, -1)\n if (value.length === 0) continue\n\n const surrounding = buildSurrounding(lines, i)\n\n results.push({\n value,\n line: i + 1,\n column: match.index + 1,\n context: 'other',\n scope: 'script',\n parent: '',\n surrounding,\n })\n }\n\n // Tag text extraction: >text<\n const tagTextRe = />([^<>{]+)</g\n let tagMatch: RegExpExecArray | null\n tagTextRe.lastIndex = 0\n\n while ((tagMatch = tagTextRe.exec(line)) !== null) {\n const text = tagMatch[1]!.trim()\n if (text.length === 0) continue\n if (/^[\\s\\W]*$/.test(text) && !/[a-zA-Z]/.test(text)) continue\n\n results.push({\n value: text,\n line: i + 1,\n column: tagMatch.index + 1,\n context: 'template_text',\n scope: 'template',\n parent: '',\n surrounding: buildSurrounding(lines, i),\n })\n }\n }\n\n return results\n}\n\nfunction buildSurrounding(lines: string[], lineIdx: number): string {\n const start = Math.max(0, lineIdx - 1)\n const end = Math.min(lines.length - 1, lineIdx + 1)\n\n const parts: string[] = []\n for (let i = start; i <= end; i++) {\n const line = lines[i]\n if (line !== undefined) {\n parts.push(line)\n }\n }\n\n const joined = parts.join('\\n')\n if (joined.length > SURROUNDING_MAX) {\n return joined.slice(0, SURROUNDING_MAX)\n }\n return joined\n}\n\n// ─── Public API ───\n\n/**\n * Extract strings from a source file with structural context.\n *\n * Routes to the correct parser based on file extension:\n * - .tsx/.jsx/.ts/.js/.mjs -> tsx-parser (AST-based)\n * - .vue -> vue-parser (lazy-loaded, AST-based)\n * - .svelte -> svelte-parser (lazy-loaded, AST-based)\n * - .astro -> astro-parser (lazy-loaded, AST-based)\n * - unknown -> empty array\n *\n * Falls back to regex extraction when the dedicated parser's\n * optional dependency is not installed.\n *\n * Applies structural pre-filter to remove 100% non-content strings.\n * Returns only candidates that should be sent to the agent.\n */\nexport async function extractStrings(\n filePath: string,\n content: string,\n ext: string,\n): Promise<ExtractedString[]> {\n const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`\n let rawStrings: ExtractedString[]\n\n if (TSX_EXTENSIONS.has(normalizedExt)) {\n rawStrings = parseTsx(content, filePath)\n } else if (VUE_EXTENSIONS.has(normalizedExt)) {\n const parseVue = await loadVueParser()\n if (parseVue) {\n rawStrings = await parseVue(content, filePath)\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else if (SVELTE_EXTENSIONS.has(normalizedExt)) {\n const parseSvelte = await loadSvelteParser()\n if (parseSvelte) {\n try {\n rawStrings = await parseSvelte(content, filePath)\n } catch {\n // svelte/compiler not installed — fall back to regex\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else if (ASTRO_EXTENSIONS.has(normalizedExt)) {\n const parseAstro = await loadAstroParser()\n if (parseAstro) {\n try {\n rawStrings = await parseAstro(content, filePath)\n } catch {\n // @astrojs/compiler not installed — fall back to regex\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n return []\n }\n\n // Apply structural pre-filter\n const { candidates } = applyPreFilter(rawStrings)\n return candidates\n}\n\n// Re-export types for convenience\nexport type { ExtractedString, StructuralContext, PreFilterRule } from './types.js'\nexport { applyPreFilter, shouldSkip, calculateContentScore } from './pre-filter.js'\nexport type { PreFilterResult } from './pre-filter.js'\n","import type {\n StringContext,\n ScanCandidate,\n DuplicateGroup,\n ScanCandidatesResult,\n ScanSummaryResult,\n} from '@contentrain/types'\nimport { join, extname } from 'node:path'\nimport { readText } from '../util/fs.js'\nimport {\n autoDetectSourceDirs,\n discoverFiles,\n} from './scan-config.js'\nimport { extractStrings } from './ast-scanner/index.js'\nimport { calculateContentScore } from './ast-scanner/pre-filter.js'\nimport type { StructuralContext } from './ast-scanner/types.js'\n\n// ─── Options ───\n\nexport interface ScanOptions {\n paths?: string[]\n include?: string[]\n exclude?: string[]\n limit?: number\n offset?: number\n min_length?: number\n max_length?: number\n /** Minimum content confidence score (0-1). Default: 0.4 */\n min_score?: number\n}\n\n// ─── Constants ───\n\nconst DEFAULT_LIMIT = 50\nconst DEFAULT_OFFSET = 0\nconst DEFAULT_MIN_LENGTH = 2\nconst DEFAULT_MAX_LENGTH = 500\nconst DEFAULT_MIN_SCORE = 0.4\nconst SUMMARY_SAMPLE_SIZE = 10\n\n// ─── Context mapping: StructuralContext → StringContext ───\n\nconst CONTEXT_MAP: Record<StructuralContext, StringContext> = {\n 'template_text': 'template_text',\n 'template_attribute': 'template_attribute',\n 'jsx_text': 'jsx_text',\n 'jsx_attribute': 'jsx_attribute',\n 'variable_assignment': 'variable_assignment',\n 'object_property': 'object_value',\n 'function_argument': 'function_argument',\n 'array_element': 'other',\n 'enum_value': 'other',\n 'template_literal': 'other',\n 'switch_case': 'other',\n 'other': 'other',\n // Pre-filtered contexts should not reach here, but map them just in case\n 'import_path': 'other',\n 'type_annotation': 'other',\n 'css_class': 'other',\n 'css_utility_call': 'other',\n 'console_call': 'other',\n 'test_assertion': 'other',\n}\n\n// ─── Main: scanCandidates ───\n\nexport async function scanCandidates(\n projectRoot: string,\n options?: ScanOptions,\n): Promise<ScanCandidatesResult> {\n const limit = options?.limit ?? DEFAULT_LIMIT\n const offset = options?.offset ?? DEFAULT_OFFSET\n const minLength = options?.min_length ?? DEFAULT_MIN_LENGTH\n const maxLength = options?.max_length ?? DEFAULT_MAX_LENGTH\n const minScore = options?.min_score ?? DEFAULT_MIN_SCORE\n\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n const files = await discoverFiles(projectRoot, {\n paths: scanDirs,\n include: options?.include,\n exclude: options?.exclude,\n })\n\n // ─── Phase 1: Extract strings from all files (pre-filter applied inside extractStrings) ───\n\n const filePromises = files.map(async (relPath) => {\n const filePath = join(projectRoot, relPath)\n const content = await readText(filePath)\n if (!content) return { relPath, extractions: [] }\n\n const ext = extname(filePath)\n const extractions = await extractStrings(filePath, content, ext)\n return { relPath, extractions }\n })\n\n const fileResults = await Promise.all(filePromises)\n\n // ─── Phase 2: Score + length filter + deduplicate ───\n\n let rawStringsFound = 0\n let skippedCount = 0\n let lowConfidenceCount = 0\n const skipReasons: Record<string, number> = {}\n\n // Deduplication map: value → first candidate + all occurrences\n const uniqueMap = new Map<string, {\n candidate: ScanCandidate\n maxScore: number\n }>()\n\n // Also track duplicates for backward compatibility\n const dupeMap = new Map<string, Array<{ file: string; line: number }>>()\n\n for (const { relPath, extractions } of fileResults) {\n rawStringsFound += extractions.length\n\n for (const extraction of extractions) {\n // Length filter\n if (extraction.value.length < minLength || extraction.value.length > maxLength) {\n skippedCount++\n skipReasons['length_filter'] = (skipReasons['length_filter'] ?? 0) + 1\n continue\n }\n\n // shouldSkip was already applied inside extractStrings (via applyPreFilter).\n // But applyPreFilter uses default minScore. Here we apply the user-configured minScore\n // on the contentScore that was attached during pre-filtering.\n\n // Get the contentScore attached by applyPreFilter\n const contentScore: number = (extraction as unknown as { contentScore?: number }).contentScore ?? calculateContentScore(extraction)\n\n if (contentScore < minScore) {\n lowConfidenceCount++\n skipReasons['low_confidence'] = (skipReasons['low_confidence'] ?? 0) + 1\n continue\n }\n\n const mappedContext = CONTEXT_MAP[extraction.context]\n const loc = { file: relPath, line: extraction.line }\n\n // Track all occurrences for duplicates section\n if (!dupeMap.has(extraction.value)) {\n dupeMap.set(extraction.value, [])\n }\n dupeMap.get(extraction.value)!.push(loc)\n\n // Deduplication: keep first occurrence, accumulate locations\n if (!uniqueMap.has(extraction.value)) {\n uniqueMap.set(extraction.value, {\n candidate: {\n file: relPath,\n line: extraction.line,\n column: extraction.column,\n value: extraction.value,\n context: mappedContext,\n surrounding: extraction.surrounding,\n contentScore,\n occurrences: [loc],\n },\n maxScore: contentScore,\n })\n } else {\n const entry = uniqueMap.get(extraction.value)!\n entry.candidate.occurrences.push(loc)\n // Keep the highest score across occurrences\n if (contentScore > entry.maxScore) {\n entry.maxScore = contentScore\n entry.candidate.contentScore = contentScore\n entry.candidate.file = relPath\n entry.candidate.line = extraction.line\n entry.candidate.column = extraction.column\n entry.candidate.context = mappedContext\n entry.candidate.surrounding = extraction.surrounding\n }\n }\n }\n }\n\n // Build sorted unique candidates (highest score first)\n const allUniqueCandidates = [...uniqueMap.values()]\n .map(e => e.candidate)\n .toSorted((a, b) => b.contentScore - a.contentScore)\n\n // Build duplicate groups (only count >= 2), sorted by count descending\n const duplicates: DuplicateGroup[] = [...dupeMap.entries()]\n .filter(([, occurrences]) => occurrences.length >= 2)\n .map(([value, occurrences]) => ({ value, count: occurrences.length, occurrences }))\n .toSorted((a, b) => b.count - a.count)\n\n // Pagination on unique candidates\n const uniqueCount = allUniqueCandidates.length\n const paginated = allUniqueCandidates.slice(offset, offset + limit)\n const hasMore = uniqueCount > offset + limit\n\n return {\n candidates: paginated,\n duplicates,\n stats: {\n files_scanned: files.length,\n raw_strings_found: rawStringsFound,\n skipped: skippedCount,\n low_confidence: lowConfidenceCount,\n unique_candidates: uniqueCount,\n candidates_returned: paginated.length,\n has_more: hasMore,\n skip_reasons: skipReasons,\n },\n }\n}\n\n// ─── Main: scanSummary ───\n\nexport async function scanSummary(\n projectRoot: string,\n options?: ScanOptions,\n): Promise<ScanSummaryResult> {\n const minLength = options?.min_length ?? DEFAULT_MIN_LENGTH\n const maxLength = options?.max_length ?? DEFAULT_MAX_LENGTH\n const minScore = options?.min_score ?? DEFAULT_MIN_SCORE\n\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n const files = await discoverFiles(projectRoot, {\n paths: scanDirs,\n include: options?.include,\n exclude: options?.exclude,\n })\n\n // Group files by directory\n const dirFiles = new Map<string, string[]>()\n const fileTypes: Record<string, number> = {}\n\n for (const relPath of files) {\n const parts = relPath.split('/')\n const dir = parts.slice(0, -1).join('/') || '.'\n const ext = extname(relPath)\n\n if (!dirFiles.has(dir)) dirFiles.set(dir, [])\n dirFiles.get(dir)!.push(relPath)\n\n fileTypes[ext] = (fileTypes[ext] ?? 0) + 1\n }\n\n // Sample files per directory and count candidates\n const byDirectory: Record<string, { files: number; candidates: number }> = {}\n const freqMap = new Map<string, number>()\n let totalCandidatesEstimate = 0\n\n for (const [dir, dirFileList] of dirFiles) {\n const totalInDir = dirFileList.length\n const sampleFiles = dirFileList.slice(0, SUMMARY_SAMPLE_SIZE)\n let sampleCandidates = 0\n\n const samplePromises = sampleFiles.map(async (relPath) => {\n const filePath = join(projectRoot, relPath)\n const content = await readText(filePath)\n if (!content) return []\n\n const ext = extname(filePath)\n return extractStrings(filePath, content, ext)\n })\n\n const sampleResults = await Promise.all(samplePromises)\n\n for (const extractions of sampleResults) {\n for (const extraction of extractions) {\n // Apply same filters as scanCandidates\n if (extraction.value.length < minLength || extraction.value.length > maxLength) continue\n\n const contentScore: number = (extraction as unknown as { contentScore?: number }).contentScore ?? calculateContentScore(extraction)\n if (contentScore < minScore) continue\n\n sampleCandidates++\n\n // Track frequencies for top_repeated\n const prev = freqMap.get(extraction.value) ?? 0\n freqMap.set(extraction.value, prev + 1)\n }\n }\n\n // Estimate for full directory\n const avgPerFile = sampleFiles.length > 0 ? sampleCandidates / sampleFiles.length : 0\n const estimatedCandidates = Math.round(avgPerFile * totalInDir)\n\n byDirectory[dir] = {\n files: totalInDir,\n candidates: estimatedCandidates,\n }\n\n totalCandidatesEstimate += estimatedCandidates\n }\n\n // Top repeated strings\n const topRepeated = [...freqMap.entries()]\n .filter(([, count]) => count >= 2)\n .toSorted((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([value, count]) => ({ value, count }))\n\n return {\n total_files: files.length,\n total_candidates_estimate: totalCandidatesEstimate,\n by_directory: byDirectory,\n top_repeated: topRepeated,\n sampling_note: `Based on first ${SUMMARY_SAMPLE_SIZE} files per directory. Counts are from sampled subset, not project-wide.`,\n file_types: fileTypes,\n }\n}\n"],"mappings":";;;;;AAiBA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,0BAA0B;AAChC,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,iBAAiB;AAEvB,MAAM,eAAe,IAAI,IAAI;CAAC;CAAU;CAAS;CAAW;CAAO,CAAC;AAIpE,SAAS,UAAU,KAAsB;AACvC,KAAI,kCAAkC,KAAK,IAAI,CAAE,QAAO;AACxD,KAAI,4BAA4B,KAAK,IAAI,CAAE,QAAO;AAClD,KAAI,qBAAqB,KAAK,IAAI,aAAa,CAAC,IAAI,CAAC,IAAI,SAAS,IAAI,KAAK,IAAI,SAAS,IAAI,IAAI,IAAI,SAAS,IAAI,EAC/G,QAAO;AAET,QAAO;;AAKT,MAAM,sBAAsB;AAE5B,SAAS,eAAe,OAAwB;CAC9C,MAAM,WAAW,MAAM,MAAM,CAAC,MAAM,MAAM;AAC1C,KAAI,SAAS,SAAS,EAAG,QAAO;CAChC,I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AAW;AAGhF,QAD8B,WAAoD,gBAAgB,sBAAsB,WAAW,IAChH,SAAU;AAE7B;GAGA,MAAM,OAAO,QAAQ,IAAI,WAAW,MAAM,IAAI;AAC9C,WAAQ,IAAI,WAAW,OAAO,OAAO,EAAE;;EAK3C,MAAM,aAAa,YAAY,SAAS,IAAI,mBAAmB,YAAY,SAAS;EACpF,MAAM,sBAAsB,KAAK,MAAM,aAAa,WAAW;AAE/D,cAAY,OAAO;GACjB,OAAO;GACP,YAAY;GACb;AAED,6BAA2B;;CAI7B,MAAM,cAAc,CAAC,GAAG,QAAQ,SAAS,CAAC,CACvC,QAAQ,GAAG,WAAW,SAAS,EAAE,CACjC,UAAU,GAAG,MAAM,EAAE,KAAK,EAAE,GAAG,CAC/B,MAAM,GAAG,GAAG,CACZ,KAAK,CAAC,OAAO,YAAY;EAAE;EAAO;EAAO,EAAE;AAE9C,QAAO;EACL,aAAa,MAAM;EACnB,2BAA2B;EAC3B,cAAc;EACd,cAAc;EACd,eAAe,kBAAkB,oBAAoB;EACrD,YAAY;EACb"}
1
+ {"version":3,"file":"scanner-VOwrKLGC.mjs","names":[],"sources":["../src/core/ast-scanner/pre-filter.ts","../src/core/ast-scanner/index.ts","../src/core/scanner.ts"],"sourcesContent":["import type { ExtractedString } from './types.js'\n\n// ─── Pre-filter Result ───\n\nexport interface PreFilterResult {\n /** Strings that passed the pre-filter (candidates for agent) */\n candidates: ExtractedString[]\n /** Total number of strings removed by shouldSkip */\n skipped: number\n /** Total number of strings removed by low content score */\n lowConfidence: number\n /** Breakdown: skip reason → count */\n skipReasons: Record<string, number>\n}\n\n// ─── Value-based regexes ───\n\nconst PURE_NUMBER_RE = /^-?\\d+(\\.\\d+)?$/\nconst HEX_COLOR_RE = /^#[0-9a-f]{3,8}$/i\nconst FILE_EXT_RE = /\\.(png|jpg|jpeg|gif|svg|webp|ico|css|scss|less|js|ts|tsx|jsx|json|md|html|xml|yaml|yml|woff|woff2|ttf|eot|mp4|webm|mp3|wav|pdf)$/i\nconst SVG_PATH_DATA_RE = /^[Mm][\\d\\s.,LHVCSQTAZlhvcsqtazmMzZ-]+$/\nconst SVG_VIEWBOX_RE = /^\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?\\s+\\d+(\\.\\d+)?$/\nconst I18N_KEY_RE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)+$/\nconst TECHNICAL_IDENTIFIER_RE = /^[_a-z][a-z0-9_-]*$/\nconst ERROR_CODE_RE = /^[A-Z][A-Z0-9_]+$/\nconst PLACEHOLDER_RE = /^\\{\\d+\\}$|^\\.{2,}$/\nconst CAMEL_CASE_RE = /^[a-z]+[A-Z]/\nconst LOCALE_CODE_RE = /^[a-z]{2}[-_][A-Z]{2}$/\nconst DIMENSION_RE = /^\\d+[x×]\\d+$/\nconst REPEAT_CHAR_RE = /^(.)\\1{3,}$/\nconst MIME_TYPE_RE = /^(application|text|image|audio|video|multipart|font)\\/[\\w.+-]+$/\nconst PASCAL_CASE_RE = /^[A-Z][a-z]+[A-Z]/\n\nconst HTML_TARGETS = new Set(['_blank', '_self', '_parent', '_top'])\n\n// ─── URL / path detection (consolidated from legacy isNonContent) ───\n\nfunction isURLLike(str: string): boolean {\n if (/^(https?|ftp|file|mailto|data):/.test(str)) return true\n if (/^(\\.\\.?\\/|\\/|[A-Za-z]:\\\\)/.test(str)) return true\n if (/^['\"]?[@a-z][\\w-]*/.test(str.toLowerCase()) && !str.includes(' ') && (str.includes('/') || str.includes('.'))) {\n return true\n }\n return false\n}\n\n// ─── CSS / Tailwind detection ───\n\nconst TAILWIND_SEGMENT_RE = /^(?:bg-|text-|border-|flex|grid|p-|px-|py-|pt-|pb-|pl-|pr-|m-|mx-|my-|mt-|mb-|ml-|mr-|rounded|shadow|w-|h-|min-|max-|gap-|space-|items-|justify-|self-|overflow-|z-|opacity-|transition|duration-|ease-|animate-|font-|leading-|tracking-|decoration-|underline|line-through|uppercase|lowercase|capitalize|truncate|whitespace-|break-|sr-only|not-sr-only|hover:|focus:|active:|disabled:|dark:|sm:|md:|lg:|xl:|2xl:|group-|peer-|ring-|outline-|divide-|table-|col-|row-|aspect-|object-|inset-|top-|right-|bottom-|left-|translate-|rotate-|scale-|skew-|origin-|cursor-|select-|resize-|fill-|stroke-|block|inline|absolute|relative|fixed|sticky|static|float-|clear-|isolate|visible|invisible|grow|shrink|basis-|order-|place-)/\n\nfunction isCssClassList(value: string): boolean {\n const segments = value.trim().split(/\\s+/)\n if (segments.length < 2) return false\n let matched = 0\n for (const seg of segments) {\n if (TAILWIND_SEGMENT_RE.test(seg)) matched++\n }\n return matched / segments.length >= 0.5\n}\n\nfunction isSingleCssUtility(value: string): boolean {\n const trimmed = value.trim()\n if (trimmed.includes(' ')) return false\n return TAILWIND_SEGMENT_RE.test(trimmed)\n}\n\n// ─── SVG technical attributes ───\n\nconst SVG_TECHNICAL_ATTRIBUTES = new Set([\n 'd', 'viewBox', 'points', 'transform', 'pathLength',\n 'xmlns', 'preserveAspectRatio',\n 'stroke-linecap', 'stroke-linejoin', 'stroke-width',\n 'stroke-dasharray', 'stroke-dashoffset', 'stroke-miterlimit',\n 'fill-rule', 'clip-rule',\n])\n\nconst SVG_GRAPHIC_ELEMENTS = new Set([\n 'svg', 'path', 'circle', 'rect', 'line', 'polyline', 'polygon',\n 'ellipse', 'g', 'defs', 'use', 'symbol', 'clipPath', 'mask',\n 'pattern', 'linearGradient', 'radialGradient', 'stop',\n 'marker', 'animate', 'animateTransform', 'image',\n])\n\n// ─── Known function names ───\n\nconst I18N_FUNCTIONS = new Set([\n 't', '$t', 'i18n', 'translate', 'formatMessage', 'msg',\n])\n\nconst EMIT_FUNCTIONS = new Set([\n 'emit', '$emit',\n])\n\n// ─── Translatable attribute whitelist (i18next-cli compatible + extended) ───\n\nconst TRANSLATABLE_ATTRIBUTES = new Set([\n // Standard HTML content attributes\n 'title', 'alt', 'placeholder', 'label', 'summary', 'caption',\n 'abbr', 'accesskey', 'content', 'description',\n // ARIA content\n 'aria-label', 'aria-description', 'aria-placeholder',\n 'aria-roledescription', 'aria-valuetext',\n // React Native accessibility (equivalent to aria-label)\n 'accessibilityLabel', 'accessibilityHint', 'accessibilityValue',\n // Common component content props\n 'heading', 'subheading', 'message', 'hint', 'tooltip',\n 'helper-text', 'error-message', 'success-message',\n 'confirm-text', 'cancel-text', 'empty-text', 'loading-text',\n 'no-data-text', 'no-results-text',\n])\n\n// ─── Translatable object property whitelist (i18next-cli compatible) ───\n\nconst TRANSLATABLE_PROPERTIES = new Set([\n 'label', 'title', 'description', 'text', 'message', 'placeholder',\n 'caption', 'summary', 'heading', 'subheading', 'subtitle', 'tooltip',\n 'hint', 'helpText', 'errorMessage', 'successMessage', 'name',\n])\n\n// ─── shouldSkip: Binary non-content detection ───\n\n/**\n * Determines if a string is definitely NOT user-visible content.\n * Returns skip reason if it should be filtered, null if it should proceed to scoring.\n *\n * Conservative for template_text/jsx_text (tag-between text is almost always content).\n * Aggressive for everything else (technical tokens, config values, framework artifacts).\n */\nexport function shouldSkip(str: ExtractedString): string | null {\n // ── Context-based rules (AST-determined, 100% accurate) ──\n\n if (str.context === 'import_path') return 'import_path'\n if (str.context === 'type_annotation') return 'type_annotation'\n if (str.context === 'css_class') return 'css_class'\n if (str.context === 'css_utility_call') return 'css_utility_call'\n if (str.context === 'console_call') return 'console_call'\n if (str.context === 'test_assertion') return 'test_assertion'\n if (str.context === 'switch_case') return 'switch_case'\n\n const v = str.value\n\n // ── Value-based rules (structural patterns) ──\n\n if (v.length <= 1) return 'single_char'\n if (/^\\s+$/.test(v)) return 'whitespace'\n if (PURE_NUMBER_RE.test(v)) return 'pure_number'\n if (HEX_COLOR_RE.test(v)) return 'hex_color'\n if (FILE_EXT_RE.test(v)) return 'file_extension'\n if (v.startsWith('--')) return 'cli_flag'\n\n // ── i18n key paths (checked before URL — both contain dots, but i18n keys are more specific) ──\n\n if (I18N_KEY_RE.test(v)) return 'i18n_key'\n\n // ── MIME types (checked before URL — both contain slash, MIME is more specific) ──\n\n if (MIME_TYPE_RE.test(v)) return 'mime_type'\n\n // ── URL/path patterns ──\n\n if (isURLLike(v)) return 'url_path'\n\n // ── CSS patterns ──\n\n if (isCssClassList(v)) return 'css_class_list'\n if (isSingleCssUtility(v)) return 'css_utility_token'\n\n // ── SVG patterns ──\n\n if (v.length > 3 && SVG_PATH_DATA_RE.test(v)) return 'svg_path_data'\n if (SVG_VIEWBOX_RE.test(v)) return 'svg_viewbox'\n if (str.parentProperty !== undefined && SVG_TECHNICAL_ATTRIBUTES.has(str.parentProperty)) return 'svg_technical_attr'\n if (str.context === 'template_attribute' && SVG_GRAPHIC_ELEMENTS.has(str.parent)) return 'svg_element_attr'\n\n // ── Framework event patterns ──\n\n if (v.startsWith('update:')) return 'vue_emit_event'\n\n // ── Placeholder / interpolation ──\n\n if (PLACEHOLDER_RE.test(v)) return 'placeholder'\n\n // ── Structural value patterns (100% non-content) ──\n\n if (LOCALE_CODE_RE.test(v)) return 'locale_code'\n if (DIMENSION_RE.test(v)) return 'dimension'\n if (REPEAT_CHAR_RE.test(v)) return 'repeat_chars'\n if (HTML_TARGETS.has(v)) return 'html_target'\n\n // ── Known function argument detection ──\n\n if (str.context === 'function_argument' && I18N_FUNCTIONS.has(str.parent)) {\n // i18n function args: filter lowercase identifiers (namespace/key), keep sentences\n if (/^[a-z][a-z0-9_.-]*$/.test(v)) return 'i18n_function_arg'\n }\n\n if (str.context === 'function_argument' && EMIT_FUNCTIONS.has(str.parent)) {\n return 'emit_event_arg'\n }\n\n // ── CRITICAL: Technical identifier detection (i18next-cli proven pattern) ──\n // Single lowercase ASCII word/kebab-case/snake_case < 30 chars → technical token\n // EXEMPT: template_text and jsx_text (tag-between text IS content, even lowercase)\n\n if (str.context !== 'template_text' && str.context !== 'jsx_text') {\n if (TECHNICAL_IDENTIFIER_RE.test(v) && v.length < 30) {\n return 'technical_identifier'\n }\n }\n\n // ── Error codes (SCREAMING_SNAKE_CASE with underscores) ──\n\n if (ERROR_CODE_RE.test(v) && v.includes('_') && v.length > 3) {\n return 'error_code'\n }\n\n return null\n}\n\n// ─── calculateContentScore: 0-1 confidence scoring ───\n\n/**\n * Calculates a content confidence score (0-1) for a string that passed shouldSkip.\n * Uses AST context metadata (our advantage over offset-based tools) combined with\n * value-based signals proven by i18next-cli.\n *\n * Base score: 0.5. Boosted/penalized by context and value characteristics.\n */\nexport function calculateContentScore(str: ExtractedString): number {\n let score = 0.5\n\n // ── Context signals (AST metadata advantage) ──\n\n // Template/JSX text = almost certainly user-visible content\n if (str.context === 'template_text' || str.context === 'jsx_text') {\n score += 0.3\n }\n\n // Content-bearing attribute (title, alt, placeholder, aria-label, etc.)\n if (str.context === 'template_attribute' || str.context === 'jsx_attribute') {\n if (str.parentProperty && TRANSLATABLE_ATTRIBUTES.has(str.parentProperty)) {\n score += 0.2\n } else {\n score -= 0.2 // Unknown/technical attribute\n }\n }\n\n // Content-bearing object property (message, label, description, etc.)\n if (str.context === 'object_property') {\n if (str.parentProperty && TRANSLATABLE_PROPERTIES.has(str.parentProperty)) {\n score += 0.25\n }\n }\n\n // ── Value signals (i18next-cli proven heuristics) ──\n\n // Multi-word strings are more likely content\n const wordCount = str.value.split(/\\s+/).length\n if (wordCount >= 3) score += 0.2\n else if (wordCount === 2) score += 0.1\n\n // Terminal punctuation suggests a sentence\n if (/[.!?:;]$/.test(str.value)) score += 0.1\n\n // Non-ASCII characters (Turkish, Chinese, Arabic, etc.) → almost certainly content\n if (/[\\u0080-\\uFFFF]/.test(str.value)) score += 0.15\n\n // Capitalized first letter with lowercase body (Dashboard, Kaydet, Settings)\n if (/^[A-Z]/.test(str.value) && /[a-z]/.test(str.value)) score += 0.1\n\n // camelCase → probably a technical identifier\n if (CAMEL_CASE_RE.test(str.value)) score -= 0.3\n\n // PascalCase with internal uppercase (PhGameController, GameCard) → likely component/icon name\n // Does NOT match single-uppercase words (Dashboard, Karadeniz, Settings)\n if (PASCAL_CASE_RE.test(str.value) && !str.value.includes(' ')) score -= 0.25\n\n // Short ALL-CAPS (TRY, GET, USD) → likely code/abbreviation, not content\n // In template_text the +0.3 context boost keeps real labels like \"FAQ\" above threshold\n if (/^[A-Z]{2,5}$/.test(str.value)) score -= 0.15\n\n // Contains slash without spaces → path-like\n if (str.value.includes('/') && !str.value.includes(' ')) score -= 0.2\n\n return Math.max(0, Math.min(1, score))\n}\n\n// ─── Public API ───\n\n/**\n * Two-phase pre-filter:\n * 1. shouldSkip(): Binary removal of definite non-content\n * 2. calculateContentScore(): 0-1 confidence scoring for ambiguous strings\n *\n * Returns candidates that passed both phases, with content scores attached.\n */\nexport function applyPreFilter(\n strings: ExtractedString[],\n minScore: number = 0.4,\n): PreFilterResult {\n const candidates: ExtractedString[] = []\n const skipReasons: Record<string, number> = {}\n let skipped = 0\n let lowConfidence = 0\n\n for (const str of strings) {\n // Phase 1: Binary skip\n const skipReason = shouldSkip(str)\n if (skipReason) {\n skipped++\n skipReasons[skipReason] = (skipReasons[skipReason] ?? 0) + 1\n continue\n }\n\n // Phase 2: Content scoring\n const contentScore = calculateContentScore(str)\n if (contentScore < minScore) {\n lowConfidence++\n skipReasons['low_confidence'] = (skipReasons['low_confidence'] ?? 0) + 1\n continue\n }\n\n // Attach score to the extraction for downstream use\n ;(str as ExtractedString & { contentScore: number }).contentScore = contentScore\n candidates.push(str)\n }\n\n return { candidates, skipped, lowConfidence, skipReasons }\n}\n","import type { ExtractedString } from './types.js'\nimport { applyPreFilter } from './pre-filter.js'\nimport { parseTsx } from './tsx-parser.js'\n\n// ─── Extension sets ───\n\nconst TSX_EXTENSIONS = new Set(['.tsx', '.jsx', '.ts', '.js', '.mjs'])\nconst VUE_EXTENSIONS = new Set(['.vue'])\nconst SVELTE_EXTENSIONS = new Set(['.svelte'])\nconst ASTRO_EXTENSIONS = new Set(['.astro'])\n\n// ─── Lazy-loaded parsers ───\n\n/**\n * Lazily import vue-parser. Returns undefined if not available\n * (@vue/compiler-sfc is an optional dependency).\n */\nasync function loadVueParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]> | ExtractedString[]) | undefined> {\n try {\n const mod = await import('./vue-parser.js')\n return mod.parseVue\n } catch {\n return undefined\n }\n}\n\n/**\n * Lazily import svelte-parser. Returns undefined if not available\n * (svelte is an optional dependency).\n */\nasync function loadSvelteParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]>) | undefined> {\n try {\n const mod = await import('./svelte-parser.js')\n return mod.parseSvelte\n } catch {\n return undefined\n }\n}\n\n/**\n * Lazily import astro-parser. Returns undefined if not available\n * (@astrojs/compiler is an optional dependency).\n */\nasync function loadAstroParser(): Promise<((content: string, fileName: string) => Promise<ExtractedString[]>) | undefined> {\n try {\n const mod = await import('./astro-parser.js')\n return mod.parseAstro\n } catch {\n return undefined\n }\n}\n\n// ─── Regex fallback for unknown extensions ───\n\nconst SURROUNDING_MAX = 120\n\n/**\n * Minimal regex-based extractor for file types without AST parsers.\n * Extracts quoted strings and tag text — conservative, low accuracy.\n * Used as fallback when dedicated parsers are unavailable.\n */\nfunction extractWithRegex(content: string, _filePath: string): ExtractedString[] {\n const lines = content.split('\\n')\n const results: ExtractedString[] = []\n\n // Simple quoted string extraction\n const stringRe = /(['\"`])(?:(?!\\1|\\\\).|\\\\.)*?\\1/g\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!\n const trimmed = line.trim()\n\n // Skip comments, imports\n if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*')) continue\n if (/^\\s*(import|export)\\s/.test(line)) continue\n\n let match: RegExpExecArray | null\n stringRe.lastIndex = 0\n\n while ((match = stringRe.exec(line)) !== null) {\n // Remove surrounding quotes\n const raw = match[0]\n const value = raw.slice(1, -1)\n if (value.length === 0) continue\n\n const surrounding = buildSurrounding(lines, i)\n\n results.push({\n value,\n line: i + 1,\n column: match.index + 1,\n context: 'other',\n scope: 'script',\n parent: '',\n surrounding,\n })\n }\n\n // Tag text extraction: >text<\n const tagTextRe = />([^<>{]+)</g\n let tagMatch: RegExpExecArray | null\n tagTextRe.lastIndex = 0\n\n while ((tagMatch = tagTextRe.exec(line)) !== null) {\n const text = tagMatch[1]!.trim()\n if (text.length === 0) continue\n if (/^[\\s\\W]*$/.test(text) && !/[a-zA-Z]/.test(text)) continue\n\n results.push({\n value: text,\n line: i + 1,\n column: tagMatch.index + 1,\n context: 'template_text',\n scope: 'template',\n parent: '',\n surrounding: buildSurrounding(lines, i),\n })\n }\n }\n\n return results\n}\n\nfunction buildSurrounding(lines: string[], lineIdx: number): string {\n const start = Math.max(0, lineIdx - 1)\n const end = Math.min(lines.length - 1, lineIdx + 1)\n\n const parts: string[] = []\n for (let i = start; i <= end; i++) {\n const line = lines[i]\n if (line !== undefined) {\n parts.push(line)\n }\n }\n\n const joined = parts.join('\\n')\n if (joined.length > SURROUNDING_MAX) {\n return joined.slice(0, SURROUNDING_MAX)\n }\n return joined\n}\n\n// ─── Public API ───\n\n/**\n * Extract strings from a source file with structural context.\n *\n * Routes to the correct parser based on file extension:\n * - .tsx/.jsx/.ts/.js/.mjs -> tsx-parser (AST-based)\n * - .vue -> vue-parser (lazy-loaded, AST-based)\n * - .svelte -> svelte-parser (lazy-loaded, AST-based)\n * - .astro -> astro-parser (lazy-loaded, AST-based)\n * - unknown -> empty array\n *\n * Falls back to regex extraction when the dedicated parser's\n * optional dependency is not installed.\n *\n * Applies structural pre-filter to remove 100% non-content strings.\n * Returns only candidates that should be sent to the agent.\n */\nexport async function extractStrings(\n filePath: string,\n content: string,\n ext: string,\n): Promise<ExtractedString[]> {\n const normalizedExt = ext.startsWith('.') ? ext : `.${ext}`\n let rawStrings: ExtractedString[]\n\n if (TSX_EXTENSIONS.has(normalizedExt)) {\n rawStrings = parseTsx(content, filePath)\n } else if (VUE_EXTENSIONS.has(normalizedExt)) {\n const parseVue = await loadVueParser()\n if (parseVue) {\n rawStrings = await parseVue(content, filePath)\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else if (SVELTE_EXTENSIONS.has(normalizedExt)) {\n const parseSvelte = await loadSvelteParser()\n if (parseSvelte) {\n try {\n rawStrings = await parseSvelte(content, filePath)\n } catch {\n // svelte/compiler not installed — fall back to regex\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else if (ASTRO_EXTENSIONS.has(normalizedExt)) {\n const parseAstro = await loadAstroParser()\n if (parseAstro) {\n try {\n rawStrings = await parseAstro(content, filePath)\n } catch {\n // @astrojs/compiler not installed — fall back to regex\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n rawStrings = extractWithRegex(content, filePath)\n }\n } else {\n return []\n }\n\n // Apply structural pre-filter\n const { candidates } = applyPreFilter(rawStrings)\n return candidates\n}\n\n// Re-export types for convenience\nexport type { ExtractedString, StructuralContext, PreFilterRule } from './types.js'\nexport { applyPreFilter, shouldSkip, calculateContentScore } from './pre-filter.js'\nexport type { PreFilterResult } from './pre-filter.js'\n","import type {\n StringContext,\n ScanCandidate,\n DuplicateGroup,\n ScanCandidatesResult,\n ScanSummaryResult,\n} from '@contentrain/types'\nimport { join, extname } from 'node:path'\nimport { readText } from '../util/fs.js'\nimport {\n autoDetectSourceDirs,\n discoverFiles,\n} from './scan-config.js'\nimport { extractStrings } from './ast-scanner/index.js'\nimport { calculateContentScore } from './ast-scanner/pre-filter.js'\nimport type { StructuralContext } from './ast-scanner/types.js'\n\n// ─── Options ───\n\nexport interface ScanOptions {\n paths?: string[]\n include?: string[]\n exclude?: string[]\n limit?: number\n offset?: number\n min_length?: number\n max_length?: number\n /** Minimum content confidence score (0-1). Default: 0.4 */\n min_score?: number\n}\n\n// ─── Constants ───\n\nconst DEFAULT_LIMIT = 50\nconst DEFAULT_OFFSET = 0\nconst DEFAULT_MIN_LENGTH = 2\nconst DEFAULT_MAX_LENGTH = 500\nconst DEFAULT_MIN_SCORE = 0.4\nconst SUMMARY_SAMPLE_SIZE = 10\n\n// ─── Context mapping: StructuralContext → StringContext ───\n\nconst CONTEXT_MAP: Record<StructuralContext, StringContext> = {\n 'template_text': 'template_text',\n 'template_attribute': 'template_attribute',\n 'jsx_text': 'jsx_text',\n 'jsx_attribute': 'jsx_attribute',\n 'variable_assignment': 'variable_assignment',\n 'object_property': 'object_value',\n 'function_argument': 'function_argument',\n 'array_element': 'other',\n 'enum_value': 'other',\n 'template_literal': 'other',\n 'switch_case': 'other',\n 'other': 'other',\n // Pre-filtered contexts should not reach here, but map them just in case\n 'import_path': 'other',\n 'type_annotation': 'other',\n 'css_class': 'other',\n 'css_utility_call': 'other',\n 'console_call': 'other',\n 'test_assertion': 'other',\n}\n\n// ─── Main: scanCandidates ───\n\nexport async function scanCandidates(\n projectRoot: string,\n options?: ScanOptions,\n): Promise<ScanCandidatesResult> {\n const limit = options?.limit ?? DEFAULT_LIMIT\n const offset = options?.offset ?? DEFAULT_OFFSET\n const minLength = options?.min_length ?? DEFAULT_MIN_LENGTH\n const maxLength = options?.max_length ?? DEFAULT_MAX_LENGTH\n const minScore = options?.min_score ?? DEFAULT_MIN_SCORE\n\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n const files = await discoverFiles(projectRoot, {\n paths: scanDirs,\n include: options?.include,\n exclude: options?.exclude,\n })\n\n // ─── Phase 1: Extract strings from all files (pre-filter applied inside extractStrings) ───\n\n const filePromises = files.map(async (relPath) => {\n const filePath = join(projectRoot, relPath)\n const content = await readText(filePath)\n if (!content) return { relPath, extractions: [] }\n\n const ext = extname(filePath)\n const extractions = await extractStrings(filePath, content, ext)\n return { relPath, extractions }\n })\n\n const fileResults = await Promise.all(filePromises)\n\n // ─── Phase 2: Score + length filter + deduplicate ───\n\n let rawStringsFound = 0\n let skippedCount = 0\n let lowConfidenceCount = 0\n const skipReasons: Record<string, number> = {}\n\n // Deduplication map: value → first candidate + all occurrences\n const uniqueMap = new Map<string, {\n candidate: ScanCandidate\n maxScore: number\n }>()\n\n // Also track duplicates for backward compatibility\n const dupeMap = new Map<string, Array<{ file: string; line: number }>>()\n\n for (const { relPath, extractions } of fileResults) {\n rawStringsFound += extractions.length\n\n for (const extraction of extractions) {\n // Length filter\n if (extraction.value.length < minLength || extraction.value.length > maxLength) {\n skippedCount++\n skipReasons['length_filter'] = (skipReasons['length_filter'] ?? 0) + 1\n continue\n }\n\n // shouldSkip was already applied inside extractStrings (via applyPreFilter).\n // But applyPreFilter uses default minScore. Here we apply the user-configured minScore\n // on the contentScore that was attached during pre-filtering.\n\n // Get the contentScore attached by applyPreFilter\n const contentScore: number = (extraction as unknown as { contentScore?: number }).contentScore ?? calculateContentScore(extraction)\n\n if (contentScore < minScore) {\n lowConfidenceCount++\n skipReasons['low_confidence'] = (skipReasons['low_confidence'] ?? 0) + 1\n continue\n }\n\n const mappedContext = CONTEXT_MAP[extraction.context]\n const loc = { file: relPath, line: extraction.line }\n\n // Track all occurrences for duplicates section\n if (!dupeMap.has(extraction.value)) {\n dupeMap.set(extraction.value, [])\n }\n dupeMap.get(extraction.value)!.push(loc)\n\n // Deduplication: keep first occurrence, accumulate locations\n if (!uniqueMap.has(extraction.value)) {\n uniqueMap.set(extraction.value, {\n candidate: {\n file: relPath,\n line: extraction.line,\n column: extraction.column,\n value: extraction.value,\n context: mappedContext,\n surrounding: extraction.surrounding,\n contentScore,\n occurrences: [loc],\n },\n maxScore: contentScore,\n })\n } else {\n const entry = uniqueMap.get(extraction.value)!\n entry.candidate.occurrences.push(loc)\n // Keep the highest score across occurrences\n if (contentScore > entry.maxScore) {\n entry.maxScore = contentScore\n entry.candidate.contentScore = contentScore\n entry.candidate.file = relPath\n entry.candidate.line = extraction.line\n entry.candidate.column = extraction.column\n entry.candidate.context = mappedContext\n entry.candidate.surrounding = extraction.surrounding\n }\n }\n }\n }\n\n // Build sorted unique candidates (highest score first)\n const allUniqueCandidates = [...uniqueMap.values()]\n .map(e => e.candidate)\n .toSorted((a, b) => b.contentScore - a.contentScore)\n\n // Build duplicate groups (only count >= 2), sorted by count descending\n const duplicates: DuplicateGroup[] = [...dupeMap.entries()]\n .filter(([, occurrences]) => occurrences.length >= 2)\n .map(([value, occurrences]) => ({ value, count: occurrences.length, occurrences }))\n .toSorted((a, b) => b.count - a.count)\n\n // Pagination on unique candidates\n const uniqueCount = allUniqueCandidates.length\n const paginated = allUniqueCandidates.slice(offset, offset + limit)\n const hasMore = uniqueCount > offset + limit\n\n return {\n candidates: paginated,\n duplicates,\n stats: {\n files_scanned: files.length,\n raw_strings_found: rawStringsFound,\n skipped: skippedCount,\n low_confidence: lowConfidenceCount,\n unique_candidates: uniqueCount,\n candidates_returned: paginated.length,\n has_more: hasMore,\n skip_reasons: skipReasons,\n },\n }\n}\n\n// ─── Main: scanSummary ───\n\nexport async function scanSummary(\n projectRoot: string,\n options?: ScanOptions,\n): Promise<ScanSummaryResult> {\n const minLength = options?.min_length ?? DEFAULT_MIN_LENGTH\n const maxLength = options?.max_length ?? DEFAULT_MAX_LENGTH\n const minScore = options?.min_score ?? DEFAULT_MIN_SCORE\n\n const scanDirs = options?.paths ?? await autoDetectSourceDirs(projectRoot)\n const files = await discoverFiles(projectRoot, {\n paths: scanDirs,\n include: options?.include,\n exclude: options?.exclude,\n })\n\n // Group files by directory\n const dirFiles = new Map<string, string[]>()\n const fileTypes: Record<string, number> = {}\n\n for (const relPath of files) {\n const parts = relPath.split('/')\n const dir = parts.slice(0, -1).join('/') || '.'\n const ext = extname(relPath)\n\n if (!dirFiles.has(dir)) dirFiles.set(dir, [])\n dirFiles.get(dir)!.push(relPath)\n\n fileTypes[ext] = (fileTypes[ext] ?? 0) + 1\n }\n\n // Sample files per directory and count candidates\n const byDirectory: Record<string, { files: number; candidates: number }> = {}\n const freqMap = new Map<string, number>()\n let totalCandidatesEstimate = 0\n\n for (const [dir, dirFileList] of dirFiles) {\n const totalInDir = dirFileList.length\n const sampleFiles = dirFileList.slice(0, SUMMARY_SAMPLE_SIZE)\n let sampleCandidates = 0\n\n const samplePromises = sampleFiles.map(async (relPath) => {\n const filePath = join(projectRoot, relPath)\n const content = await readText(filePath)\n if (!content) return []\n\n const ext = extname(filePath)\n return extractStrings(filePath, content, ext)\n })\n\n const sampleResults = await Promise.all(samplePromises)\n\n for (const extractions of sampleResults) {\n for (const extraction of extractions) {\n // Apply same filters as scanCandidates\n if (extraction.value.length < minLength || extraction.value.length > maxLength) continue\n\n const contentScore: number = (extraction as unknown as { contentScore?: number }).contentScore ?? calculateContentScore(extraction)\n if (contentScore < minScore) continue\n\n sampleCandidates++\n\n // Track frequencies for top_repeated\n const prev = freqMap.get(extraction.value) ?? 0\n freqMap.set(extraction.value, prev + 1)\n }\n }\n\n // Estimate for full directory\n const avgPerFile = sampleFiles.length > 0 ? sampleCandidates / sampleFiles.length : 0\n const estimatedCandidates = Math.round(avgPerFile * totalInDir)\n\n byDirectory[dir] = {\n files: totalInDir,\n candidates: estimatedCandidates,\n }\n\n totalCandidatesEstimate += estimatedCandidates\n }\n\n // Top repeated strings\n const topRepeated = [...freqMap.entries()]\n .filter(([, count]) => count >= 2)\n .toSorted((a, b) => b[1] - a[1])\n .slice(0, 20)\n .map(([value, count]) => ({ value, count }))\n\n return {\n total_files: files.length,\n total_candidates_estimate: totalCandidatesEstimate,\n by_directory: byDirectory,\n top_repeated: topRepeated,\n sampling_note: `Based on first ${SUMMARY_SAMPLE_SIZE} files per directory. Counts are from sampled subset, not project-wide.`,\n file_types: fileTypes,\n }\n}\n"],"mappings":";;;;;AAiBA,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,cAAc;AACpB,MAAM,mBAAmB;AACzB,MAAM,iBAAiB;AACvB,MAAM,cAAc;AACpB,MAAM,0BAA0B;AAChC,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,gBAAgB;AACtB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,iBAAiB;AAEvB,MAAM,eAAe,IAAI,IAAI;CAAC;CAAU;CAAS;CAAW;CAAO,CAAC;AAIpE,SAAS,UAAU,KA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I,mBAAmB;EAEvB,MAAM,iBAAiB,YAAY,IAAI,OAAO,YAAY;GACxD,MAAM,WAAW,KAAK,aAAa,QAAQ;GAC3C,MAAM,UAAU,MAAM,SAAS,SAAS;AACxC,OAAI,CAAC,QAAS,QAAO,EAAE;AAGvB,UAAO,eAAe,UAAU,SADpB,QAAQ,SAAS,CACgB;IAC7C;EAEF,MAAM,gBAAgB,MAAM,QAAQ,IAAI,eAAe;AAEvD,OAAK,MAAM,eAAe,cACxB,MAAK,MAAM,cAAc,aAAa;AAEpC,OAAI,WAAW,MAAM,SAAS,aAAa,WAAW,MAAM,SAAS,UAAW;AAGhF,QAD8B,WAAoD,gBAAgB,sBAAsB,WAAW,IAChH,SAAU;AAE7B;GAGA,MAAM,OAAO,QAAQ,IAAI,WAAW,MAAM,IAAI;AAC9C,WAAQ,IAAI,WAAW,OAAO,OAAO,EAAE;;EAK3C,MAAM,aAAa,YAAY,SAAS,IAAI,mBAAmB,YAAY,SAAS;EACpF,MAAM,sBAAsB,KAAK,MAAM,aAAa,WAAW;AAE/D,cAAY,OAAO;GACjB,OAAO;GACP,YAAY;GACb;AAED,6BAA2B;;CAI7B,MAAM,cAAc,CAAC,GAAG,QAAQ,SAAS,CAAC,CACvC,QAAQ,GAAG,WAAW,SAAS,EAAE,CACjC,UAAU,GAAG,MAAM,EAAE,KAAK,EAAE,GAAG,CAC/B,MAAM,GAAG,GAAG,CACZ,KAAK,CAAC,OAAO,YAAY;EAAE;EAAO;EAAO,EAAE;AAE9C,QAAO;EACL,aAAa,MAAM;EACnB,2BAA2B;EAC3B,cAAc;EACd,cAAc;EACd,eAAe,kBAAkB,oBAAoB;EACrD,YAAY;EACb"}
@@ -1,4 +1,4 @@
1
- import { n as ToolProvider } from "../../server-DZBcZWhE.mjs";
1
+ import { r as ToolProvider } from "../../server-B1KfvywF.mjs";
2
2
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
3
3
  import http from "node:http";
4
4
 
@@ -53,6 +53,16 @@ interface HttpMcpServerResolverOptions {
53
53
  * Defaults to 15 minutes.
54
54
  */
55
55
  sessionTtlMs?: number;
56
+ /**
57
+ * Optional tenant binding. When set, the fingerprint computed on the
58
+ * session-creating request is stored with the session, and every
59
+ * follow-up request carrying that `Mcp-Session-Id` must produce the
60
+ * same fingerprint (e.g. derive it from the tenant headers the proxy
61
+ * injects). A mismatch answers 404 — per the Streamable HTTP spec the
62
+ * client then re-initializes and gets a session bound to its own
63
+ * provider. This closes session-id replay across tenants.
64
+ */
65
+ sessionFingerprint?: (req: http.IncomingMessage) => string | undefined;
56
66
  }
57
67
  interface HttpMcpServerHandle {
58
68
  server: http.Server;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/server/http/server.ts"],"mappings":";;;;;UAOiB,oBAAA;;EAEf,WAAA;EAFe;EAIf,SAAA;;EAEA,IAAA;AAAA;AAAA,UAGe,4BAAA;EAHf;EAKA,QAAA,EAAU,YAAA;EALN;EAOJ,WAAA;EAJ2C;EAM3C,SAAA;EAJsB;EAMtB,IAAA;AAAA;;;;;;AAeF;;;;;;;UAAiB,4BAAA;EAOuD;;;;;;EAAtE,eAAA,GAAkB,GAAA,EAAK,IAAA,CAAK,eAAA,KAAoB,YAAA,GAAe,OAAA,CAAQ,YAAA;EAAA;EAEvE,WAAA;EAEA;EAAA,SAAA;EAQA;EANA,IAAA;EAMY;AAGd;;;;EAHE,YAAA;AAAA;AAAA,UAGe,mBAAA;EACf,MAAA,EAAQ,IAAA,CAAK,MAAA;EAAb;;;;;;EAOA,GAAA,EAAK,SAAA;EACL,GAAA;EACA,KAAA,QAAa,OAAA;AAAA;AAmBf;;;;;;;;;;;;;;AAAA,iBAAsB,kBAAA,CACpB,IAAA,EAAM,oBAAA;EAAyB,IAAA;EAAc,IAAA;AAAA,IAC5C,OAAA,CAAQ,mBAAA;;;;;;;;;;;;;;;iBAgCW,sBAAA,CACpB,IAAA,GAAO,4BAAA,GAA+B,4BAAA;EAAkC,IAAA;EAAc,IAAA;AAAA,IACrF,OAAA,CAAQ,mBAAA"}
1
+ {"version":3,"file":"index.d.mts","names":[],"sources":["../../../src/server/http/server.ts"],"mappings":";;;;;UAOiB,oBAAA;;EAEf,WAAA;EAFe;EAIf,SAAA;;EAEA,IAAA;AAAA;AAAA,UAGe,4BAAA;EAHf;EAKA,QAAA,EAAU,YAAA;EALN;EAOJ,WAAA;EAJ2C;EAM3C,SAAA;EAJsB;EAMtB,IAAA;AAAA;;;;;;AAeF;;;;;;;UAAiB,4BAAA;EA6BgC;;;;;;EAtB/C,eAAA,GAAkB,GAAA,EAAK,IAAA,CAAK,eAAA,KAAoB,YAAA,GAAe,OAAA,CAAQ,YAAA;EAAR;EAE/D,WAAA;EAAA;EAEA,SAAA;EAEA;EAAA,IAAA;EAgBA;;;;;EAVA,YAAA;EAae;;;;;;;;;EAHf,kBAAA,IAAsB,GAAA,EAAK,IAAA,CAAK,eAAA;AAAA;AAAA,UAGjB,mBAAA;EACf,MAAA,EAAQ,IAAA,CAAK,MAAA;EAQb;;;;;AAoBF;EArBE,GAAA,EAAK,SAAA;EACL,GAAA;EACA,KAAA,QAAa,OAAA;AAAA;;;;;;;;;;;;AAqDf;;;iBAlCsB,kBAAA,CACpB,IAAA,EAAM,oBAAA;EAAyB,IAAA;EAAc,IAAA;AAAA,IAC5C,OAAA,CAAQ,mBAAA;;;;;;;;;;;;;;;iBAgCW,sBAAA,CACpB,IAAA,GAAO,4BAAA,GAA+B,4BAAA;EAAkC,IAAA;EAAc,IAAA;AAAA,IACrF,OAAA,CAAQ,mBAAA"}
@@ -10,16 +10,16 @@ import "../../branch-lifecycle-D7tXOE4f.mjs";
10
10
  import "../../id-DV_T9Ic8.mjs";
11
11
  import "../../transaction-qliKvBRL.mjs";
12
12
  import "../../local-BZEUWBoC.mjs";
13
- import "../../detect-eWS6lvoH.mjs";
14
- import "../../annotations-BFJbfSKe.mjs";
15
- import { t as createServer } from "../../server-tTuinKHD.mjs";
16
- import "../../validator-Z3DGNWQ6.mjs";
17
- import "../../scan-config-jC6XmiqF.mjs";
18
- import "../../graph-builder-DXv2JEp-.mjs";
19
- import "../../scanner-DKMwc03k.mjs";
20
- import "../../tsx-parser-CQc6nr-o.mjs";
21
- import "../../apply-manager-BRmB27H5.mjs";
22
- import "../../doctor-qiUKCy9b.mjs";
13
+ import "../../detect-wVSI9VuY.mjs";
14
+ import "../../annotations-DSzewhL4.mjs";
15
+ import { n as createServer } from "../../server-B6_fzRmK.mjs";
16
+ import "../../validator-8vaPxSba.mjs";
17
+ import "../../scan-config-BGUflS8t.mjs";
18
+ import "../../graph-builder-CRUX_8mA.mjs";
19
+ import "../../scanner-VOwrKLGC.mjs";
20
+ import "../../tsx-parser-B_aI_C2r.mjs";
21
+ import "../../apply-manager-BnPbPXFG.mjs";
22
+ import "../../doctor-BTToHt0y.mjs";
23
23
  import { randomUUID } from "node:crypto";
24
24
  import http from "node:http";
25
25
  import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@@ -107,6 +107,7 @@ async function startMultiTenantHttpMcpServer(opts) {
107
107
  authToken: opts.authToken,
108
108
  resolveProvider: opts.resolveProvider,
109
109
  projectRoot: opts.projectRoot,
110
+ sessionFingerprint: opts.sessionFingerprint,
110
111
  sessions
111
112
  });
112
113
  });
@@ -139,6 +140,10 @@ async function handleMultiTenantRequest(req, res, ctx) {
139
140
  const existingSessionId = pickSessionId(req.headers[MCP_SESSION_HEADER]);
140
141
  if (existingSessionId && ctx.sessions.has(existingSessionId)) {
141
142
  const session = ctx.sessions.get(existingSessionId);
143
+ if (ctx.sessionFingerprint && ctx.sessionFingerprint(req) !== session.fingerprint) {
144
+ writeJson(res, 404, { error: "Session not found" });
145
+ return;
146
+ }
142
147
  session.lastUsed = Date.now();
143
148
  try {
144
149
  await session.transport.handleRequest(req, res);
@@ -148,8 +153,10 @@ async function handleMultiTenantRequest(req, res, ctx) {
148
153
  return;
149
154
  }
150
155
  try {
156
+ const provider = await ctx.resolveProvider(req);
157
+ const fingerprint = ctx.sessionFingerprint?.(req);
151
158
  const mcp = createServer({
152
- provider: await ctx.resolveProvider(req),
159
+ provider,
153
160
  projectRoot: ctx.projectRoot
154
161
  });
155
162
  const transport = new StreamableHTTPServerTransport({
@@ -158,7 +165,8 @@ async function handleMultiTenantRequest(req, res, ctx) {
158
165
  ctx.sessions.set(sessionId, {
159
166
  mcp,
160
167
  transport,
161
- lastUsed: Date.now()
168
+ lastUsed: Date.now(),
169
+ fingerprint
162
170
  });
163
171
  }
164
172
  });