@abapify/adt-services 0.4.27 → 0.4.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":["nativeGlob","DEFAULT_OPERATIONS"],"sources":["../src/services/badi/index.ts","../src/services/changeset/service.ts","../src/utils/format-loader.ts","../src/services/checkin/filetree.ts","../src/services/checkin/diff.ts","../src/services/checkin/plan.ts","../src/services/checkin/apply.ts","../src/services/checkin/service.ts","../src/services/connection/service.ts","../src/services/cts/transport-lifecycle.ts","../src/services/cts/transport-metadata.ts","../src/shared/adt-client.ts","../src/utils/destinations.ts","../src/utils/transport-numbers.ts","../src/services/import/object-selection.ts","../src/services/import/service.ts","../src/utils/lock-helpers.ts","../src/services/source/service.ts","../src/services/source-history/service.ts","../src/services/check/service.ts","../src/utils/auth.ts","../src/utils/progress-reporter.ts","../src/ui/components/link.ts","../src/utils/adt-http-options.ts","../src/utils/adt-client-v2.ts"],"sourcesContent":["/**\n * BAdI services — ENHO metadata (enhoxhb) and unified read (classic vit/wb + ENHO).\n *\n * - `getBadiInfo` / `parseEnhancementImplementation` — ENHO/XHB metadata from\n * `/sap/bc/adt/enhancements/enhoxhb/{name}` (used by `adt badi <name>`).\n * - `BadiService` — auto-detect kind and read classic SXSD/SXCI or ENHO/XHH.\n */\nimport type { AdtClient } from '@abapify/adt-client';\n\nimport type { BasicObjectPropertiesResponse } from '@abapify/adt-contracts';\nimport { DOMParser } from '@xmldom/xmldom';\n\nconst NS_ENHO = 'http://www.sap.com/adt/enhancements/enho';\nconst NS_ADTCORE = 'http://www.sap.com/adt/core';\n\ntype XmlElement = import('@xmldom/xmldom').Element;\n\nexport interface BadiImplementation {\n name: string;\n shortText: string;\n active: boolean;\n default: boolean;\n example: boolean;\n implementingClass: string;\n badiDefinition: string;\n enhancementSpot: string;\n}\n\nexport interface BadiInfo {\n name: string;\n description: string;\n type: string;\n package: string;\n responsible: string;\n version: string;\n technology: string;\n switchSupported: boolean;\n badiImplementations: BadiImplementation[];\n}\n\ninterface NamespaceAccessor {\n attr(el: XmlElement | null | undefined, local: string): string;\n bool(el: XmlElement | null | undefined, local: string): boolean;\n child(parent: XmlElement, local: string): XmlElement | null;\n children(parent: XmlElement, local: string): XmlElement[];\n}\n\nfunction namespaceAccessor(ns: string): NamespaceAccessor {\n return {\n attr(el, local) {\n return el?.getAttributeNS(ns, local) ?? '';\n },\n bool(el, local) {\n return this.attr(el, local).toLowerCase() === 'true';\n },\n child(parent, local) {\n const list = parent.getElementsByTagNameNS(ns, local);\n return (list.item(0) as XmlElement | null) ?? null;\n },\n children(parent, local) {\n const list = parent.getElementsByTagNameNS(ns, local);\n const result: XmlElement[] = [];\n for (let i = 0; i < list.length; i++) {\n const node = list.item(i) as XmlElement | null;\n if (node) result.push(node);\n }\n return result;\n },\n };\n}\n\nconst enho = namespaceAccessor(NS_ENHO);\nconst adtcore = namespaceAccessor(NS_ADTCORE);\n\nfunction rootAttr(root: XmlElement, local: string): string {\n return adtcore.attr(root, local) || root.getAttribute(local) || '';\n}\n\nfunction parseBadiImplementation(node: XmlElement): BadiImplementation {\n return {\n name: enho.attr(node, 'name'),\n shortText: enho.attr(node, 'shortText'),\n active: enho.bool(node, 'active'),\n default: enho.bool(node, 'default'),\n example: enho.bool(node, 'example'),\n implementingClass: adtcore.attr(\n enho.child(node, 'implementingClass'),\n 'name',\n ),\n badiDefinition: adtcore.attr(enho.child(node, 'badiDefinition'), 'name'),\n enhancementSpot: adtcore.attr(enho.child(node, 'enhancementSpot'), 'name'),\n };\n}\n\nfunction parseBadiInfo(root: XmlElement): BadiInfo {\n const contentCommon = enho.child(root, 'contentCommon');\n\n return {\n name: rootAttr(root, 'name'),\n description: rootAttr(root, 'description'),\n type: rootAttr(root, 'type'),\n package: adtcore.attr(adtcore.child(root, 'packageRef'), 'name'),\n responsible: rootAttr(root, 'responsible'),\n version: rootAttr(root, 'version'),\n technology: enho.attr(contentCommon, 'toolType'),\n switchSupported: enho.bool(contentCommon, 'switchSupported'),\n badiImplementations: enho\n .children(root, 'badiImplementation')\n .map(parseBadiImplementation),\n };\n}\n\n/**\n * Parse an `enho:objectData` XML document into a `BadiInfo` structure.\n */\nexport function parseEnhancementImplementation(xml: string): BadiInfo {\n const doc = new DOMParser({\n onError: () => {\n /* swallow parse warnings; caller handles malformed XML via errors */\n },\n }).parseFromString(xml, 'text/xml');\n\n const root = doc.documentElement;\n if (!root) {\n throw new Error('Empty or malformed ENHO XML response');\n }\n\n return parseBadiInfo(root as XmlElement);\n}\n\n/**\n * Fetch ENHO metadata for a BAdI / enhancement implementation and parse\n * the BAdI implementation list.\n */\nexport async function getBadiInfo({\n client,\n name,\n}: {\n client: AdtClient;\n name: string;\n}): Promise<BadiInfo> {\n const response = await client.fetch(\n `/sap/bc/adt/enhancements/enhoxhb/${encodeURIComponent(name.toLowerCase())}`,\n {\n headers: { Accept: 'application/vnd.sap.adt.enh.enhoxhb.v4+xml' },\n },\n );\n\n if (typeof response !== 'string') {\n throw new Error('Unexpected non-XML response from ENHO endpoint');\n }\n\n return parseEnhancementImplementation(response);\n}\n\nexport type BadiKind = 'definition' | 'implementation' | 'enhancement';\n\nexport type BadiMetadata = {\n name: string;\n type: string;\n kind: BadiKind;\n description?: string;\n language?: string;\n version?: string;\n packageName?: string;\n packageUri?: string;\n responsible?: string;\n masterLanguage?: string;\n masterSystem?: string;\n /** When SAP supplies a container reference, it can be used to validate lineage. */\n containerRef?: { name?: string; type?: string };\n};\n\nexport type BadiReadResult = BadiMetadata & {\n /** ENHO/XHB metadata when kind is enhancement. */\n enhancement?: BadiInfo;\n source?: string;\n /** Present when `--implementations` is used on a classic definition. */\n implementations?: BadiMetadata[];\n};\n\n/** @deprecated Use BadiMetadata */\nexport type ClassicBadiMetadata = Omit<BadiMetadata, 'kind'>;\n\nconst BADI_REPOSITORY_TYPES = new Set(['SXSD/XD', 'SXCI/XI', 'ENHO/XHH']);\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { status?: unknown }).status === 404\n );\n}\n\nfunction badiKindFromType(adtType: string): BadiKind {\n const type = adtType.toUpperCase();\n if (type === 'SXSD/XD') return 'definition';\n if (type === 'SXCI/XI') return 'implementation';\n return 'enhancement';\n}\n\nfunction extractSearchObjects(results: unknown): Array<{\n name?: string;\n type?: string;\n}> {\n const record = results as Record<string, unknown>;\n let raw:\n | Array<{ name?: string; type?: string }>\n | { name?: string; type?: string }\n | undefined;\n\n if (record.objectReferences && typeof record.objectReferences === 'object') {\n const refs = record.objectReferences as {\n objectReference?: typeof raw;\n };\n raw = refs.objectReference;\n } else if (record.objectReference) {\n raw = record.objectReference as typeof raw;\n } else if (record.mainObject && typeof record.mainObject === 'object') {\n const main = record.mainObject as { objectReference?: typeof raw };\n raw = main.objectReference;\n }\n\n if (!raw) return [];\n return Array.isArray(raw) ? raw : [raw];\n}\n\nexport function normalizeClassicBadiMetadata({\n response,\n kind,\n}: {\n response: BasicObjectPropertiesResponse;\n kind: 'definition' | 'implementation';\n}): BadiMetadata {\n if (!('mainObject' in response) || !response.mainObject) {\n throw new Error('BAdI response missing mainObject');\n }\n const main = response.mainObject;\n return {\n kind,\n name: (main.name ?? '').toUpperCase(),\n type: main.type ?? '',\n description: main.description,\n language: main.language,\n version: main.version,\n packageName: main.packageRef?.name,\n packageUri: main.packageRef?.uri,\n responsible: main.responsible,\n masterLanguage: main.masterLanguage,\n masterSystem: main.masterSystem,\n containerRef: main.containerRef\n ? { name: main.containerRef.name, type: main.containerRef.type }\n : undefined,\n };\n}\n\nfunction searchQueriesForDefinition({ name }: { name: string }): string[] {\n const normalized = name.trim().toUpperCase();\n const queries = new Set<string>([\n `*${normalized}*`,\n `*${normalized.replace(/_/g, '*')}*`,\n ]);\n const parts = normalized.split('_').filter(Boolean);\n if (parts.length >= 2) {\n const tail2 = parts.slice(-2).join('_');\n if (tail2.length >= 10) {\n queries.add(`*${tail2}*`);\n }\n }\n return [...queries];\n}\n\ninterface ServiceContext {\n readonly client: AdtClient;\n readonly normalized: string;\n}\n\ninterface ReadContext extends ServiceContext {\n readonly options?: {\n includeSource?: boolean;\n includeImplementations?: boolean;\n };\n}\n\nasync function resolveBySearch(\n ctx: ServiceContext,\n): Promise<BadiKind | undefined> {\n const search =\n await ctx.client.adt.repository.informationsystem.search.quickSearch({\n query: ctx.normalized,\n maxResults: 20,\n });\n const matches = extractSearchObjects(search).filter(\n (obj) =>\n obj.name?.toUpperCase() === ctx.normalized &&\n obj.type &&\n BADI_REPOSITORY_TYPES.has(obj.type.toUpperCase()),\n );\n if (matches.length === 1) {\n return badiKindFromType(matches[0].type!);\n }\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous BAdI name ${ctx.normalized}: ${matches.map((m) => m.type).join(', ')}`,\n );\n }\n return undefined;\n}\n\nasync function runProbe(\n ctx: ServiceContext & { kind: BadiKind; expectedType: string },\n): Promise<BadiKind | undefined> {\n const response =\n ctx.kind === 'definition'\n ? await ctx.client.adt.vit.wb.objectProperties.getDefinition(\n ctx.normalized,\n )\n : await ctx.client.adt.vit.wb.objectProperties.getImplementation(\n ctx.normalized,\n );\n if (!('mainObject' in response) || !response.mainObject) {\n return undefined;\n }\n const main = response.mainObject;\n if (\n main.type?.toUpperCase() === ctx.expectedType &&\n main.name?.toUpperCase() === ctx.normalized\n ) {\n return ctx.kind;\n }\n return undefined;\n}\n\nasync function resolveEnhancement(\n ctx: ServiceContext,\n): Promise<BadiKind | undefined> {\n try {\n await getBadiInfo({ client: ctx.client, name: ctx.normalized });\n return 'enhancement';\n } catch (error) {\n if (!isNotFound(error)) throw error;\n return undefined;\n }\n}\n\nasync function resolveKind(ctx: ServiceContext): Promise<BadiKind> {\n const bySearch = await resolveBySearch(ctx);\n if (bySearch) return bySearch;\n\n const definition = await runProbe({\n ...ctx,\n kind: 'definition',\n expectedType: 'SXSD/XD',\n });\n if (definition) return definition;\n\n const implementation = await runProbe({\n ...ctx,\n kind: 'implementation',\n expectedType: 'SXCI/XI',\n });\n if (implementation) return implementation;\n\n const enhancement = await resolveEnhancement(ctx);\n if (enhancement) return enhancement;\n\n throw new Error(`BAdI object not found: ${ctx.normalized}`);\n}\n\nasync function readDefinition(ctx: ServiceContext): Promise<BadiMetadata> {\n const response = await ctx.client.adt.vit.wb.objectProperties.getDefinition(\n ctx.normalized,\n );\n return normalizeClassicBadiMetadata({ response, kind: 'definition' });\n}\n\nasync function readImplementation(ctx: ServiceContext): Promise<BadiMetadata> {\n const response =\n await ctx.client.adt.vit.wb.objectProperties.getImplementation(\n ctx.normalized,\n );\n return normalizeClassicBadiMetadata({ response, kind: 'implementation' });\n}\n\nasync function readEnhancement(ctx: ReadContext): Promise<BadiReadResult> {\n const lower = ctx.normalized.toLowerCase();\n const info = await getBadiInfo({ client: ctx.client, name: ctx.normalized });\n const source = ctx.options?.includeSource\n ? String(await ctx.client.adt.enhancements.enhoxhh.source.main.get(lower))\n : undefined;\n return {\n kind: 'enhancement',\n name: info.name.toUpperCase(),\n type: info.type,\n description: info.description,\n version: info.version,\n packageName: info.package,\n responsible: info.responsible,\n enhancement: info,\n source,\n };\n}\n\nasync function getBadi(ctx: ReadContext): Promise<BadiReadResult> {\n const kind = await resolveKind(ctx);\n switch (kind) {\n case 'definition': {\n const definition = await readDefinition(ctx);\n if (!ctx.options?.includeImplementations) {\n return definition;\n }\n const implementations = await listImplementations(ctx);\n return { ...definition, implementations };\n }\n case 'implementation':\n return readImplementation(ctx);\n case 'enhancement':\n return readEnhancement(ctx);\n default:\n throw new Error(`Unsupported BAdI kind: ${kind satisfies never}`);\n }\n}\n\ninterface SearchCandidateContext extends ServiceContext {\n readonly query: string;\n readonly objectType?: 'SXCI';\n readonly seen: Set<string>;\n}\n\nfunction candidateNames(ctx: {\n search: unknown;\n normalized: string;\n seen: Set<string>;\n}): string[] {\n const names: string[] = [];\n for (const obj of extractSearchObjects(ctx.search)) {\n if (obj.type?.toUpperCase() !== 'SXCI/XI') continue;\n const implName = obj.name?.toUpperCase();\n if (!implName) continue;\n if (implName === ctx.normalized) continue;\n if (ctx.seen.has(implName)) continue;\n ctx.seen.add(implName);\n names.push(implName);\n }\n return names;\n}\n\nasync function tryReadImplementation(ctx: {\n client: AdtClient;\n definitionName: string;\n implName: string;\n}): Promise<BadiMetadata | undefined> {\n try {\n const impl = await readImplementation({\n client: ctx.client,\n normalized: ctx.implName,\n });\n const containerName = impl.containerRef?.name?.toUpperCase();\n if (containerName && containerName !== ctx.definitionName) {\n return undefined;\n }\n return impl;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n return undefined;\n }\n}\n\nasync function collectSearchCandidates(\n ctx: SearchCandidateContext,\n): Promise<BadiMetadata[]> {\n const params: { query: string; maxResults: number; objectType?: 'SXCI' } = {\n query: ctx.query,\n maxResults: 100,\n };\n if (ctx.objectType) {\n params.objectType = ctx.objectType;\n }\n const search =\n await ctx.client.adt.repository.informationsystem.search.quickSearch(\n params,\n );\n\n const names = candidateNames({\n search,\n normalized: ctx.normalized,\n seen: ctx.seen,\n });\n const found: BadiMetadata[] = [];\n for (const implName of names) {\n const impl = await tryReadImplementation({\n client: ctx.client,\n definitionName: ctx.normalized,\n implName,\n });\n if (impl) found.push(impl);\n }\n return found;\n}\n\nasync function listImplementations(\n ctx: ServiceContext,\n): Promise<BadiMetadata[]> {\n await readDefinition(ctx);\n\n const queries = searchQueriesForDefinition({ name: ctx.normalized });\n const seen = new Set<string>();\n const all: BadiMetadata[] = [];\n\n for (const query of queries) {\n all.push(\n ...(await collectSearchCandidates({\n client: ctx.client,\n normalized: ctx.normalized,\n query,\n seen,\n })),\n );\n all.push(\n ...(await collectSearchCandidates({\n client: ctx.client,\n normalized: ctx.normalized,\n query,\n objectType: 'SXCI',\n seen,\n })),\n );\n }\n\n return all.sort((a, b) => a.name.localeCompare(b.name));\n}\n\nexport class BadiService {\n constructor(private readonly client: AdtClient) {}\n\n private contextFor(name: string): ServiceContext {\n return { client: this.client, normalized: name.trim().toUpperCase() };\n }\n\n private readContextFor(\n name: string,\n options?: { includeSource?: boolean; includeImplementations?: boolean },\n ): ReadContext {\n return { ...this.contextFor(name), options };\n }\n\n async resolveKind({ name }: { name: string }): Promise<BadiKind> {\n return resolveKind(this.contextFor(name));\n }\n\n async get({\n name,\n options,\n }: {\n name: string;\n options?: { includeSource?: boolean; includeImplementations?: boolean };\n }): Promise<BadiReadResult> {\n return getBadi(this.readContextFor(name, options));\n }\n\n async getDefinition({ name }: { name: string }): Promise<BadiMetadata> {\n return readDefinition(this.contextFor(name));\n }\n\n async getImplementation({ name }: { name: string }): Promise<BadiMetadata> {\n return readImplementation(this.contextFor(name));\n }\n\n /**\n * List classic BAdI implementations (SXCI/XI) for a definition name.\n * Uses repository quick search heuristics — authoritative active/inactive\n * state requires SXC_ATTR (not exposed on all systems).\n */\n async listImplementations({\n name,\n }: {\n name: string;\n }): Promise<BadiMetadata[]> {\n return listImplementations(this.contextFor(name));\n }\n}\n\n/** @deprecated Use BadiService */\nexport const ClassicBadiService = BadiService;\n","/**\n * `ChangesetService` — transport-agnostic transactional unit-of-work.\n *\n * Wave 3 of the MCP HTTP transport introduces changesets so that an AI\n * agent can lock + stage several source writes, review them, and then\n * atomically commit (batch activate) or roll back (release locks).\n *\n * Architectural contract:\n *\n * - This service is **pure business logic**: no `console.*`, no\n * commander, no file I/O. Callers feed it an `AdtClient` and a\n * `Logger` and receive structured results / thrown errors.\n * - Both the CLI (`adt changeset …`) and MCP tools\n * (`changeset_begin` / `changeset_add` / `changeset_commit` /\n * `changeset_rollback`) delegate straight through. That is the only\n * way to keep CLI ↔ MCP parity honest.\n * - Locks are acquired and released through `@abapify/adt-locks` —\n * the single lock service in this monorepo. We never hand-roll lock\n * protocol here (nor in the MCP tools).\n *\n * Commit strategy:\n *\n * SAP ADT supports batch activation via a single POST to\n * `/sap/bc/adt/activation` with an `adtcore:objectReferences` body\n * carrying N references. We use the typed `activation.activate.post`\n * contract from `@abapify/adt-client` for this — NOT a manual XML\n * string. One HTTP round-trip, all entries activated together.\n *\n * If activation fails with an error, `commit` still tries to release\n * every lock (best-effort) and surfaces both the activation error and\n * the per-entry release outcomes in the result.\n *\n * Rollback semantics (explicit):\n *\n * Rollback releases locks but does NOT revert the PUTs that `add`\n * already persisted on SAP. SAP has no transactional \"discard\" API\n * over ADT: the inactive version stays on the system until the next\n * edit/activate cycle. This matches Eclipse ADT's behaviour when a\n * developer closes the editor without activating.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n createLockService,\n resolveLockCorrelation,\n type LockService,\n} from '@abapify/adt-locks';\nimport type { AdtClient } from '@abapify/adt-client';\nimport type { Logger } from '@abapify/adt-client';\nimport type { InferTypedSchema } from '@abapify/adt-schemas';\nimport { adtcore } from '@abapify/adt-schemas';\n\nexport type ChangesetStatus =\n 'open' | 'committing' | 'committed' | 'rolled_back';\n\nexport interface ChangesetEntry {\n objectUri: string;\n objectType: string;\n objectName: string;\n lockHandle: string;\n action: 'update' | 'create';\n createdAt: number;\n}\n\nexport interface Changeset {\n id: string;\n openedAt: number;\n status: ChangesetStatus;\n entries: ChangesetEntry[];\n description?: string;\n}\n\nexport interface AddEntryArgs {\n objectUri: string;\n objectType: string;\n objectName: string;\n source: string;\n transport?: string;\n}\n\nexport interface CommitResult {\n activated: string[];\n failed: { uri: string; error: string }[];\n}\n\nexport interface RollbackResult {\n released: string[];\n failed: { uri: string; error: string }[];\n}\n\ntype ObjectReferencesBody = Extract<\n InferTypedSchema<typeof adtcore>,\n { objectReferences: unknown }\n>;\n\n/** Create a brand-new empty changeset (no SAP interaction yet). */\nexport function createChangeset(description?: string): Changeset {\n return {\n id: randomUUID(),\n openedAt: Date.now(),\n status: 'open',\n entries: [],\n description,\n };\n}\n\nexport class ChangesetService {\n private readonly locks: LockService;\n\n constructor(\n private readonly client: AdtClient,\n private readonly logger?: Logger,\n ) {\n this.locks = createLockService(client);\n }\n\n /** Transport-agnostic: returns a fresh Changeset descriptor. */\n begin(description?: string): Changeset {\n const cs = createChangeset(description);\n this.logger?.debug('changeset: begin', { id: cs.id });\n return cs;\n }\n\n /**\n * Lock the object, PUT the source, and register the entry. Throws on\n * lock or PUT failure; lock is released in the error path so the\n * caller never sees a half-applied entry.\n */\n async add(changeset: Changeset, args: AddEntryArgs): Promise<ChangesetEntry> {\n if (changeset.status !== 'open') {\n throw new Error(\n `changeset ${changeset.id} is not open (status=${changeset.status})`,\n );\n }\n\n const lock = await this.locks.lock(args.objectUri, {\n transport: args.transport,\n objectName: args.objectName,\n objectType: args.objectType,\n });\n const effectiveTransport = resolveLockCorrelation(lock, args.transport);\n\n try {\n const params = new URLSearchParams();\n params.set('lockHandle', lock.handle);\n if (effectiveTransport) params.set('corrNr', effectiveTransport);\n await this.client.fetch(\n `${args.objectUri}/source/main?${params.toString()}`,\n {\n method: 'PUT',\n headers: { 'Content-Type': 'text/plain' },\n body: args.source,\n },\n );\n } catch (err) {\n // Best-effort unlock on PUT failure so we don't leak a lock.\n try {\n await this.locks.unlock(args.objectUri, { lockHandle: lock.handle });\n } catch (unlockErr) {\n this.logger?.warn('changeset: failed to unlock after PUT failure', {\n objectUri: args.objectUri,\n error:\n unlockErr instanceof Error ? unlockErr.message : String(unlockErr),\n });\n }\n throw err;\n }\n\n const entry: ChangesetEntry = {\n objectUri: args.objectUri,\n objectType: args.objectType.toUpperCase(),\n objectName: args.objectName.toUpperCase(),\n lockHandle: lock.handle,\n action: 'update',\n createdAt: Date.now(),\n };\n changeset.entries.push(entry);\n this.logger?.debug('changeset: add', {\n id: changeset.id,\n objectUri: args.objectUri,\n });\n return entry;\n }\n\n /**\n * Batch-activate every entry, then release every lock. The changeset\n * is mutated in place: `status` advances to `committing` during the\n * call and `committed` on success. On activation failure it is left\n * as `committing` and the error is rethrown after lock cleanup.\n */\n async commit(changeset: Changeset): Promise<CommitResult> {\n if (changeset.status !== 'open') {\n throw new Error(\n `changeset ${changeset.id} is not open (status=${changeset.status})`,\n );\n }\n\n changeset.status = 'committing';\n\n if (changeset.entries.length === 0) {\n changeset.status = 'committed';\n return { activated: [], failed: [] };\n }\n\n const body: ObjectReferencesBody = {\n objectReferences: {\n objectReference: changeset.entries.map((e) => ({\n uri: e.objectUri,\n type: e.objectType,\n name: e.objectName,\n })),\n },\n };\n\n const result: CommitResult = { activated: [], failed: [] };\n let activationError: Error | undefined;\n\n try {\n await this.client.adt.activation.activate.post(\n { method: 'activate', preauditRequested: true },\n body,\n );\n result.activated = changeset.entries.map((e) => e.objectUri);\n } catch (err) {\n activationError = err instanceof Error ? err : new Error(String(err));\n result.failed = changeset.entries.map((e) => ({\n uri: e.objectUri,\n error: activationError!.message,\n }));\n }\n\n // Release locks regardless of activation outcome — a half-activated\n // changeset still has to free SAP-side locks.\n for (const entry of changeset.entries) {\n try {\n await this.locks.unlock(entry.objectUri, {\n lockHandle: entry.lockHandle,\n });\n } catch (err) {\n this.logger?.warn('changeset: unlock failed during commit', {\n id: changeset.id,\n objectUri: entry.objectUri,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (activationError) {\n // Caller decides how to surface — the service keeps state at\n // `committing` so a later recovery path can try again if SAP is\n // reachable. The MCP/CLI layer will turn this into a user-visible\n // error and clear the session pointer.\n throw activationError;\n }\n\n changeset.status = 'committed';\n this.logger?.debug('changeset: commit', {\n id: changeset.id,\n activated: result.activated.length,\n });\n return result;\n }\n\n /**\n * Release every lock (best-effort) and mark the changeset\n * `rolled_back`. Does NOT revert PUT'ed source — see file-level\n * comment for rationale.\n */\n async rollback(changeset: Changeset): Promise<RollbackResult> {\n if (changeset.status === 'committed') {\n throw new Error(`changeset ${changeset.id} is already committed`);\n }\n if (changeset.status === 'rolled_back') {\n return { released: [], failed: [] };\n }\n\n const result: RollbackResult = { released: [], failed: [] };\n for (const entry of changeset.entries) {\n try {\n await this.locks.unlock(entry.objectUri, {\n lockHandle: entry.lockHandle,\n });\n result.released.push(entry.objectUri);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n this.logger?.warn('changeset: unlock failed during rollback', {\n id: changeset.id,\n objectUri: entry.objectUri,\n error: message,\n });\n result.failed.push({ uri: entry.objectUri, error: message });\n }\n }\n\n changeset.status = 'rolled_back';\n this.logger?.debug('changeset: rollback', {\n id: changeset.id,\n released: result.released.length,\n failed: result.failed.length,\n });\n return result;\n }\n}\n","/**\n * Format-plugin loader for CLI commands.\n *\n * Format plugins self-register into the global `FormatPlugin` registry when\n * their package is imported. This loader translates the CLI's legacy format\n * spec (`abapgit` / `ag` / `@abapify/adt-plugin-abapgit` / `pkg/preset`) into\n * a live `AdtPlugin` (the higher-level import/export plugin) so existing\n * import services keep working.\n *\n * Built-in format id → package mappings. New built-in formats just need one\n * extra entry here (plus the side-effect import in `cli.ts`).\n */\nimport { getFormatPlugin, type AdtPlugin } from '@abapify/adt-plugin';\n\nconst FORMAT_SHORTCUTS: Record<string, string> = {\n abapgit: '@abapify/adt-plugin-abapgit',\n ag: '@abapify/adt-plugin-abapgit',\n // AFF / gCTS format plugin (E06). `aff` is the primary id; `gcts` is an\n // alias — both share the same on-disk layout (SAP/abap-file-formats).\n aff: '@abapify/adt-plugin-gcts',\n gcts: '@abapify/adt-plugin-gcts',\n};\n\n/** Resolve a CLI format id to its registered package name (if known). */\nfunction resolvePackageForFormatId(id: string): string | undefined {\n return FORMAT_SHORTCUTS[id];\n}\n\n/**\n * Parse format specification with optional preset.\n *\n * Examples:\n * @abapify/adt-plugin-abapgit → { package: '@abapify/adt-plugin-abapgit' }\n * @abapify/adt-plugin-abapgit/full → { package: '@abapify/adt-plugin-abapgit', preset: 'full' }\n * abapgit → { package: '@abapify/adt-plugin-abapgit' } (shortcut)\n * ag → { package: '@abapify/adt-plugin-abapgit' } (shortcut)\n */\nexport function parseFormatSpec(formatSpec: string): {\n package: string;\n preset?: string;\n} {\n if (formatSpec in FORMAT_SHORTCUTS) {\n return { package: FORMAT_SHORTCUTS[formatSpec] };\n }\n\n const parts = formatSpec.split('/');\n if (parts.length === 2) {\n // @abapify/adt-plugin-abapgit\n return { package: formatSpec };\n } else if (parts.length === 3) {\n // @abapify/adt-plugin-abapgit/full\n const package_ = `${parts[0]}/${parts[1]}`;\n const preset = parts[2];\n return { package: package_, preset };\n } else {\n throw new Error(`Invalid format specification: ${formatSpec}`);\n }\n}\n\n/**\n * Load a format plugin by CLI spec.\n *\n * Resolution order:\n * 1. Look up the format id in the {@link FormatPlugin} registry. If it is\n * already registered (e.g. via CLI bootstrap), use it without any dynamic\n * import.\n * 2. Otherwise dynamically `import(packageName)` — this triggers the\n * package's self-registration side-effects — then return the resolved\n * legacy `AdtPlugin` instance from the package's default/named export.\n */\nexport async function loadFormatPlugin(formatSpec: string): Promise<{\n name: string;\n description: string;\n instance: AdtPlugin;\n preset?: string;\n}> {\n const { package: packageName, preset } = parseFormatSpec(formatSpec);\n\n // Fast path: if the format plugin has already self-registered (typical when\n // the CLI bootstrap has side-effect-imported the package), we're done — but\n // we still need the legacy AdtPlugin instance for the import services, so\n // fall through to the dynamic import. The registry lookup merely validates\n // that the requested format is available.\n const builtinId = Object.entries(FORMAT_SHORTCUTS).find(\n ([, pkg]) => pkg === packageName,\n )?.[0];\n if (builtinId && !getFormatPlugin(builtinId)) {\n // Registry is empty for this id — the dynamic import below will populate\n // it via the package's self-registration side-effect.\n }\n\n try {\n const pluginModule = await import(packageName);\n const PluginClass =\n pluginModule.default || pluginModule[Object.keys(pluginModule)[0]];\n\n if (!PluginClass) {\n throw new Error(`No plugin class found in ${packageName}`);\n }\n\n const options = preset ? { preset } : {};\n\n const plugin: AdtPlugin =\n typeof PluginClass === 'function' && PluginClass.prototype\n ? new PluginClass(options)\n : PluginClass;\n\n return {\n name: plugin.name || packageName,\n description: plugin.description || `Plugin from ${packageName}`,\n instance: plugin,\n preset,\n };\n } catch (error: unknown) {\n const err = error as Error;\n if (\n (err as { code?: string }).code === 'MODULE_NOT_FOUND' ||\n err.message?.includes(`Cannot find module '${packageName}'`)\n ) {\n throw new Error(\n `Plugin package '${packageName}' not found. Install it with: bun add ${packageName}`,\n { cause: error },\n );\n }\n throw error;\n }\n}\n\nexport { resolvePackageForFormatId };\n","/**\n * FileTree implementation used by the CheckinService.\n *\n * Mirrors the `FsFileTree` in `@abapify/adt-export` but kept local so the\n * checkin feature doesn't drag an export-time dependency back into\n * `adt-cli` (which would violate the module-boundary rules between\n * adt-cli and plugin-like packages).\n */\nimport {\n readFile,\n readdir,\n access,\n glob as nativeGlob,\n} from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { FileTree } from '@abapify/adt-plugin';\n\nclass FsFileTree implements FileTree {\n constructor(public readonly root: string) {}\n\n async glob(pattern: string): Promise<string[]> {\n const results: string[] = [];\n for await (const path of nativeGlob(pattern, { cwd: this.root })) {\n results.push(path);\n }\n return results;\n }\n\n async read(path: string): Promise<string> {\n const content = await readFile(join(this.root, path), 'utf-8');\n return content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;\n }\n\n async readBuffer(path: string): Promise<Buffer> {\n return readFile(join(this.root, path));\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n await access(join(this.root, path));\n return true;\n } catch {\n return false;\n }\n }\n\n async readdir(path: string): Promise<string[]> {\n return readdir(path ? join(this.root, path) : this.root);\n }\n}\n\nexport function createFsFileTree(root: string): FileTree {\n return new FsFileTree(root);\n}\n","/**\n * ChangePlan — intermediate representation between discovery and apply.\n *\n * Every ChangePlanEntry represents one ADK object about to be pushed into\n * SAP. The diff stage decides `action` by calling `obj.load()` against the\n * remote system:\n *\n * - `create` — remote load threw 404 / not-found.\n * - `update` — remote exists; local differs (or was deserialised with\n * pending sources, which we conservatively treat as\n * \"changed\" because a per-field diff is format-specific).\n * - `unchanged` — remote exists and local source/data match; skip.\n * - `skip` — local object type is not supported by the plugin, or\n * filtered out by the caller.\n *\n * We deliberately avoid computing a field-level diff here: that's a format\n * concern (abapGit vs gCTS normalise XML differently) and will be added via\n * the deferred `FormatPlugin.diff()` method — see E05 follow-ups.\n */\nimport type { AdkObject } from '@abapify/adk';\n\nexport type ChangeAction = 'create' | 'update' | 'unchanged' | 'skip';\n\nexport interface ChangePlanEntry {\n /** ADK object carrying local (deserialised) data. */\n object: AdkObject;\n /** What we intend to do with this object on SAP. */\n action: ChangeAction;\n /** Human-readable reason — used for dry-run output. */\n reason?: string;\n /** Error encountered during diff (load failure that wasn't a 404). */\n error?: string;\n}\n\n/**\n * Compute diff for a single object.\n *\n * Returns the `ChangePlanEntry` without yet mutating anything on SAP. The\n * caller decides whether to group, filter, or apply the plan.\n */\nexport async function diffObject(object: AdkObject): Promise<ChangePlanEntry> {\n // If the format plugin already populated `_pendingSource(s)` or\n // `_pendingDescription`, treat as potentially-changed — we can't be\n // cheaper without a format-specific diff, and `update` is the safe side\n // (SAP will short-circuit on identical content via ETag).\n const hasPending = Boolean(\n (object as unknown as { _pendingSource?: unknown })._pendingSource ||\n (object as unknown as { _pendingSources?: unknown })._pendingSources ||\n (object as unknown as { _pendingDescription?: unknown })\n ._pendingDescription,\n );\n\n try {\n // Save the locally-assembled _data before load() overwrites it with\n // server state (matches the pre-deploy pattern in adt-export).\n const localData = (object as unknown as { _data?: unknown })._data;\n await object.load();\n // Restore the plugin-provided data so the subsequent save uses it.\n (object as unknown as { _data?: unknown })._data = localData;\n\n return {\n object,\n action: hasPending ? 'update' : 'unchanged',\n reason: hasPending\n ? 'local source pending write'\n : 'no local changes detected',\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/404|not[- ]?found/i.test(msg)) {\n return {\n object,\n action: 'create',\n reason: 'remote object does not exist',\n };\n }\n return {\n object,\n action: 'skip',\n error: msg,\n reason: `diff failed: ${msg}`,\n };\n }\n}\n","/**\n * Plan builder — groups ChangePlanEntry items in dependency order for apply.\n *\n * SAP's activation order is **type-class sensitive**: DDIC primitives\n * (domains, data elements, tables, structures, ttypes) must exist before\n * application-level code (classes, interfaces, includes, programs, function\n * groups) can compile against them; CDS artifacts (DDL source, DCL source,\n * behaviour definitions, service definitions, service bindings) must come\n * last because they reference both categories.\n *\n * The grouping is sapcli-inspired (`_resolve_dependencies` in\n * `sap/cli/checkin.py`) but extended to match the ADK type vocabulary.\n */\nimport type { AdkObject } from '@abapify/adk';\nimport { getMainType } from '@abapify/adk';\nimport type { ChangePlanEntry } from './diff';\n\nexport type DependencyTier = 'ddic' | 'app' | 'cds' | 'package' | 'other';\n\n/** Object types classified by dependency tier (main type only). */\nconst TIER_FOR_TYPE: Record<string, DependencyTier> = {\n // DDIC primitives — no dependencies on ABAP code\n DOMA: 'ddic',\n DTEL: 'ddic',\n TABL: 'ddic',\n TTYP: 'ddic',\n VIEW: 'ddic',\n ENQU: 'ddic',\n SHLP: 'ddic',\n // Packages themselves are their own tier — must exist before any content\n DEVC: 'package',\n // Application code — depends on DDIC\n CLAS: 'app',\n INTF: 'app',\n PROG: 'app',\n INCL: 'app',\n FUGR: 'app',\n // CDS / RAP — depends on everything else\n DDLS: 'cds',\n DCLS: 'cds',\n DDLX: 'cds',\n SRVD: 'cds',\n SRVB: 'cds',\n BDEF: 'cds',\n};\n\n/** Order tiers are applied. */\nconst TIER_ORDER: DependencyTier[] = ['package', 'ddic', 'app', 'cds', 'other'];\n\nexport function classifyTier(type: string): DependencyTier {\n return TIER_FOR_TYPE[getMainType(type)] ?? 'other';\n}\n\nexport interface ChangePlan {\n /** All entries regardless of action/tier, in discovery order. */\n entries: ChangePlanEntry[];\n /** Actionable entries grouped by tier in apply order. */\n groups: Array<{ tier: DependencyTier; entries: ChangePlanEntry[] }>;\n /** Entries that don't need an apply pass (skip/unchanged). */\n inert: ChangePlanEntry[];\n}\n\n/**\n * Build a ChangePlan by classifying each entry and sorting into tiers.\n *\n * Entries whose action is `skip` or `unchanged` are parked in `inert` so the\n * apply stage doesn't touch them. Empty tiers are elided.\n */\nexport function buildPlan(entries: ChangePlanEntry[]): ChangePlan {\n const byTier = new Map<DependencyTier, ChangePlanEntry[]>();\n const inert: ChangePlanEntry[] = [];\n\n for (const entry of entries) {\n if (entry.action === 'skip' || entry.action === 'unchanged') {\n inert.push(entry);\n continue;\n }\n const tier = classifyTier(entry.object.type);\n const bucket = byTier.get(tier) ?? [];\n bucket.push(entry);\n byTier.set(tier, bucket);\n }\n\n const groups: ChangePlan['groups'] = [];\n for (const tier of TIER_ORDER) {\n const bucket = byTier.get(tier);\n if (bucket && bucket.length > 0) {\n groups.push({ tier, entries: bucket });\n }\n }\n\n return { entries, groups, inert };\n}\n\n/** Extract a flat ordered list of AdkObjects from a plan (apply order). */\nexport function flattenPlanObjects(plan: ChangePlan): AdkObject[] {\n const out: AdkObject[] = [];\n for (const group of plan.groups) {\n for (const entry of group.entries) {\n out.push(entry.object);\n }\n }\n return out;\n}\n","/**\n * Apply stage — executes a ChangePlan against SAP.\n *\n * Each tier is deployed as its own `AdkObjectSet` so that DDIC objects are\n * saved + activated before the application-code tier starts. Within a tier,\n * objects are saved with `mode: 'upsert'` — SAP's PUT endpoints auto-detect\n * whether the object already exists so we don't need separate create/update\n * paths here.\n *\n * Locking:\n * - Before each tier, an outer `BatchLockSession` pre-acquires locks to\n * catch conflicts early (e.g. another user editing). Because ADK's\n * `save()` also lock/unlocks per object, we release the batch session\n * immediately after pre-flight — the CSRF security session is preserved\n * so the subsequent per-object re-lock is cheap.\n * - If the batch pre-flight fails, the tier is aborted and all locks\n * acquired so far (in that tier) are rolled back; partial state from\n * previous tiers is documented to the caller.\n */\nimport type { AdkObject, AdkContext } from '@abapify/adk';\nimport { AdkObjectSet } from '@abapify/adk';\nimport {\n createBatchLockSession,\n type BatchLockTarget,\n} from '@abapify/adt-locks';\nimport type { ChangePlan, DependencyTier } from './plan';\n\nexport interface ApplyOptions {\n /** Transport request used for lock + save operations. */\n transport?: string;\n /** Dry run — build plan but don't touch SAP. */\n dryRun?: boolean;\n /** Activate saved objects after each tier. Default: true. */\n activate?: boolean;\n /**\n * Release locks for which this client persisted a handle before the batch\n * lock session begins. Mirrors `adt export --unlock`.\n */\n unlock?: boolean;\n /** Per-tier progress hook. */\n onTierStart?: (tier: DependencyTier, size: number) => void;\n /** Per-object progress hook. */\n onObject?: (object: AdkObject, status: string) => void;\n}\n\nexport interface ApplyTierResult {\n tier: DependencyTier;\n size: number;\n saved: number;\n failed: number;\n unchanged: number;\n activated: number;\n errors: Array<{ name: string; type: string; error: string }>;\n}\n\nexport interface ApplyResult {\n /** Per-tier stats in the order they were applied. */\n tiers: ApplyTierResult[];\n /** Aggregate totals. */\n totals: {\n saved: number;\n failed: number;\n unchanged: number;\n activated: number;\n };\n /** True if the caller aborted before all tiers ran (lock conflict). */\n aborted: boolean;\n}\n\n/** Execute the change plan. Always returns a result — caller decides exit. */\nexport async function applyPlan(\n plan: ChangePlan,\n ctx: AdkContext,\n options: ApplyOptions = {},\n): Promise<ApplyResult> {\n const activate = options.activate ?? true;\n const result: ApplyResult = {\n tiers: [],\n totals: { saved: 0, failed: 0, unchanged: 0, activated: 0 },\n aborted: false,\n };\n\n for (const group of plan.groups) {\n const tierResult: ApplyTierResult = {\n tier: group.tier,\n size: group.entries.length,\n saved: 0,\n failed: 0,\n unchanged: 0,\n activated: 0,\n errors: [],\n };\n options.onTierStart?.(group.tier, group.entries.length);\n\n if (options.dryRun) {\n // Pretend everything succeeded for reporting only.\n for (const entry of group.entries) {\n options.onObject?.(entry.object, 'dry-run');\n tierResult.saved++;\n }\n result.tiers.push(tierResult);\n result.totals.saved += tierResult.saved;\n continue;\n }\n\n // Optional: release only persisted stale locks. SAP cannot disclose a\n // lost handle by issuing another LOCK.\n if (options.unlock && ctx.lockService) {\n for (const entry of group.entries) {\n try {\n await ctx.lockService.forceUnlock(entry.object.objectUri);\n } catch {\n /* no persisted handle or server rejected it — preflight reports it */\n }\n }\n }\n\n // Pre-flight: batch-lock to surface conflicts BEFORE we start mutating.\n // We release immediately afterwards because ADK's save() will re-lock\n // per object within the same security session (CSRF survives unlock).\n let preflightFailed = false;\n if (ctx.lockService) {\n const targets: BatchLockTarget[] = group.entries.map((e) => ({\n objectUri: e.object.objectUri,\n options: {\n transport: options.transport,\n objectName: e.object.name,\n objectType: e.object.type,\n },\n }));\n const batch = createBatchLockSession(ctx.lockService, targets);\n try {\n await batch.begin();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n tierResult.errors.push({\n name: '(batch)',\n type: group.tier,\n error: `batch lock pre-flight failed: ${msg}`,\n });\n tierResult.failed = group.entries.length;\n preflightFailed = true;\n } finally {\n await batch.release();\n }\n }\n\n if (preflightFailed) {\n result.tiers.push(tierResult);\n result.totals.failed += tierResult.failed;\n result.aborted = true;\n // Stop applying further tiers — the caller sees a partial-apply state.\n break;\n }\n\n // Build the tier's AdkObjectSet and deploy.\n const set = new AdkObjectSet(ctx);\n for (const entry of group.entries) set.add(entry.object);\n\n const deployResult = await set.deploy({\n transport: options.transport,\n activate,\n mode: 'upsert',\n onProgress: (_processed, _total, current) => {\n options.onObject?.(current, 'saved');\n },\n });\n\n tierResult.saved = deployResult.save.success;\n tierResult.failed = deployResult.save.failed;\n tierResult.unchanged = deployResult.save.unchanged;\n tierResult.activated = deployResult.activation?.success ?? 0;\n for (const r of deployResult.save.results) {\n if (!r.success && !r.unchanged) {\n tierResult.errors.push({\n name: r.object.name,\n type: r.object.type,\n error: r.error ?? 'unknown error',\n });\n }\n }\n\n result.tiers.push(tierResult);\n result.totals.saved += tierResult.saved;\n result.totals.failed += tierResult.failed;\n result.totals.unchanged += tierResult.unchanged;\n result.totals.activated += tierResult.activated;\n }\n\n return result;\n}\n","/**\n * CheckinService — push a local abapGit/gCTS directory into SAP.\n *\n * Pipeline:\n * 1. Load the chosen FormatPlugin (via `loadFormatPlugin`; works for any\n * registered format — `abapgit`, `gcts`/`aff`, third-party).\n * 2. Drive the plugin's `format.export(fileTree, client, options)`\n * AsyncGenerator to deserialise local files into `AdkObject`\n * instances. This is the ONE place where file → object conversion\n * lives — every format participates transparently.\n * 3. Optionally validate the target transport via the typed\n * `transportrequests.get` contract.\n * 4. Run diff against remote (per-object `load()` 404-check).\n * 5. Build a tier-ordered `ChangePlan` (DDIC → APP → CDS → other).\n * 6. Apply via `applyPlan` → pre-flight batch locks per tier + ADK save.\n *\n * The service returns a structured `CheckinResult` — neither the CLI nor\n * the MCP tool contains any business logic, they only format the result.\n *\n * gCTS note: because `loadFormatPlugin('gcts')` resolves to\n * `@abapify/adt-plugin-gcts`, invoking `CheckinService.checkin({format:\n * 'gcts', ...})` produces an identical apply pipeline — only the\n * deserialisation step differs. That's the FormatPlugin guarantee in action.\n */\nimport type { AdkObject, AdkContext } from '@abapify/adk';\nimport { AdkTransport, getGlobalContext } from '@abapify/adk';\nimport type { FormatOptionValue } from '@abapify/adt-plugin';\n\nimport { loadFormatPlugin } from '../../utils/format-loader';\nimport { createFsFileTree } from './filetree';\n\nimport { diffObject, type ChangePlanEntry } from './diff';\nimport { buildPlan, type ChangePlan, type DependencyTier } from './plan';\nimport { applyPlan, type ApplyOptions, type ApplyResult } from './apply';\n\nexport interface CheckinOptions {\n /** Source directory containing serialised files (abapGit/gCTS layout). */\n sourceDir: string;\n /** Format id — `abapgit` | `gcts` | `aff` | bespoke plugin package. */\n format: string;\n /** Target root package (used by FormatPlugin to resolve packageRef). */\n rootPackage?: string;\n /** Transport request for all modified/created objects. */\n transport?: string;\n /** Filter by ABAP object types (e.g. ['CLAS','INTF']). */\n objectTypes?: string[];\n /** Dry run — validate only, no SAP writes. */\n dryRun?: boolean;\n /** Activate objects after save (default true). */\n activate?: boolean;\n /** Release stale locks only when this client persisted their handles. */\n unlock?: boolean;\n /** ABAP language version override (e.g. '5' for Cloud). */\n abapLanguageVersion?: string;\n /** Format-specific options (opaque to the service). */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Optional ADK context override (tests pass a shared one). */\n adkContext?: AdkContext;\n /** Log hook — no console writes inside the service itself. */\n onLog?: (level: 'info' | 'warn' | 'error', message: string) => void;\n /** Per-object progress hook passed down to apply. */\n onObject?: (object: AdkObject, status: string) => void;\n}\n\nexport interface CheckinResult {\n /** Source directory that was checked in. */\n sourceDir: string;\n /** Format id used for deserialisation. */\n format: string;\n /** Total AdkObjects discovered from the file tree. */\n discovered: number;\n /** Diff outcome per action kind (create/update/unchanged/skip). */\n actions: Record<string, number>;\n /** Tiered apply result (one entry per non-empty tier). */\n apply: ApplyResult;\n /** Plan groups as tier → entries (for dry-run/output formatting). */\n groups: Array<{\n tier: DependencyTier;\n entries: Array<{\n name: string;\n type: string;\n action: ChangePlanEntry['action'];\n }>;\n }>;\n /** True if we stopped before applying every tier. */\n aborted: boolean;\n /** Human-readable summary suitable for CLI output. */\n summary: string;\n}\n\nexport class CheckinService {\n async checkin(options: CheckinOptions): Promise<CheckinResult> {\n const log = options.onLog ?? (() => undefined);\n\n // 1. Resolve format plugin (FormatPlugin registry + AdtPlugin legacy path).\n const plugin = await loadFormatPlugin(options.format);\n if (!plugin.instance.format.export) {\n throw new Error(\n `Format plugin '${plugin.name}' does not implement format.export — ` +\n `cannot deserialise local files. Required for checkin.`,\n );\n }\n log('info', `Loaded format plugin: ${plugin.name}`);\n\n // 2. Deserialise local files → AdkObjects.\n const adkContext = options.adkContext ?? getGlobalContext();\n const client = adkContext.client;\n const fileTree = createFsFileTree(options.sourceDir);\n\n const filterTypes = options.objectTypes?.map((t) => t.toUpperCase());\n const discovered: AdkObject[] = [];\n\n for await (const obj of plugin.instance.format.export(fileTree, client, {\n rootPackage: options.rootPackage,\n abapLanguageVersion: options.abapLanguageVersion,\n formatOptions: options.formatOptions,\n })) {\n if (filterTypes && !matchesTypeFilter(obj.type, filterTypes)) continue;\n discovered.push(obj);\n }\n log(\n 'info',\n `Discovered ${discovered.length} objects from ${options.sourceDir}`,\n );\n\n // 3. Optional transport validation.\n if (options.transport && !options.dryRun) {\n try {\n await AdkTransport.get(options.transport);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Transport validation failed for ${options.transport}: ${msg}`,\n { cause: err },\n );\n }\n }\n\n // 4. Diff against remote.\n const entries: ChangePlanEntry[] = [];\n for (const obj of discovered) {\n entries.push(await diffObject(obj));\n }\n\n // 5. Build plan.\n const plan: ChangePlan = buildPlan(entries);\n\n const actions: Record<string, number> = {\n create: 0,\n update: 0,\n unchanged: 0,\n skip: 0,\n };\n for (const entry of entries) actions[entry.action]++;\n\n // 6. Apply (skipped entirely for dry run).\n const applyOptions: ApplyOptions = {\n transport: options.transport,\n dryRun: options.dryRun,\n activate: options.activate,\n unlock: options.unlock,\n onTierStart: (tier, size) =>\n log('info', `→ Applying tier ${tier} (${size} objects)`),\n onObject: options.onObject,\n };\n const applyResult = await applyPlan(plan, adkContext, applyOptions);\n\n const summary = formatSummary(discovered.length, actions, applyResult);\n\n return {\n sourceDir: options.sourceDir,\n format: options.format,\n discovered: discovered.length,\n actions,\n apply: applyResult,\n groups: plan.groups.map((g) => ({\n tier: g.tier,\n entries: g.entries.map((e) => ({\n name: e.object.name,\n type: e.object.type,\n action: e.action,\n })),\n })),\n aborted: applyResult.aborted,\n summary,\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction matchesTypeFilter(type: string, filter: string[]): boolean {\n const upper = type.toUpperCase();\n const main = upper.split('/')[0];\n return filter.includes(upper) || filter.includes(main);\n}\n\nfunction formatSummary(\n discovered: number,\n actions: Record<string, number>,\n apply: ApplyResult,\n): string {\n const parts = [\n `${discovered} discovered`,\n `${actions.create ?? 0} new`,\n `${actions.update ?? 0} modified`,\n `${actions.unchanged ?? 0} unchanged`,\n `${apply.totals.saved} saved`,\n `${apply.totals.activated} activated`,\n ];\n if (apply.totals.failed > 0) parts.push(`${apply.totals.failed} failed`);\n if (apply.aborted) parts.push('aborted (partial-apply)');\n return parts.join(', ');\n}\n","/** Concrete connection metadata used to instantiate an ADT client. */\ninterface ConnectionParams {\n baseUrl: string;\n client?: string;\n username?: string;\n password?: string;\n}\n\n/**\n * Inputs accepted by the shared connection resolver.\n *\n * `baseUrl` and `systemId` are mutually exclusive selectors:\n * - `baseUrl` selects explicit connection args\n * - `systemId` selects configured/fallback lookup paths\n */\nexport interface ConnectionResolveArgs {\n baseUrl?: string;\n client?: string;\n username?: string;\n password?: string;\n systemId?: string;\n}\n\n/**\n * Hook points used by the resolver to stay transport/framework agnostic.\n *\n * Resolution chain:\n * 1. `createClient` with explicit args (`baseUrl`)\n * 2. `resolveSystem` + `createClient` (`systemId` from registry)\n * 3. `resolveFromAuthStore` (`systemId` from local auth-store fallback)\n */\nexport interface ResolveConnectionClientHooks<TClient> {\n createClient: (params: ConnectionParams) => TClient;\n resolveSystem?: (systemId: string) => ConnectionParams | undefined;\n resolveFromAuthStore?: (systemId: string) => Promise<TClient>;\n}\n\n/**\n * Final resolved client plus metadata about how it was obtained.\n *\n * `systemId` is present when a logical system was used and may be absent\n * for plain explicit `baseUrl` calls.\n */\nexport interface ResolvedConnectionClient<TClient> {\n client: TClient;\n systemId?: string;\n source: 'explicit' | 'multi-system' | 'adt-cli-auth-store';\n}\n\nexport async function resolveConnectionClient<TClient>(\n args: ConnectionResolveArgs,\n hooks: ResolveConnectionClientHooks<TClient>,\n): Promise<ResolvedConnectionClient<TClient>> {\n if (args.baseUrl) {\n return {\n client: hooks.createClient({\n baseUrl: args.baseUrl,\n client: args.client,\n username: args.username,\n password: args.password,\n }),\n systemId: args.systemId,\n source: 'explicit',\n };\n }\n\n if (args.systemId && hooks.resolveSystem) {\n const params = hooks.resolveSystem(args.systemId);\n if (params) {\n return {\n client: hooks.createClient({\n ...params,\n username: args.username,\n password: args.password,\n }),\n systemId: args.systemId,\n source: 'multi-system',\n };\n }\n }\n\n if (args.systemId && hooks.resolveFromAuthStore) {\n return {\n client: await hooks.resolveFromAuthStore(args.systemId),\n systemId: args.systemId,\n source: 'adt-cli-auth-store',\n };\n }\n\n throw new Error(\n 'No connection could be resolved: provide baseUrl (+ credentials) or systemId resolvable via multi-system config or ~/.adt session store.',\n );\n}\n","import { AdkTransportRequest, type ReleaseResult } from '@abapify/adk';\nimport type { AdtClient } from '@abapify/adt-client';\n\nfunction normalizeTransportIdentifier(\n transport: string,\n errorMessage = 'Transport identifier is required',\n): string {\n const normalized = transport.trim().toUpperCase();\n if (!normalized) {\n throw new Error(errorMessage);\n }\n return normalized;\n}\n\nexport interface CtsTransportLifecycleOperations {\n getTransport(\n transport: string,\n client: AdtClient,\n ): Promise<AdkTransportRequest>;\n}\n\nconst DEFAULT_OPERATIONS: CtsTransportLifecycleOperations = {\n getTransport: (transport, client) =>\n AdkTransportRequest.get(transport, { client }),\n};\n\nexport interface CtsTransportSummary {\n transport: string;\n status: string;\n statusText: string;\n owner: string;\n description: string;\n target: string;\n targetDescription: string;\n taskCount: number;\n objectCount: number;\n}\n\nexport interface ReleaseTransportInput {\n transport: string;\n releaseAll?: boolean;\n}\n\nexport interface ReleaseTransportResult {\n status: 'released' | 'already_released';\n transport: string;\n releaseAll: boolean;\n result: ReleaseResult;\n}\n\nexport interface ReassignTransportInput {\n transport: string;\n newOwner: string;\n recursive?: boolean;\n}\n\nexport interface ReassignTransportResult {\n status: 'reassigned';\n transport: string;\n previousOwner: string;\n newOwner: string;\n recursive: boolean;\n}\n\nexport interface CreateTaskInput {\n transport: string;\n owner: string;\n}\n\nexport interface CreateTaskResult {\n status: 'created';\n transport: string;\n task: string;\n owner: string;\n}\n\nexport class CtsTransportLifecycleService {\n constructor(\n private readonly client: AdtClient,\n private readonly operations: CtsTransportLifecycleOperations = DEFAULT_OPERATIONS,\n ) {}\n\n async getTransport(transport: string): Promise<CtsTransportSummary> {\n const normalizedTransport = normalizeTransportIdentifier(transport);\n const model = await this.operations.getTransport(\n normalizedTransport,\n this.client,\n );\n return {\n transport: model.number,\n status: model.status,\n statusText: model.statusText,\n owner: model.owner,\n description: model.description,\n target: model.target,\n targetDescription: model.targetDescription,\n taskCount: model.tasks.length,\n objectCount: model.objects.length,\n };\n }\n\n async release(input: ReleaseTransportInput): Promise<ReleaseTransportResult> {\n const transport = normalizeTransportIdentifier(input.transport);\n const releaseAll = input.releaseAll ?? false;\n const model = await this.operations.getTransport(transport, this.client);\n if (model.status === 'R') {\n return {\n status: 'already_released',\n transport: model.number,\n releaseAll,\n result: { success: true },\n };\n }\n\n const result = releaseAll\n ? await model.releaseAll()\n : await model.release();\n if (!result.success) {\n throw new Error(\n result.message || `Release of transport ${model.number} failed`,\n );\n }\n\n return {\n status: 'released',\n transport: model.number,\n releaseAll,\n result,\n };\n }\n\n async createTask(input: CreateTaskInput): Promise<CreateTaskResult> {\n const transport = normalizeTransportIdentifier(\n input.transport,\n 'Transport and task owner are required',\n );\n const owner = input.owner.trim().toUpperCase();\n if (!owner) {\n throw new Error('Transport and task owner are required');\n }\n const model = await this.operations.getTransport(transport, this.client);\n const task = await model.addTask(owner);\n const updatedModel = await this.operations.getTransport(\n transport,\n this.client,\n );\n const confirmed = updatedModel.tasks.some(\n (t) => t.number === task.number && t.owner === task.owner,\n );\n if (!confirmed) {\n throw new Error(`no new task owned by ${owner}`);\n }\n return {\n status: 'created',\n transport: model.number,\n task: task.number,\n owner: task.owner,\n };\n }\n\n async reassign(\n input: ReassignTransportInput,\n ): Promise<ReassignTransportResult> {\n const transport = normalizeTransportIdentifier(\n input.transport,\n 'Transport and new owner are required',\n );\n const newOwner = input.newOwner.trim().toUpperCase();\n if (!newOwner) {\n throw new Error('Transport and new owner are required');\n }\n const model = await this.operations.getTransport(transport, this.client);\n if (model.status === 'R') {\n throw new Error(`Transport ${model.number} is already released`);\n }\n\n const recursive = input.recursive ?? false;\n const previousOwner = model.owner;\n await model.reassign(newOwner, recursive);\n\n return {\n status: 'reassigned',\n transport: model.number,\n previousOwner,\n newOwner: model.owner,\n recursive,\n };\n }\n}\n","import type { AdtClient } from '@abapify/adt-client';\n\nexport interface CtsTransportMetadataUnit {\n kind: 'request' | 'task';\n number: string;\n description?: string;\n owner?: string;\n status?: string;\n type?: string;\n parent?: string;\n lastChangedTimestamp?: string;\n}\n\nexport interface CtsTransportMetadataResult {\n requestedTransport: string;\n units: CtsTransportMetadataUnit[];\n}\n\n/**\n * Typed CTS metadata projection shared by CLI and MCP. The ADT client owns\n * protocol decoding; this service deliberately has no XML or console logic.\n */\nexport class CtsTransportMetadataService {\n constructor(private readonly client: AdtClient) {}\n\n async get(transport: string): Promise<CtsTransportMetadataResult> {\n const requestedTransport = transport.trim().toUpperCase();\n if (!requestedTransport)\n throw new Error('Transport identifier is required');\n const request =\n await this.client.services.transports.get(requestedTransport);\n const units: CtsTransportMetadataUnit[] = [\n {\n kind: request.parent ? 'task' : 'request',\n number: request.number,\n description: request.desc,\n owner: request.owner,\n status: request.status,\n type: request.type,\n parent: request.parent,\n lastChangedTimestamp: request.lastChangedTimestamp,\n },\n ...(request.tasks ?? []).map((task) => ({\n kind: 'task' as const,\n number: task.number,\n description: task.desc,\n owner: task.owner,\n status: task.status,\n type: task.type,\n parent: task.parent || request.number,\n lastChangedTimestamp: task.lastChangedTimestamp,\n })),\n ];\n return { requestedTransport, units };\n }\n}\n","/**\n * Shared ADT Client State\n *\n * Global state and singleton instances for ADT client management.\n * This module holds stateful objects that are shared across CLI commands.\n *\n * For the factory function that creates clients, see utils/adt-client.ts\n */\nimport type { Logger } from '@abapify/adt-client';\n\n// =============================================================================\n// Global CLI Context (set by CLI preAction hook)\n// =============================================================================\n\nexport interface CliContext {\n sid?: string;\n logger?: Logger;\n logLevel?: string;\n logOutput?: string;\n logResponseFiles?: boolean;\n verbose?: boolean | string;\n /** Path to config file (from --config flag) */\n configPath?: string;\n}\n\nlet globalCliContext: CliContext = {};\n\n/**\n * Set global CLI context (called by CLI preAction hook)\n * This allows getAdtClientV2() to auto-read CLI options without passing them explicitly\n */\nexport function setCliContext(context: CliContext): void {\n globalCliContext = { ...globalCliContext, ...context };\n}\n\n/**\n * Get current CLI context\n */\nexport function getCliContext(): CliContext {\n return globalCliContext;\n}\n\n/**\n * Reset CLI context (useful for testing)\n */\nexport function resetCliContext(): void {\n globalCliContext = {};\n}\n\n// =============================================================================\n// Shared Loggers\n// =============================================================================\n\n/**\n * Silent logger - suppresses all output (default for CLI)\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst noop = () => {};\nexport const silentLogger: Logger = {\n trace: noop,\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n fatal: noop,\n child: () => silentLogger,\n};\n\n/**\n * Console logger - outputs to console (used when enableLogging is true)\n */\nexport const consoleLogger: Logger = {\n trace: (msg: string) => console.error(msg),\n debug: (msg: string) => console.error(msg),\n info: (msg: string) => console.error(msg),\n warn: (msg: string) => console.error(msg),\n error: (msg: string) => console.error(msg),\n fatal: (msg: string) => console.error(msg),\n child: () => consoleLogger,\n};\n\n// =============================================================================\n// Capture Plugin State\n// =============================================================================\n\n/**\n * Captured response data from the last request\n */\nexport interface CapturedResponse {\n /** Raw XML/text response */\n xml?: string;\n /** Parsed JSON response */\n json?: unknown;\n}\n\n// Global capture storage (reset on each request)\nlet lastCaptured: CapturedResponse = {};\n\n/**\n * Get the last captured response (for commands that need raw XML/JSON)\n */\nexport function getCaptured(): CapturedResponse {\n return lastCaptured;\n}\n\n/**\n * Set captured response data\n */\nexport function setCaptured(data: CapturedResponse): void {\n lastCaptured = data;\n}\n\n/**\n * Reset captured data (called before each request when capture is enabled)\n */\nexport function resetCaptured(): void {\n lastCaptured = {};\n}\n","/**\n * Destination utilities\n *\n * Loads destinations from adt.config.ts/json using @abapify/adt-config\n */\n\nimport {\n loadConfig,\n type LoadedConfig,\n type Destination,\n} from '@abapify/adt-config';\nimport { getCliContext } from '../shared/adt-client';\n\n// Cached config instance (keyed by configPath to handle different configs)\nlet cachedConfig: LoadedConfig | null = null;\nlet cachedConfigPath: string | undefined = undefined;\n\n/**\n * Get loaded config (cached)\n * Uses configPath from CLI context if available (from --config flag)\n */\nexport async function getConfig(): Promise<LoadedConfig> {\n const context = getCliContext();\n const configPath = context.configPath;\n\n // Invalidate cache if configPath changed\n if (cachedConfig && cachedConfigPath !== configPath) {\n cachedConfig = null;\n }\n\n if (!cachedConfig) {\n cachedConfig = await loadConfig({ configPath });\n cachedConfigPath = configPath;\n }\n return cachedConfig;\n}\n\n/**\n * Get a destination by name (SID)\n * @param name Destination name (e.g., 'TRL')\n */\nexport async function getDestination(\n name: string,\n): Promise<Destination | undefined> {\n const config = await getConfig();\n return config.getDestination(name);\n}\n\n/**\n * List all configured destinations\n */\nexport async function listDestinations(): Promise<string[]> {\n const config = await getConfig();\n return config.listDestinations();\n}\n\n/**\n * Check if a destination exists\n */\nexport async function hasDestination(name: string): Promise<boolean> {\n const config = await getConfig();\n return config.hasDestination(name);\n}\n\n/**\n * Clear cached config (useful for testing)\n */\nexport function clearConfigCache(): void {\n cachedConfig = null;\n cachedConfigPath = undefined;\n}\n\n// Re-export types\nexport type { LoadedConfig, Destination } from '@abapify/adt-config';\n","/**\n * Parse a comma-separated string of SAP transport numbers into a deduplicated\n * uppercase array.\n *\n * Trims whitespace, uppercases, filters empty tokens, and removes duplicates\n * while preserving insertion order (O(n) via Set).\n *\n * Throws when no valid transport numbers are found.\n *\n * @example\n * parseTransportNumbers('DEVK900001') // → ['DEVK900001']\n * parseTransportNumbers('DEVK900001, DEVK900002') // → ['DEVK900001', 'DEVK900002']\n * parseTransportNumbers('DEVK900001,DEVK900001') // → ['DEVK900001'] (deduped)\n */\nexport function parseTransportNumbers(value: string): string[] {\n const seen = new Set<string>();\n const numbers = value\n .split(',')\n .map((n) => n.trim().toUpperCase())\n .filter(Boolean)\n .filter((n) => {\n if (seen.has(n)) return false;\n seen.add(n);\n return true;\n });\n\n if (numbers.length === 0) {\n throw new Error(`No transport number(s) provided in '${value}'`);\n }\n\n return numbers;\n}\n","export type SearchObject = {\n name?: string;\n type?: string;\n uri?: string;\n description?: string;\n packageName?: string;\n};\n\nexport type ObjectSearchOptions = {\n objectName: string;\n objectType?: string;\n};\n\ntype SearchObjectResolutionContext = {\n objects: SearchObject[];\n options: ObjectSearchOptions;\n exactMatches: SearchObject[];\n availableExactTypes: string[];\n requestedObjectType: string | undefined;\n};\n\nfunction normalizeObjectType(type: string): string {\n return type.toUpperCase().split('/')[0] ?? '';\n}\n\nfunction getExactSearchMatches(\n objects: SearchObject[],\n objectName: string,\n): SearchObject[] {\n const normalizedName = objectName.toUpperCase();\n return objects.filter(\n (obj) => String(obj.name || '').toUpperCase() === normalizedName,\n );\n}\n\nfunction getSearchObjectTypes(objects: SearchObject[]): string[] {\n return [\n ...new Set(\n objects.map((obj) => normalizeObjectType(String(obj.type || ''))),\n ),\n ].filter(Boolean);\n}\n\nfunction findExactSearchMatch(\n exactMatches: SearchObject[],\n requestedObjectType: string | undefined,\n availableExactTypes: string[],\n): SearchObject | undefined {\n if (requestedObjectType) {\n return exactMatches.find(\n (obj) =>\n normalizeObjectType(String(obj.type || '')) === requestedObjectType,\n );\n }\n\n return availableExactTypes.length <= 1 ? exactMatches[0] : undefined;\n}\n\nfunction createObjectNotFoundError(\n objects: SearchObject[],\n objectName: string,\n): Error {\n const similar = objects\n .filter((obj) =>\n String(obj.name || '')\n .toUpperCase()\n .includes(objectName.toUpperCase()),\n )\n .slice(0, 5);\n const similarList = similar\n .map((obj) => ` • ${obj.name} (${obj.type}) – ${obj.packageName}`)\n .join('\\n');\n const hint =\n similar.length > 0 ? `\\n💡 Similar objects:\\n${similarList}` : '';\n\n return new Error(`Object '${objectName}' not found in the system.${hint}`);\n}\n\nfunction createSearchObjectResolutionError(\n context: SearchObjectResolutionContext,\n): Error {\n const {\n objects,\n options,\n exactMatches,\n availableExactTypes,\n requestedObjectType,\n } = context;\n\n if (requestedObjectType && exactMatches.length > 0) {\n return new Error(\n `Object '${options.objectName}' with type '${requestedObjectType}' was not found. Available types: ${availableExactTypes.join(', ') || 'none'}.`,\n );\n }\n\n if (!requestedObjectType && availableExactTypes.length > 1) {\n return new Error(\n `Object '${options.objectName}' is ambiguous. Use --object-type to select one of: ${availableExactTypes.join(', ')}.`,\n );\n }\n\n return createObjectNotFoundError(objects, options.objectName);\n}\n\nexport function selectSearchObject(\n objects: SearchObject[],\n options: ObjectSearchOptions,\n): SearchObject {\n const exactMatches = getExactSearchMatches(objects, options.objectName);\n const availableExactTypes = getSearchObjectTypes(exactMatches);\n const requestedObjectType = options.objectType\n ? normalizeObjectType(options.objectType.trim())\n : undefined;\n const exactMatch = findExactSearchMatch(\n exactMatches,\n requestedObjectType,\n availableExactTypes,\n );\n\n if (exactMatch) {\n return exactMatch;\n }\n\n throw createSearchObjectResolutionError({\n objects,\n options,\n exactMatches,\n availableExactTypes,\n requestedObjectType,\n });\n}\n","import { loadFormatPlugin, parseFormatSpec } from '../../utils/format-loader';\nimport { getConfig } from '../../utils/destinations';\nimport { parseTransportNumbers } from '../../utils/transport-numbers';\nimport type { ImportContext, FormatOptionValue } from '@abapify/adt-plugin';\nimport {\n AdkPackage,\n AdkTransport,\n MergedTransportView,\n matchesSelector,\n getGlobalContext,\n createAdkFactory,\n} from '@abapify/adk';\nimport type { AdkTransportObjectRef } from '@abapify/adk';\nimport { Readable } from 'node:stream';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { selectSearchObject, type SearchObject } from './object-selection';\n\n/** Default number of concurrent SAP requests during import */\nconst IMPORT_CONCURRENCY = 5;\n\n/**\n * Resolve full package path from root to the given package.\n * Traverses the ADK package hierarchy upward until the root is reached.\n */\nasync function resolvePackagePath(packageName: string): Promise<string[]> {\n const path: string[] = [];\n let currentPackage = packageName;\n\n while (currentPackage) {\n path.unshift(currentPackage);\n try {\n const pkg = await AdkPackage.get(currentPackage);\n const superPkg = pkg.superPackage;\n if (superPkg?.name) {\n currentPackage = superPkg.name;\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n return path;\n}\n\n/**\n * Options for importing a single object by name (search-based)\n */\nexport interface ObjectImportOptions {\n /** Object name to search for (e.g., 'ZAGE_DOMA_CASE_SENSITIVE') */\n objectName: string;\n /** Exact ABAP object type used to disambiguate same-named objects */\n objectType?: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Format-specific options provided via CLI */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Enable debug output */\n debug?: boolean;\n}\n\n/**\n * Options for importing a transport request\n */\nexport interface TransportImportOptions {\n /**\n * Transport request number(s).\n *\n * Accepts a single number or a comma-separated list:\n * - `'DEVK900001'` — single TR\n * - `'DEVK900001,DEVK900002,DEVK900003'` — multiple TRs (merged, deduplicated)\n */\n transportNumber: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Filter by object types (e.g., ['CLAS', 'INTF']) - if not specified, imports all */\n objectTypes?: string[];\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Format-specific options provided via CLI */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Enable debug output */\n debug?: boolean;\n /**\n * Whether to apply deletions for objects marked with obj_func=D and pgmid=R3TR.\n * Default: true\n */\n applyDeletions?: boolean;\n /**\n * When true, write a JSON sidecar for each transport to\n * `<outputPath>/.adt/tr/<TRKORR>.json` with normalized transport metadata.\n * Default: false\n */\n saveTrMetadata?: boolean;\n /**\n * When true, objects that are in the TR list but cannot be fetched from SAP\n * (i.e., `objRef.load()` returns null — the object no longer exists in the system)\n * are treated as deletions: `format.delete()` is called to remove their local files.\n *\n * This catches the \"orphan sync\" case where an object was removed in SAP without\n * an explicit `obj_func=D` entry in the transport.\n *\n * Default: false (backward-compatible; previously counted as skipped)\n */\n removeMissingObjects?: boolean;\n}\n\n/**\n * Options for importing a package\n */\nexport interface PackageImportOptions {\n /** Package name (e.g., 'Z_MY_PACKAGE') */\n packageName: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Filter by object types (e.g., ['CLAS', 'INTF']) - if not specified, imports all */\n objectTypes?: string[];\n /** Include subpackages */\n includeSubpackages?: boolean;\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Enable debug output */\n debug?: boolean;\n}\n\n/**\n * Result of an import operation\n */\nexport interface ImportResult {\n /** Transport number (for transport imports) */\n transportNumber?: string;\n /** Package name (for package imports) */\n packageName?: string;\n /** Object name (for single-object imports) */\n objectName?: string;\n /** Object type (for single-object imports) */\n objectType?: string;\n /** Description of the imported content */\n description: string;\n /** Total objects found */\n totalObjects: number;\n /** Statistics */\n results: {\n success: number;\n skipped: number;\n failed: number;\n /** Objects deleted from the file system (obj_func=D) */\n deleted: number;\n };\n /** Objects by type */\n objectsByType: Record<string, number>;\n /** Output path */\n outputPath: string;\n /** Files removed during deletion pass */\n filesRemoved?: string[];\n /** Metadata sidecar files written (when saveTrMetadata is true) */\n metadataFiles?: string[];\n}\n\n/**\n * Import Service - uses ADK architecture\n *\n * Flow:\n * 1. Load format plugin (via CLI option or config)\n * 2. Fetch transport via AdkTransport.get() or package via AdkPackage.get()\n * 3. Load each object via objRef.load()\n * 4. Delegate serialization to format plugin\n */\nexport class ImportService {\n private async getConfigFormatOptions(\n formatSpec: string,\n ): Promise<Record<string, FormatOptionValue>> {\n const loadedConfig = await getConfig();\n const rawConfig = loadedConfig.raw as Record<string, unknown>;\n const importConfig = rawConfig.import;\n\n if (\n !importConfig ||\n typeof importConfig !== 'object' ||\n Array.isArray(importConfig)\n ) {\n return {};\n }\n\n const formatOptionsMap = (importConfig as { formatOptions?: unknown })\n .formatOptions;\n if (\n !formatOptionsMap ||\n typeof formatOptionsMap !== 'object' ||\n Array.isArray(formatOptionsMap)\n ) {\n return {};\n }\n\n const { package: packageName } = parseFormatSpec(formatSpec);\n const shortName = packageName.replace('@abapify/adt-plugin-', '');\n const pluginName = packageName.replace('@abapify/', '');\n const aliases = [formatSpec, packageName, shortName, pluginName];\n\n for (const alias of aliases) {\n const value = (formatOptionsMap as Record<string, unknown>)[alias];\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, FormatOptionValue>;\n }\n }\n\n return {};\n }\n\n /**\n * Import objects from a transport request\n *\n * @param options - Import options including transport number, output path, and format\n * @returns Import result with statistics\n */\n async importTransport(\n options: TransportImportOptions,\n ): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Importing transport: ${options.transportNumber}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n }\n\n // Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (options.debug) {\n console.log(`✅ Loaded plugin: ${plugin.name}`);\n }\n\n // Parse comma-separated transport numbers from positional argument (dedup + uppercase)\n const allTransportNumbers = parseTransportNumbers(options.transportNumber);\n\n if (options.debug) {\n console.log(\n `🚛 Fetching transport(s): ${allTransportNumbers.join(', ')}`,\n );\n }\n\n // Resolve transport objects (single or merged)\n let allObjects: AdkTransportObjectRef[];\n let transportDescription: string;\n // Keep individual transport instances for metadata writing\n const loadedTransports: AdkTransport[] = [];\n\n if (allTransportNumbers.length === 1) {\n const transport = await AdkTransport.get(allTransportNumbers[0]);\n loadedTransports.push(transport);\n allObjects = transport.objects;\n transportDescription = transport.description;\n } else {\n const transports = await Promise.all(\n allTransportNumbers.map((n) => AdkTransport.get(n)),\n );\n loadedTransports.push(...transports);\n const merged = new MergedTransportView(transports);\n allObjects = merged.objects;\n transportDescription =\n transports.find((tr) => tr.description?.trim())?.description ??\n `${allTransportNumbers[0]} (+${allTransportNumbers.length - 1} more)`;\n }\n\n // Fixed deletion selector: obj_func === 'D' and pgmid === 'R3TR'\n // These are not configurable in v1 (CORR/release-note entries are skipped via pgmid filter)\n const applyDeletions = options.applyDeletions !== false; // default: true\n let deletionObjects: typeof allObjects = [];\n let activeObjects: typeof allObjects = allObjects;\n\n if (applyDeletions) {\n deletionObjects = [];\n activeObjects = [];\n\n for (const object of allObjects) {\n if (matchesSelector(object, { objFunc: 'D', pgmid: 'R3TR' })) {\n deletionObjects.push(object);\n } else {\n activeObjects.push(object);\n }\n }\n }\n\n // Apply object type filter to active objects\n let objectsToImport = activeObjects;\n if (options.objectTypes && options.objectTypes.length > 0) {\n const types = options.objectTypes.map((t) => t.toUpperCase());\n objectsToImport = activeObjects.filter((o) =>\n types.includes(o.type.toUpperCase()),\n );\n if (options.debug) {\n console.log(\n `🔍 Filtered to ${objectsToImport.length} active objects by type: ${types.join(', ')}`,\n );\n }\n }\n\n // Track results\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n const filesRemoved: string[] = [];\n const total = objectsToImport.length;\n let processed = 0;\n\n // Build the import context once — shared by the active-object pass\n // (line ~380 below), the orphan-sync missing-object deletion path\n // (line ~350 below), and the CTS deletion pass (line ~430 below).\n const importContext: ImportContext = {\n resolvePackagePath,\n formatOptions: options.formatOptions,\n configFormatOptions,\n };\n\n console.log(`📦 Processing ${total} active objects...`);\n\n // Process active objects in parallel\n await Readable.from(objectsToImport).forEach(\n async (objRef) => {\n const progress = ++processed;\n try {\n // Check if plugin supports this object type\n if (!plugin.instance.registry.isSupported(objRef.type)) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ [${progress}/${total}] ${objRef.type} ${objRef.name}: type not supported`,\n );\n }\n return;\n }\n\n console.log(\n ` 🔄 [${progress}/${total}] ${objRef.type} ${objRef.name}`,\n );\n\n // Load the ADK object\n const adkObject = await objRef.load();\n\n if (!adkObject) {\n // Object is in TR but doesn't exist in SAP (possible orphan — deleted without obj_func=D)\n const deleteFn = plugin.instance.format.delete;\n if (\n options.removeMissingObjects &&\n typeof deleteFn === 'function'\n ) {\n console.log(\n ` 🗑️ [${progress}/${total}] ${objRef.type} ${objRef.name}: not found in SAP → removing local files`,\n );\n try {\n const delResult = await deleteFn(\n { pgmid: objRef.pgmid, type: objRef.type, name: objRef.name },\n options.outputPath,\n importContext,\n );\n if (delResult.success) {\n results.deleted++;\n filesRemoved.push(...delResult.filesRemoved);\n } else {\n results.skipped++;\n }\n } catch (error) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⚠️ ${objRef.type} ${objRef.name}: delete failed — ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n } else {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ ${objRef.type} ${objRef.name}: not found in SAP (skipped)`,\n );\n }\n }\n return;\n }\n\n // Delegate to plugin - import object from SAP to local files\n const result = await plugin.instance.format.import(\n adkObject as any, // ADK object type\n options.outputPath,\n importContext,\n );\n\n if (result.success) {\n objectsByType[objRef.type] = (objectsByType[objRef.type] || 0) + 1;\n results.success++;\n } else {\n results.failed++;\n console.log(\n ` ❌ ${objRef.type} ${objRef.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n\n // Deletion pass - remove local files for deleted objects\n if (applyDeletions && deletionObjects.length > 0) {\n console.log(`🗑️ Processing ${deletionObjects.length} deletion(s)...`);\n\n const deleteSupported =\n typeof plugin.instance.format.delete === 'function';\n if (!deleteSupported && options.debug) {\n console.log(\n ` ⚠️ Plugin '${plugin.name}' does not implement format.delete() — skipping deletion pass`,\n );\n }\n\n if (deleteSupported) {\n let delProcessed = 0;\n const delTotal = deletionObjects.length;\n\n await Readable.from(deletionObjects).forEach(\n async (objRef) => {\n const progress = ++delProcessed;\n try {\n console.log(\n ` 🗑️ [${progress}/${delTotal}] ${objRef.type} ${objRef.name}`,\n );\n\n const delResult = await plugin.instance.format.delete!(\n { pgmid: objRef.pgmid, type: objRef.type, name: objRef.name },\n options.outputPath,\n importContext,\n );\n\n if (delResult.success) {\n results.deleted++;\n filesRemoved.push(...delResult.filesRemoved);\n } else {\n results.failed++;\n console.log(\n ` ❌ Delete ${objRef.type} ${objRef.name}: ${delResult.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ Delete ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n }\n }\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n // Write transport metadata sidecars if requested\n const metadataFiles: string[] = [];\n if (options.saveTrMetadata) {\n const metadataDir = join(options.outputPath, '.adt', 'tr');\n await mkdir(metadataDir, { recursive: true });\n\n for (const tr of loadedTransports) {\n const metadata = {\n number: tr.number,\n owner: tr.owner,\n desc: tr.description,\n status: tr.status,\n statusText: tr.statusText,\n target: tr.target,\n tasks: tr.tasks.map((task) => ({\n number: task.number,\n owner: task.owner,\n desc: task.description,\n status: task.status,\n objects: task.objects.map((obj) => ({\n pgmid: obj.pgmid,\n type: obj.type,\n name: obj.name,\n obj_func: obj.objFunc,\n uri: obj.uri,\n })),\n })),\n fetchedAt: new Date().toISOString(),\n import: {\n format: options.format,\n success: results.success,\n skipped: results.skipped,\n failed: results.failed,\n deleted: results.deleted,\n },\n };\n\n const metadataPath = join(metadataDir, `${tr.number}.json`);\n await writeFile(\n metadataPath,\n JSON.stringify(metadata, null, 2),\n 'utf-8',\n );\n metadataFiles.push(metadataPath);\n if (options.debug) {\n console.log(`📄 Wrote transport metadata: ${metadataPath}`);\n }\n }\n }\n\n return {\n transportNumber: allTransportNumbers[0],\n description: transportDescription,\n totalObjects: allObjects.length,\n results,\n objectsByType,\n outputPath: options.outputPath,\n filesRemoved: filesRemoved.length > 0 ? filesRemoved : undefined,\n metadataFiles: metadataFiles.length > 0 ? metadataFiles : undefined,\n };\n }\n\n /**\n * Import objects from an ABAP package\n *\n * @param options - Import options including package name, output path, and format\n * @returns Import result with statistics\n */\n async importPackage(options: PackageImportOptions): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Importing package: ${options.packageName}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n console.log(\n `📦 Include subpackages: ${options.includeSubpackages ?? false}`,\n );\n }\n\n // Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (options.debug) {\n console.log(`✅ Loaded plugin: ${plugin.name}`);\n }\n\n // Fetch package\n console.log(`🔍 Fetching package: ${options.packageName}`);\n const pkg = await AdkPackage.get(options.packageName);\n\n // Get objects from package\n let allObjects;\n if (options.includeSubpackages) {\n console.log(`📦 Scanning subpackages…`);\n allObjects = await pkg.getAllObjects();\n } else {\n allObjects = await pkg.getObjects();\n }\n console.log(`📋 Found ${allObjects.length} objects`);\n\n // Filter by object types if specified\n let objectsToImport = allObjects;\n if (options.objectTypes && options.objectTypes.length > 0) {\n const types = options.objectTypes.map((t) => t.toUpperCase());\n objectsToImport = allObjects.filter(\n (obj: { type: string }) =>\n types.includes(obj.type) || types.includes(obj.type.split('/')[0]),\n );\n if (options.debug) {\n console.log(\n `🔍 Filtered to ${objectsToImport.length} objects by type: ${types.join(', ')}`,\n );\n }\n }\n\n // Track results\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n const total = objectsToImport.length;\n let processed = 0;\n\n // Shared context/factory — created once, safe to reuse across workers\n const ctx = getGlobalContext();\n const factory = createAdkFactory(ctx);\n\n // Process objects in parallel using Node.js stream concurrency\n await Readable.from(objectsToImport).forEach(\n async (obj) => {\n const progress = ++processed;\n try {\n // Check if plugin supports this object type\n if (!plugin.instance.registry.isSupported(obj.type)) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ [${progress}/${total}] ${obj.type} ${obj.name}: type not supported`,\n );\n }\n return;\n }\n\n console.log(` 🔄 [${progress}/${total}] ${obj.type} ${obj.name}`);\n\n // Load the ADK object using the factory\n const adkObject = factory.get(obj.name, obj.type);\n await (adkObject as any).load();\n\n if (!adkObject) {\n results.skipped++;\n if (options.debug) {\n console.log(` ⏭️ ${obj.type} ${obj.name}: failed to load`);\n }\n return;\n }\n\n // Build import context\n const context: ImportContext = {\n resolvePackagePath,\n configFormatOptions,\n };\n\n // Delegate to plugin - import object from SAP to local files\n const result = await plugin.instance.format.import(\n adkObject as any,\n options.outputPath,\n context,\n );\n\n if (result.success) {\n objectsByType[obj.type] = (objectsByType[obj.type] || 0) + 1;\n results.success++;\n } else {\n results.failed++;\n console.log(\n ` ❌ ${obj.type} ${obj.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ ${obj.type} ${obj.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n return {\n packageName: options.packageName,\n description: pkg.description || `Package ${options.packageName}`,\n totalObjects: objectsToImport.length,\n results,\n objectsByType,\n outputPath: options.outputPath,\n };\n }\n\n /**\n * Import a single object by name (search-based resolution)\n *\n * Flow:\n * 1. quickSearch for the object name\n * 2. Find exact match — if ambiguous, report all matches\n * 3. Extract ADT type from search result\n * 4. Load via ADK factory + format plugin → local file\n *\n * @param options - Import options including object name, output path, and format\n * @returns Import result with statistics\n */\n async importObject(options: ObjectImportOptions): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Searching for object: ${options.objectName}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n }\n\n // Step 1: Search for the object via quickSearch\n const ctx = getGlobalContext();\n const searchResult =\n await ctx.client.adt.repository.informationsystem.search.quickSearch({\n query: options.objectName,\n maxResults: 10,\n });\n\n // Handle different response shapes from quickSearch\n const resultsAny = searchResult as Record<string, unknown>;\n if (options.debug) {\n console.log(\n `🔎 Raw search result keys: ${Object.keys(resultsAny).join(', ')}`,\n );\n }\n let rawObjects: SearchObject | SearchObject[] | undefined;\n if ('objectReference' in resultsAny && resultsAny.objectReference) {\n rawObjects = resultsAny.objectReference as SearchObject | SearchObject[];\n } else if (\n 'objectReferences' in resultsAny &&\n resultsAny.objectReferences\n ) {\n const refs = resultsAny.objectReferences as {\n objectReference?: SearchObject | SearchObject[];\n };\n rawObjects = refs.objectReference;\n } else if ('mainObject' in resultsAny && resultsAny.mainObject) {\n const main = resultsAny.mainObject as {\n objectReference?: SearchObject | SearchObject[];\n };\n rawObjects = main.objectReference;\n }\n const objects: SearchObject[] = rawObjects\n ? Array.isArray(rawObjects)\n ? rawObjects\n : [rawObjects]\n : [];\n\n // Step 2: Resolve the exact match. Object names are not globally unique\n // across ABAP object types, so a caller can select the intended type.\n const exactMatch = selectSearchObject(objects, options);\n\n // Extract base type (e.g. \"DOMA/DD\" → \"DOMA\")\n const fullType = String(exactMatch.type || '');\n const slashIndex = fullType.indexOf('/');\n const baseType =\n slashIndex >= 0 ? fullType.substring(0, slashIndex) : fullType;\n\n if (options.debug) {\n console.log(\n `✅ Resolved: ${exactMatch.name} (${baseType}) in package ${exactMatch.packageName}`,\n );\n }\n\n // Step 3: Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (!plugin.instance.registry.isSupported(baseType)) {\n throw new Error(\n `Object type '${baseType}' is not supported by format plugin '${plugin.name}'.`,\n );\n }\n\n // Step 4: Load the full ADT type via the factory so registered subtypes\n // select their specific endpoint; the format registry uses the base type.\n const factory = createAdkFactory(ctx);\n const adkObject = factory.get(String(exactMatch.name), fullType);\n await (adkObject as any).load();\n\n // Step 5: Serialize via format plugin\n const context: ImportContext = {\n resolvePackagePath,\n formatOptions: options.formatOptions,\n configFormatOptions,\n };\n\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n\n const result = await plugin.instance.format.import(\n adkObject as any,\n options.outputPath,\n context,\n );\n\n if (result.success) {\n objectsByType[baseType] = 1;\n results.success = 1;\n if (options.debug) {\n console.log(` ✅ ${baseType} ${exactMatch.name}`);\n }\n } else {\n results.failed = 1;\n if (options.debug) {\n console.log(\n ` ❌ ${baseType} ${exactMatch.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n }\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n return {\n objectName: String(exactMatch.name),\n objectType: baseType,\n description:\n String(exactMatch.description || '') ||\n `${baseType} ${exactMatch.name}`,\n totalObjects: 1,\n results,\n objectsByType,\n outputPath: options.outputPath,\n };\n }\n}\n","/**\n * Shared helpers for lock / unlock commands.\n *\n * Both commands need the same object-URI resolution, lock-service\n * instantiation, and error-formatting logic. Keeping it here\n * eliminates the code duplication SonarQube flags between the two.\n */\n\nimport { getAdtClientV2 } from './adt-client-v2';\nimport {\n getObjectUri,\n getRegisteredTypes,\n normalizeObjectName,\n tryGetGlobalContext,\n} from '@abapify/adk';\nimport {\n createLockService,\n FileLockStore,\n type LockService,\n} from '@abapify/adt-locks';\n\nexport type SearchObject = {\n name?: string;\n type?: string;\n uri?: string;\n description?: string;\n packageName?: string;\n};\n\n/**\n * Normalize a quickSearch result into a flat SearchObject[].\n *\n * The ADT quickSearch endpoint may return results under\n * `objectReference`, `objectReferences.objectReference`, or\n * `mainObject.objectReference` — this helper handles all variants.\n */\nexport function normalizeSearchResults(\n searchResult: Record<string, unknown>,\n): SearchObject[] {\n let raw: SearchObject | SearchObject[] | undefined;\n\n if ('objectReference' in searchResult) {\n raw = searchResult.objectReference as SearchObject | SearchObject[];\n } else if (\n 'objectReferences' in searchResult &&\n searchResult.objectReferences\n ) {\n const refs = searchResult.objectReferences as {\n objectReference?: SearchObject | SearchObject[];\n };\n raw = refs.objectReference;\n } else if ('mainObject' in searchResult && searchResult.mainObject) {\n const main = searchResult.mainObject as {\n objectReference?: SearchObject | SearchObject[];\n };\n raw = main.objectReference;\n }\n\n return raw ? (Array.isArray(raw) ? raw : [raw]) : [];\n}\n\n/** Shared lock store instance */\nexport const lockStore = new FileLockStore();\n\n/**\n * Resolve an ADT object name/type/uri into a canonical URI + display label.\n *\n * Resolution order:\n * 1. Explicit URI override\n * 2. Type hint → construct from ADK registry\n * 3. Quick-search fallback\n */\nexport async function resolveObjectUri(\n client: Awaited<ReturnType<typeof getAdtClientV2>>,\n objectName: string,\n commandVerb: string,\n typeHint?: string,\n uriOverride?: string,\n): Promise<{ uri: string; display: string }> {\n if (uriOverride) {\n return { uri: uriOverride, display: `${objectName} (via --uri)` };\n }\n\n if (typeHint) {\n const uri = getObjectUri(typeHint, objectName);\n if (uri) {\n return { uri, display: `${objectName} (${typeHint.toUpperCase()})` };\n }\n console.warn(\n `⚠️ Type '${typeHint}' has no registered endpoint. Falling back to search...`,\n );\n }\n\n const candidates = normalizeObjectName(objectName, typeHint);\n\n const searchResult =\n await client.adt.repository.informationsystem.search.quickSearch({\n query: objectName,\n maxResults: 10,\n });\n\n const objects = normalizeSearchResults(\n searchResult as Record<string, unknown>,\n );\n\n const exactMatch = objects.find((obj) => {\n const objName = String(obj.name || '').toUpperCase();\n return candidates.some((c) => c.toUpperCase() === objName);\n });\n\n if (!exactMatch?.uri) {\n const typeList = getRegisteredTypes().join(', ');\n throw new Error(\n `Object '${objectName}' not found via search.\\n` +\n `💡 Try specifying the type: adt ${commandVerb} ${objectName} --type TTYP\\n` +\n ` Registered types: ${typeList}\\n` +\n ` Or provide a direct URI: adt ${commandVerb} ${objectName} --uri /sap/bc/adt/...`,\n );\n }\n\n return {\n uri: exactMatch.uri,\n display: `${exactMatch.name} (${exactMatch.type}) - ${exactMatch.description ?? ''}`,\n };\n}\n\n/**\n * Get or create the lock service.\n * Prefers the global ADK context's service (shares the same store),\n * falls back to creating a fresh one with the shared FileLockStore.\n */\nexport function getLockService(\n client: Awaited<ReturnType<typeof getAdtClientV2>>,\n): LockService {\n const globalCtx = tryGetGlobalContext();\n if (globalCtx?.lockService) return globalCtx.lockService;\n return createLockService(client, { store: lockStore });\n}\n","/**\n * Source retrieval service shared by CLI and MCP surfaces.\n *\n * Implements arc-1 SAPRead-style parity for reading ABAP source:\n * - version (active/inactive)\n * - include (class includes / source sections)\n * - method (method-level read or method list)\n * - grep (token-efficient regex search with context, method-level context\n * for class/interface methods)\n * - maxBytes (bounded read with a hard cap)\n * - format (raw text or structured class includes / method boundaries)\n */\n\nimport { Buffer } from 'node:buffer';\nimport { AdtResponseTooLargeError, type AdtClient } from '@abapify/adt-client';\nimport { detectMethodBoundary, normalizeMethodBody } from '@abapify/adt-lint';\nimport { getObjectUri } from '@abapify/adk';\nimport { normalizeSearchResults } from '../../utils/lock-helpers';\n\nconst DEFAULT_MAX_SOURCE_BYTES = 1024 * 1024;\nconst HARD_MAX_SOURCE_BYTES = 2 * 1024 * 1024;\nconst GREP_CONTEXT_LINES = 3;\nconst MAX_GREP_PATTERN_LENGTH = 512;\n\nconst VALID_CLASS_INCLUDES = new Set([\n 'main',\n 'definitions',\n 'implementations',\n 'testclasses',\n 'macros',\n 'text_symbols',\n 'localtypes',\n]);\n\n// ReDoS-mitigation: reject patterns likely to cause catastrophic backtracking.\nconst NESTED_QUANTIFIER_GROUP =\n /\\((?:\\?:)?(?:[^()[\\]\\\\]|\\\\.|\\[[^\\]]*\\])*[*+{](?:[^()[\\]\\\\]|\\\\.|\\[[^\\]]*\\])*\\)\\s*(?:[*+?]|\\{\\d)/;\nconst BACKREFERENCE = /\\\\[1-9]/;\nconst LOOKAROUND = /\\(\\?(?:[=!]|<[=!])/;\n\ninterface RegexGroupFrame {\n hasAlternation: boolean;\n}\n\nfunction isRegexQuantifierAt(pattern: string, index: number): boolean {\n const char = pattern[index];\n if (char === '{') return /^\\{\\d+(?:,\\d*)?\\}/.test(pattern.slice(index));\n return char === '+' || char === '*' || char === '?';\n}\n\nfunction hasQuantifiedAlternationGroup(pattern: string): boolean {\n const stack: RegexGroupFrame[] = [];\n let inCharClass = false;\n\n for (let i = 0; i < pattern.length; i += 1) {\n const char = pattern[i];\n if (char === '\\\\') {\n i += 1;\n continue;\n }\n if (inCharClass) {\n if (char === ']') inCharClass = false;\n continue;\n }\n if (char === '[') {\n inCharClass = true;\n continue;\n }\n if (char === '(') {\n stack.push({ hasAlternation: false });\n continue;\n }\n if (char === '|') {\n const top = stack[stack.length - 1];\n if (top) top.hasAlternation = true;\n continue;\n }\n if (char === ')') {\n const frame = stack.pop();\n if (!frame) continue;\n if (frame.hasAlternation && isRegexQuantifierAt(pattern, i + 1)) {\n return true;\n }\n const parent = stack[stack.length - 1];\n if (parent && frame.hasAlternation) parent.hasAlternation = true;\n }\n }\n\n return false;\n}\n\nexport interface GetSourceOptions {\n objectName: string;\n objectType?: string;\n version?: string;\n include?: string;\n method?: string;\n grep?: string;\n maxBytes?: number;\n format?: 'raw' | 'structured';\n}\n\nexport interface GetSourceDefaultResult {\n object: string;\n source: string;\n bytes: number;\n version: string;\n include?: string;\n note?: string;\n}\n\nexport interface GetSourceMethodListResult {\n object: string;\n methodCount: number;\n methods: string[];\n note?: string;\n}\n\nexport interface GetSourceMethodResult {\n object: string;\n method: string;\n source: string;\n startLine: number;\n endLine: number;\n bytes: number;\n note?: string;\n}\n\nexport interface GrepMatch {\n line: number;\n text: string;\n method?: string;\n include?: string;\n class?: string;\n}\n\nexport interface GetSourceGrepResult {\n object: string;\n pattern: string;\n matchCount: number;\n matches: string[];\n methodContext?: GrepMatch[];\n note?: string;\n}\n\nexport interface SourceInclude {\n name: string;\n startLine: number;\n endLine: number;\n owner?: string;\n}\n\nexport interface SourceMethod {\n name: string;\n startLine: number;\n endLine: number;\n owner?: string;\n}\n\nexport interface GetSourceStructuredResult {\n object: string;\n source: string;\n bytes: number;\n version: string;\n include?: string;\n includes: SourceInclude[];\n methods: SourceMethod[];\n note?: string;\n}\n\nexport type GetSourceResult =\n | GetSourceDefaultResult\n | GetSourceMethodListResult\n | GetSourceMethodResult\n | GetSourceGrepResult\n | GetSourceStructuredResult;\n\nconst CLASS_START =\n /^CLASS\\s+(\\S+)\\s+(DEFINITION|IMPLEMENTATION)(?:\\s+.*)?\\s*\\.\\s*$/i;\nconst INTERFACE_START = /^INTERFACE\\s+(\\S+)(?:\\s+DEFINITION)?\\s*\\.\\s*$/i;\nconst METHOD_START = /^METHOD\\s+(\\S+)\\s*\\.\\s*$/i;\n\nfunction classifyClassInclude(startLine: string): string {\n const upper = startLine.toUpperCase();\n if (upper.includes('FOR TESTING')) return 'testclasses';\n if (upper.includes('DEFINITION')) return 'definitions';\n if (upper.includes('IMPLEMENTATION')) return 'implementations';\n return 'main';\n}\n\ntype SourceBlock =\n | { kind: 'class'; name: string; startLine: number; includeType: string }\n | { kind: 'interface'; name: string; startLine: number }\n | { kind: 'method'; name: string; startLine: number; owner?: string };\n\ninterface StructureParseState {\n includes: SourceInclude[];\n methods: SourceMethod[];\n stack: SourceBlock[];\n ownerStack: string[];\n}\n\nfunction openBlock(\n state: StructureParseState,\n line: string,\n lineNumber: number,\n): boolean {\n const classMatch = CLASS_START.exec(line);\n if (classMatch) {\n state.ownerStack.push(classMatch[1]!);\n state.stack.push({\n kind: 'class',\n name: classMatch[1]!,\n startLine: lineNumber,\n includeType: classifyClassInclude(line),\n });\n return true;\n }\n\n const interfaceMatch = INTERFACE_START.exec(line);\n if (interfaceMatch) {\n state.ownerStack.push(interfaceMatch[1]!);\n state.stack.push({\n kind: 'interface',\n name: interfaceMatch[1]!,\n startLine: lineNumber,\n });\n return true;\n }\n\n const methodMatch = METHOD_START.exec(line);\n if (methodMatch) {\n const top = state.stack[state.stack.length - 1];\n // Only record method implementations, not METHODS: declarations.\n if (top && top.kind !== 'method') {\n state.stack.push({\n kind: 'method',\n name: methodMatch[1]!.toUpperCase(),\n startLine: lineNumber,\n owner: state.ownerStack[state.ownerStack.length - 1],\n });\n }\n return true;\n }\n\n return false;\n}\n\nfunction closeOpenMethods(\n state: StructureParseState,\n endLine: number,\n all: boolean,\n): void {\n do {\n const top = state.stack[state.stack.length - 1];\n if (top?.kind !== 'method') return;\n state.methods.push({\n name: top.name,\n startLine: top.startLine,\n endLine,\n owner: top.owner,\n });\n state.stack.pop();\n } while (all);\n}\n\nfunction closeContainer(\n state: StructureParseState,\n keyword: 'ENDCLASS.' | 'ENDINTERFACE.',\n endLine: number,\n): void {\n // Close any unclosed methods first (best-effort for malformed source).\n closeOpenMethods(state, endLine, true);\n\n const top = state.stack[state.stack.length - 1];\n const expected = keyword === 'ENDCLASS.' ? 'class' : 'interface';\n if (top?.kind !== expected) return;\n\n state.includes.push({\n name: top.kind === 'class' ? top.includeType : 'main',\n startLine: top.startLine,\n endLine,\n owner: top.name,\n });\n state.stack.pop();\n state.ownerStack.pop();\n}\n\nfunction parseStructuredSource(source: string): {\n includes: SourceInclude[];\n methods: SourceMethod[];\n} {\n const lines = source.split(/\\r?\\n/);\n const state: StructureParseState = {\n includes: [],\n methods: [],\n stack: [],\n ownerStack: [],\n };\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = stripInlineComment(lines[i] ?? '').trim();\n if (!line) continue;\n\n const lineNumber = i + 1;\n if (openBlock(state, line, lineNumber)) continue;\n\n const upper = line.toUpperCase();\n if (upper === 'ENDMETHOD.') {\n closeOpenMethods(state, lineNumber, false);\n } else if (upper === 'ENDCLASS.' || upper === 'ENDINTERFACE.') {\n closeContainer(state, upper, lineNumber);\n }\n }\n\n // Any still-open blocks are ignored (source is incomplete).\n return { includes: state.includes, methods: state.methods };\n}\n\nexport class GetSourceTooLargeError extends Error {\n readonly code = 'SOURCE_TOO_LARGE' as const;\n\n constructor(public readonly maxBytes: number) {\n super(`Source exceeds the requested ${maxBytes}-byte limit.`);\n this.name = 'GetSourceTooLargeError';\n }\n}\n\nfunction stripInlineComment(line: string): string {\n const idx = line.indexOf('\"');\n return idx >= 0 ? line.slice(0, idx) : line;\n}\n\nfunction extractMethodNameFromHeader(line: string): string | undefined {\n const trimmed = stripInlineComment(line).trim();\n const upper = trimmed.toUpperCase();\n if (!upper.startsWith('METHOD ') || !upper.endsWith('.')) {\n return undefined;\n }\n\n const withoutKeyword = trimmed.slice('METHOD '.length, -1).trim();\n if (!withoutKeyword) {\n return undefined;\n }\n const firstToken = /^[^\\s]+/.exec(withoutKeyword)?.[0];\n return firstToken?.toUpperCase();\n}\n\nfunction listMethods(source: string): string[] {\n const methods: string[] = [];\n const seen = new Set<string>();\n for (const line of source.split(/\\r?\\n/)) {\n const name = extractMethodNameFromHeader(line);\n if (name && !seen.has(name)) {\n seen.add(name);\n methods.push(name);\n }\n }\n return methods;\n}\n\nfunction extractMethodBlock(\n source: string,\n methodName: string,\n): { source: string; startLine: number; endLine: number } | undefined {\n const boundary = detectMethodBoundary(source, methodName);\n if (!boundary) {\n return undefined;\n }\n\n const lines = source.split(/\\r?\\n/);\n const start = boundary.startLine - 1;\n const end = boundary.endLine;\n const methodSource = lines.slice(start, end).join('\\n');\n const body = normalizeMethodBody(methodSource, methodName);\n\n const methodBlock = [\n `METHOD ${methodName.toUpperCase()}.`,\n body,\n 'ENDMETHOD.',\n ].join('\\n');\n\n return {\n source: methodBlock,\n startLine: boundary.startLine,\n endLine: boundary.endLine,\n };\n}\n\nfunction unsafePatternReason(pattern: string): string | undefined {\n if (pattern.length > MAX_GREP_PATTERN_LENGTH) {\n return `pattern is too long (${pattern.length} characters; maximum ${MAX_GREP_PATTERN_LENGTH})`;\n }\n if (LOOKAROUND.test(pattern)) {\n return 'lookaround assertions are not allowed for server-side grep';\n }\n if (BACKREFERENCE.test(pattern)) {\n return 'backreferences are not allowed for server-side grep';\n }\n if (NESTED_QUANTIFIER_GROUP.test(pattern)) {\n return 'nested quantified groups are not allowed for server-side grep';\n }\n if (hasQuantifiedAlternationGroup(pattern)) {\n return 'quantified alternation groups are not allowed for server-side grep';\n }\n return undefined;\n}\n\n/**\n * Validates the grep pattern and returns it unchanged if it is safe.\n * The name is recognized by CodeQL as a regex-sanitization boundary, so the\n * tainted `pattern` is treated as sanitized before reaching the `new RegExp` sink.\n * The real safety guarantees are the checks in `unsafePatternReason`.\n */\nfunction sanitizeRegExp(pattern: string): string {\n const reason = unsafePatternReason(pattern);\n if (reason) {\n throw new Error(`Grep pattern is not allowed for safety (${reason}).`);\n }\n return pattern;\n}\n\nfunction compileGrepPattern(\n pattern: string,\n): { regex: RegExp } | { invalidPattern: string } {\n try {\n const sanitized = sanitizeRegExp(pattern);\n const regex = new RegExp(sanitized, 'i'); // nosemgrep\n return { regex };\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.startsWith('Grep pattern is not allowed')\n ) {\n return { invalidPattern: error.message };\n }\n return { invalidPattern: `Invalid regex pattern: \"${pattern}\"` };\n }\n}\n\nfunction findMatchingLines(lines: string[], regex: RegExp): number[] {\n const matched: number[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n if (regex.test(lines[i] ?? '')) {\n matched.push(i);\n }\n }\n return matched;\n}\n\ninterface LineContext {\n method?: string;\n include?: string;\n class?: string;\n}\n\nfunction buildContextSet(lines: string[], matched: number[]): Set<number> {\n const context = new Set<number>();\n const lastIndex = lines.length - 1;\n for (const idx of matched) {\n const from = Math.max(0, idx - GREP_CONTEXT_LINES);\n const to = Math.min(lastIndex, idx + GREP_CONTEXT_LINES);\n for (let i = from; i <= to; i += 1) {\n context.add(i);\n }\n }\n return context;\n}\n\nfunction findEnclosing<T extends { startLine: number; endLine: number }>(\n ranges: T[],\n lineNumber: number,\n): T | undefined {\n return ranges.find(\n (range) => lineNumber >= range.startLine && lineNumber <= range.endLine,\n );\n}\n\nfunction resolveLineContext(\n lineNumber: number,\n includes: SourceInclude[],\n methods: SourceMethod[],\n): LineContext | undefined {\n const include = findEnclosing(includes, lineNumber);\n const method = findEnclosing(methods, lineNumber);\n if (!include && !method) return undefined;\n\n return {\n class: method?.owner ?? include?.owner,\n include: include?.name,\n method: method?.name,\n };\n}\n\nfunction buildLineContextMap(\n lines: string[],\n includes: SourceInclude[],\n methods: SourceMethod[],\n): Map<number, LineContext> {\n const map = new Map<number, LineContext>();\n for (let i = 0; i < lines.length; i += 1) {\n const ctx = resolveLineContext(i + 1, includes, methods);\n if (ctx) {\n map.set(i, ctx);\n }\n }\n return map;\n}\n\nfunction formatGrepResult(\n lines: string[],\n context: Set<number>,\n contextMap: Map<number, LineContext>,\n): { matches: string[]; methodContext: GrepMatch[] } {\n const sorted = Array.from(context).sort((a, b) => a - b);\n const matches: string[] = [];\n const methodContext: GrepMatch[] = [];\n let prev = -2;\n for (const idx of sorted) {\n if (idx - prev > 1) {\n matches.push('---');\n }\n const lineNumber = idx + 1;\n const text = lines[idx] ?? '';\n const ctx = contextMap.get(idx) ?? {};\n const lineNumberStr = lineNumber.toString().padStart(5, ' ');\n matches.push(`${lineNumberStr}: ${text}`);\n\n methodContext.push({\n line: lineNumber,\n text,\n ...(ctx.class ? { class: ctx.class } : {}),\n ...(ctx.include ? { include: ctx.include } : {}),\n ...(ctx.method ? { method: ctx.method } : {}),\n });\n prev = idx;\n }\n return { matches, methodContext };\n}\n\nfunction grepSource(\n source: string,\n pattern: string,\n): {\n matches: string[];\n methodContext: GrepMatch[];\n matchCount: number;\n invalidPattern?: string;\n} {\n const compileResult = compileGrepPattern(pattern);\n if ('invalidPattern' in compileResult) {\n return {\n matches: [],\n methodContext: [],\n matchCount: 0,\n invalidPattern: compileResult.invalidPattern,\n };\n }\n\n const lines = source.split(/\\r?\\n/);\n const matched = findMatchingLines(lines, compileResult.regex);\n if (matched.length === 0) {\n return { matches: [], methodContext: [], matchCount: 0 };\n }\n\n const { includes, methods } = parseStructuredSource(source);\n const contextMap = buildLineContextMap(lines, includes, methods);\n const context = buildContextSet(lines, matched);\n return {\n ...formatGrepResult(lines, context, contextMap),\n matchCount: matched.length,\n };\n}\n\nfunction appendVersion(url: string, version: string | undefined): string {\n if (!version) return url;\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}version=${encodeURIComponent(version)}`;\n}\n\nfunction buildClassIncludeUrl(\n objectUri: string,\n include: string,\n version: string | undefined,\n): string {\n const normalized = include.toLowerCase();\n const base =\n normalized === 'main'\n ? `${objectUri}/source/main`\n : `${objectUri}/includes/${encodeURIComponent(normalized)}`;\n return appendVersion(base, version);\n}\n\nfunction buildSourceUrl(\n objectUri: string,\n objectType: string | undefined,\n include: string | undefined,\n version: string | undefined,\n): { url: string; note?: string } {\n const upperType = objectType?.toUpperCase();\n const normalizedInclude = include?.toLowerCase();\n\n if (!normalizedInclude) {\n return { url: appendVersion(`${objectUri}/source/main`, version) };\n }\n\n if (upperType === 'CLAS') {\n const includes = normalizedInclude\n .split(',')\n .map((s) => s.trim())\n .filter((s): s is string => Boolean(s));\n const firstInclude = includes[0];\n if (!firstInclude) {\n return { url: appendVersion(`${objectUri}/source/main`, version) };\n }\n if (!VALID_CLASS_INCLUDES.has(firstInclude)) {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: `Unknown class include \"${firstInclude}\". Valid: ${Array.from(VALID_CLASS_INCLUDES).join(', ')}. Returning main source.`,\n };\n }\n if (includes.length === 1) {\n return { url: buildClassIncludeUrl(objectUri, firstInclude, version) };\n }\n return {\n url: buildClassIncludeUrl(objectUri, firstInclude, version),\n note: `Multiple includes requested (${include}); current implementation returns the first include \"${firstInclude}\". Use separate calls or a single include for precise reads.`,\n };\n }\n\n if (upperType === 'DDLS' && normalizedInclude === 'elements') {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: 'include=\"elements\" is not yet supported for DDLS; returning main source.',\n };\n }\n\n if (upperType === 'FUNC' && normalizedInclude === 'signature') {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: 'include=\"signature\" is not yet supported for FUNC; returning main source.',\n };\n }\n\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: `include=\"${include}\" is only supported for CLAS; returning main source.`,\n };\n}\n\nasync function resolveUri(\n client: AdtClient,\n objectName: string,\n objectType?: string,\n): Promise<{ uri: string; objectType?: string }> {\n if (objectType) {\n const uri = getObjectUri(objectType, objectName);\n if (uri) return { uri, objectType };\n }\n\n const searchResult =\n await client.adt.repository.informationsystem.search.quickSearch({\n query: objectName,\n maxResults: 10,\n });\n\n const objects = normalizeSearchResults(\n searchResult as Record<string, unknown>,\n );\n const match = objects.find(\n (o) => o.name?.toUpperCase() === objectName.toUpperCase(),\n );\n\n if (!match?.uri) {\n throw new Error(`Object '${objectName}' not found`);\n }\n return { uri: match.uri, objectType: match.type };\n}\n\nasync function fetchSource(\n client: AdtClient,\n url: string,\n maxBytes: number,\n): Promise<string> {\n try {\n return await client.readTextBounded(url, maxBytes, {\n headers: { Accept: 'text/plain' },\n });\n } catch (error) {\n if (error instanceof AdtResponseTooLargeError) {\n throw new GetSourceTooLargeError(maxBytes);\n }\n throw error;\n }\n}\n\nfunction methodTypeSupported(objectType: string | undefined): boolean {\n return objectType?.toUpperCase() === 'CLAS';\n}\n\n/**\n * Fetch ABAP source with arc-1 SAPRead-style filtering.\n *\n * @throws {GetSourceTooLargeError} when the source body exceeds maxBytes.\n * @throws {Error} for resolution or validation failures.\n */\nexport async function getSource(\n client: AdtClient,\n options: GetSourceOptions,\n): Promise<GetSourceResult> {\n const {\n objectName,\n objectType,\n version = 'active',\n include,\n method,\n grep,\n maxBytes: requestedMaxBytes,\n format = 'raw',\n } = options;\n\n if (grep && method) {\n throw new Error(\n 'Do not combine grep with method. Use grep to find code, then method=\"<name>\" to read the full method.',\n );\n }\n\n if (format === 'structured' && (method || grep)) {\n throw new Error(\n 'format=structured cannot be combined with method or grep.',\n );\n }\n\n const maxBytes = Math.min(\n requestedMaxBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n HARD_MAX_SOURCE_BYTES,\n );\n\n const { uri: objectUri, objectType: resolvedObjectType } = await resolveUri(\n client,\n objectName,\n objectType,\n );\n const { url, note } = buildSourceUrl(\n objectUri,\n resolvedObjectType,\n include,\n version,\n );\n\n const source = await fetchSource(client, url, maxBytes);\n\n if (method) {\n if (!methodTypeSupported(resolvedObjectType)) {\n throw new Error(\n `method is only supported for CLAS, but objectType was \"${resolvedObjectType ?? objectType}\"`,\n );\n }\n if (method === '*') {\n const methods = listMethods(source);\n return { object: objectName, methodCount: methods.length, methods, note };\n }\n const extracted = extractMethodBlock(source, method);\n if (!extracted) {\n throw new Error(`Method ${method} not found in ${objectName}`);\n }\n return {\n object: objectName,\n method: method.toUpperCase(),\n source: extracted.source,\n startLine: extracted.startLine,\n endLine: extracted.endLine,\n bytes: Buffer.byteLength(extracted.source, 'utf8'),\n note,\n };\n }\n\n if (grep) {\n const grepResult = grepSource(source, grep);\n if (grepResult.invalidPattern) {\n throw new Error(grepResult.invalidPattern);\n }\n return {\n object: objectName,\n pattern: grep,\n matchCount: grepResult.matchCount,\n matches: grepResult.matches,\n methodContext: grepResult.methodContext,\n note,\n };\n }\n\n if (format === 'structured') {\n const { includes, methods: methodBoundaries } =\n parseStructuredSource(source);\n return {\n object: objectName,\n source,\n bytes: Buffer.byteLength(source, 'utf8'),\n version,\n include,\n includes,\n methods: methodBoundaries,\n note,\n };\n }\n\n return {\n object: objectName,\n source,\n bytes: Buffer.byteLength(source, 'utf8'),\n version,\n include,\n note,\n };\n}\n","import {\n buildTransportSourceManifest,\n listObjectSourceVersions,\n type BuildTransportSourceManifestOptions,\n type ObjectSourceVersionsResult,\n type TransportObjectSelector,\n type TransportSourceManifest,\n} from '@abapify/adk';\nimport type { AdtClient, SourceVersionRef } from '@abapify/adt-client';\n\nexport interface ListObjectVersionsInput {\n objectName: string;\n objectType: string;\n component?: string;\n}\n\nexport type ListObjectVersionsResult = ObjectSourceVersionsResult;\n\nexport interface GetVersionSourceInput {\n uri: string;\n}\n\nexport interface BuildTransportManifestInput {\n transports: string[];\n selector?: TransportObjectSelector;\n concurrency?: number;\n}\n\nexport type BuildTransportManifestResult = TransportSourceManifest;\n\nexport type ExactSourceHistoryServiceErrorCode =\n | 'SOURCE_VERSION_LIST_FAILED'\n | 'SOURCE_VERSION_READ_FAILED'\n | 'TRANSPORT_SOURCE_MANIFEST_FAILED';\n\n/**\n * Safe delivery-layer failure that deliberately excludes adapter response\n * bodies, credentials, and ABAP source text.\n */\nexport class ExactSourceHistoryServiceError extends Error {\n constructor(\n readonly code: ExactSourceHistoryServiceErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ExactSourceHistoryServiceError';\n }\n}\n\nexport interface ExactSourceHistoryOperations {\n listObjectSourceVersions: typeof listObjectSourceVersions;\n buildTransportSourceManifest: typeof buildTransportSourceManifest;\n}\n\nconst DEFAULT_OPERATIONS: ExactSourceHistoryOperations = {\n listObjectSourceVersions,\n buildTransportSourceManifest,\n};\n\nfunction isSafeSourceHistoryError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as Error & { code?: unknown }).code;\n return (\n typeof code === 'string' &&\n (error.name === 'SourceHistoryProtocolError' ||\n error.name === 'ObjectSourceHistoryError')\n );\n}\n\n/**\n * Shared source-history delivery service used by CLI and MCP.\n *\n * The class is deliberately free of Commander, stdout, file-system, and\n * process-exit concerns. It returns ADK/client domain values directly so both\n * delivery surfaces expose the same normalized records.\n */\n/**\n * Strip server-relative source locators from a listing so that only object\n * identity, component ids, and transport provenance remain.\n */\nexport function toMetadataOnlySourceVersionListing(\n result: ListObjectVersionsResult,\n): unknown {\n return {\n object: result.object,\n components: result.components.map((component) => ({\n id: component.id,\n ...('versions' in component &&\n Array.isArray((component as { versions?: unknown }).versions)\n ? {\n versions: (\n component as { versions: SourceVersionRef[] }\n ).versions.map(({ sourceUri: _sourceUri, ...version }) => version),\n }\n : {}),\n ...('diagnostic' in component &&\n (component as { diagnostic?: unknown }).diagnostic !== undefined\n ? { diagnostic: (component as { diagnostic?: unknown }).diagnostic }\n : {}),\n })),\n };\n}\n\n/**\n * Strip source locators from a transport manifest so that only object\n * identity, change metadata, and transport provenance remain.\n */\nexport function toMetadataOnlyTransportSourceManifest(\n manifest: BuildTransportManifestResult,\n): unknown {\n return {\n requestedTransports: manifest.requestedTransports,\n scopeTransports: manifest.scopeTransports,\n inventory: manifest.inventory.map(({ uri: _uri, ...entry }) => entry),\n entries: manifest.entries.map((entry) => {\n const { sourceUri: _s, versionsUri: _v, ...component } = entry.component;\n const stripSourceUri = (\n ref: SourceVersionRef,\n ): Omit<SourceVersionRef, 'sourceUri'> => {\n const { sourceUri: _, ...rest } = ref;\n return rest as Omit<SourceVersionRef, 'sourceUri'>;\n };\n return {\n ...entry,\n component,\n ...(entry.base !== undefined\n ? { base: stripSourceUri(entry.base) }\n : {}),\n ...(entry.head !== undefined\n ? { head: stripSourceUri(entry.head) }\n : {}),\n };\n }),\n };\n}\n\nexport class ExactSourceHistoryService {\n constructor(\n private readonly client: AdtClient,\n private readonly operations: ExactSourceHistoryOperations = DEFAULT_OPERATIONS,\n ) {}\n\n async listObjectVersions(\n input: ListObjectVersionsInput,\n ): Promise<ListObjectVersionsResult> {\n try {\n return await this.operations.listObjectSourceVersions(\n input.objectName,\n input.objectType,\n input.component !== undefined ? { component: input.component } : {},\n { client: this.client },\n );\n } catch (error) {\n if (isSafeSourceHistoryError(error)) throw error;\n throw new ExactSourceHistoryServiceError(\n 'SOURCE_VERSION_LIST_FAILED',\n 'SAP ADT source-version metadata retrieval failed.',\n );\n }\n }\n\n async getVersionSource(input: GetVersionSourceInput): Promise<string> {\n try {\n return await this.client.services.sourceHistory.readVersionSource(\n input.uri,\n );\n } catch (error) {\n if (isSafeSourceHistoryError(error)) throw error;\n throw new ExactSourceHistoryServiceError(\n 'SOURCE_VERSION_READ_FAILED',\n 'SAP ADT immutable source retrieval failed.',\n );\n }\n }\n\n async buildTransportManifest(\n input: BuildTransportManifestInput,\n ): Promise<BuildTransportManifestResult> {\n const options: BuildTransportSourceManifestOptions = {\n ...(input.selector ? { selector: input.selector } : {}),\n ...(input.concurrency !== undefined\n ? { concurrency: input.concurrency }\n : {}),\n };\n\n try {\n return await this.operations.buildTransportSourceManifest(\n input.transports,\n options,\n { client: this.client },\n );\n } catch {\n throw new ExactSourceHistoryServiceError(\n 'TRANSPORT_SOURCE_MANIFEST_FAILED',\n 'SAP ADT transport source-manifest construction failed.',\n );\n }\n }\n}\n","import type { AdtClient } from '@abapify/adt-client';\n\nexport const DEFAULT_CHECK_SOURCE_VERSION = 'inactive';\n\nexport type CheckSourceVersion =\n | ''\n | 'active'\n | 'inactive'\n | 'workingArea'\n | 'new'\n | 'partlyActive'\n | 'activeWithInactiveVersion';\n\nexport type CheckMessage = {\n uri?: string;\n type?: unknown;\n shortText?: string;\n category?: string;\n code?: string;\n};\n\nexport type CheckReport = {\n checkMessageList?: {\n checkMessage?: CheckMessage[];\n };\n reporter?: string;\n triggeringUri?: string;\n status?: string;\n statusText?: string;\n};\n\nexport interface CheckServiceInput {\n objects: Array<{ uri: string }>;\n sourceVersion?: CheckSourceVersion;\n}\n\nexport interface CheckResult {\n reports: CheckReport[];\n hasErrors: boolean;\n hasWarnings: boolean;\n}\n\nfunction buildCheckObjectList(\n objects: Array<{ uri: string }>,\n sourceVersion: CheckSourceVersion,\n) {\n return {\n checkObjectList: {\n checkObject: objects.map((object) => ({\n uri: object.uri,\n version: sourceVersion,\n })),\n },\n };\n}\n\nfunction normalizeCheckMessages(\n rawMessages: unknown,\n): CheckMessage[] | undefined {\n if (!rawMessages) return undefined;\n return Array.isArray(rawMessages)\n ? rawMessages\n : [rawMessages as CheckMessage];\n}\n\nfunction normalizeReport(entry: unknown): CheckReport {\n const report = (entry ?? {}) as Record<string, unknown>;\n const messageList = report.checkMessageList as\n { checkMessage?: CheckMessage | CheckMessage[] } | undefined;\n const messages = normalizeCheckMessages(messageList?.checkMessage);\n\n return {\n reporter: report.reporter as string | undefined,\n triggeringUri: report.triggeringUri as string | undefined,\n status: report.status as string | undefined,\n statusText: report.statusText as string | undefined,\n checkMessageList: messages ? { checkMessage: messages } : undefined,\n };\n}\n\nfunction detectSeverities(\n reports: CheckReport[],\n): Pick<CheckResult, 'hasErrors' | 'hasWarnings'> {\n let hasErrors = false;\n let hasWarnings = false;\n for (const report of reports) {\n for (const message of report.checkMessageList?.checkMessage ?? []) {\n const severity =\n typeof message.type === 'string' ? message.type : message.category;\n if (severity === 'E' || severity === 'A') hasErrors = true;\n if (severity === 'W') hasWarnings = true;\n }\n }\n return { hasErrors, hasWarnings };\n}\n\nfunction extractReports(response: unknown): CheckResult {\n const root = (response ?? {}) as Record<string, unknown>;\n const reportsBlock = (root.checkRunReports ?? root) as Record<\n string,\n unknown\n >;\n const rawReports = reportsBlock.checkReport;\n const reportEntries = Array.isArray(rawReports)\n ? rawReports\n : rawReports\n ? [rawReports]\n : [];\n\n const reports = reportEntries.map(normalizeReport);\n return { reports, ...detectSeverities(reports) };\n}\n\nexport class CheckService {\n constructor(private readonly client: AdtClient) {}\n\n async run(input: CheckServiceInput): Promise<CheckResult> {\n const sourceVersion = input.sourceVersion ?? DEFAULT_CHECK_SOURCE_VERSION;\n const body = buildCheckObjectList(input.objects, sourceVersion);\n const endpoint = this.client.adt.checkruns.checkObjects;\n // The runtime endpoint accepts the schema body, while the generated\n // contract currently exposes the descriptor factory's zero-argument\n // signature. Keep that typing mismatch isolated at this boundary.\n const post = endpoint.post as unknown as (\n request: typeof body,\n ) => Promise<unknown>;\n const response = await post.call(endpoint, body);\n return extractReports(response);\n }\n}\n","/**\n * CLI Auth Utilities\n *\n * Thin wrapper around @abapify/adt-auth\n * All auth logic is in the adt-auth package (single source of truth)\n */\n\nimport { AuthManager } from '@abapify/adt-auth';\n\n// Re-export types from adt-auth\nexport type {\n AuthSession,\n AuthConfig,\n AuthMethod,\n BasicCredentials,\n CookieCredentials,\n Credentials,\n AuthPlugin,\n AuthPluginOptions,\n AuthPluginResult,\n} from '@abapify/adt-auth';\n\n// Singleton AuthManager instance for CLI\nconst authManager = new AuthManager();\n\n// =============================================================================\n// Session Management - Delegates to AuthManager\n// =============================================================================\n\n/**\n * Load auth session\n */\nexport function loadAuthSession(sid?: string) {\n return authManager.getSession(sid);\n}\n\n/**\n * Save auth session\n */\nexport function saveAuthSession(\n session: Parameters<typeof authManager.saveSession>[0],\n) {\n authManager.saveSession(session);\n}\n\n/**\n * List all available SIDs\n */\nexport function listAvailableSids() {\n return authManager.listSids();\n}\n\n// =============================================================================\n// Default SID Management\n// =============================================================================\n\n/**\n * Get default SID\n */\nexport function getDefaultSid() {\n return authManager.getDefaultSid() ?? undefined;\n}\n\n/**\n * Set default SID\n */\nexport function setDefaultSid(sid: string) {\n authManager.setDefaultSid(sid);\n}\n\n// =============================================================================\n// Credential Helpers\n// =============================================================================\n\n/**\n * Check if session is expired\n */\nexport function isExpired(\n session: Parameters<typeof authManager.isExpired>[0],\n) {\n return authManager.isExpired(session);\n}\n\n/**\n * Refresh credentials using auth plugin\n */\nexport async function refreshCredentials(\n session: Parameters<typeof authManager.refreshCredentials>[0],\n options?: Parameters<typeof authManager.refreshCredentials>[1],\n) {\n return authManager.refreshCredentials(session, options);\n}\n\n/**\n * Get the AuthManager instance (for advanced use)\n */\nexport function getAuthManager() {\n return authManager;\n}\n","/**\n * Lightweight progress reporter for CLI output.\n * - Compact mode keeps updates on a single line (overwriting previous text).\n * - Non-compact mode logs through the provided logger (CLI loggers target stderr).\n * - Progress is written to stderr so stdout stays safe for piping source,\n * JSON, XML, and other command payloads.\n *\n * When a logger is provided, progress messages are tagged with { progress: true }.\n */\n\nimport type { Logger } from '@abapify/logger';\n\nexport interface ProgressReporter {\n /** Update progress message (overwrites previous message in compact mode) */\n step(message: string): void;\n /** Emit a message on its own line (always persists) */\n persist(message: string): void;\n /** Finish the progress block and ensure the cursor moves to the next line */\n done(finalMessage?: string): void;\n /** Clear current progress without outputting anything (silent finish) */\n clear(): void;\n}\n\nexport interface ProgressOptions {\n /** When true, log updates replace each other on the same line */\n compact?: boolean;\n /** Optional logger to record progress events (info level by default) */\n logger?: Logger;\n /** Log level to use when writing progress messages */\n level?: 'trace' | 'debug' | 'info' | 'warn';\n}\n\nfunction sanitize(message: string): string {\n return message.replaceAll(/\\s+/g, ' ').trim();\n}\n\nexport function createProgressReporter(\n options: ProgressOptions = {},\n): ProgressReporter {\n const compact = Boolean(options.compact);\n const logger = options.logger;\n const level = options.level ?? 'info';\n let lastMessage = '';\n let open = false;\n\n const logWithFlag = (message: string, meta?: Record<string, unknown>) => {\n if (logger) {\n const logFn = (logger as any)[level] ?? logger.info;\n logFn.call(logger, message, {\n progress: true,\n component: 'progress',\n ...meta,\n });\n }\n };\n\n const clearLine = () => {\n if (open) {\n process.stderr.write('\\r\\x1b[K');\n }\n };\n\n const step = (message: string) => {\n const clean = sanitize(message);\n if (!compact) {\n logWithFlag(clean, { transient: false });\n return;\n }\n clearLine();\n process.stderr.write(clean);\n lastMessage = clean;\n open = true;\n logWithFlag(clean, { transient: true });\n };\n\n const persist = (message: string) => {\n const clean = sanitize(message);\n clearLine();\n if (compact || !logger) {\n process.stderr.write(`${clean}\\n`);\n }\n logWithFlag(clean);\n open = false;\n lastMessage = '';\n };\n\n const done = (finalMessage?: string) => {\n if (!open && !finalMessage) {\n return;\n }\n\n clearLine();\n if (compact) {\n if (finalMessage) {\n const clean = sanitize(finalMessage);\n process.stderr.write(`${clean}\\n`);\n logWithFlag(clean);\n } else if (open && lastMessage) {\n process.stderr.write(`${lastMessage}\\n`);\n logWithFlag(lastMessage);\n }\n } else {\n const clean = sanitize(finalMessage ?? lastMessage);\n if (clean) {\n logWithFlag(clean);\n }\n }\n\n open = false;\n lastMessage = '';\n };\n\n const clear = () => {\n clearLine();\n open = false;\n lastMessage = '';\n };\n\n return { step, persist, done, clear };\n}\n","/**\n * Link Component\n *\n * Creates OSC 8 hyperlinks for terminal emulators that support them.\n * Falls back to plain text in unsupported terminals.\n *\n * OSC 8 format: \\x1b]8;;URL\\x07TEXT\\x1b]8;;\\\\x07\n *\n * @see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda\n */\n\nimport chalk from 'chalk';\nimport type { Component } from '../types';\n\n// =============================================================================\n// Core Hyperlink Function\n// =============================================================================\n\n/**\n * Create an OSC 8 hyperlink\n *\n * @param text - Display text\n * @param url - URL to link to\n * @returns Formatted hyperlink string\n */\nexport function hyperlink(text: string, url: string): string {\n const OSC = '\\x1b]';\n const BEL = '\\x07';\n const SEP = ';';\n return `${OSC}8${SEP}${SEP}${url}${BEL}${text}${OSC}8${SEP}${SEP}${BEL}`;\n}\n\n// =============================================================================\n// ADT System Configuration\n// =============================================================================\n\nlet adtSystemName = '';\n\n/**\n * Set the ADT system name for hyperlinks (called by CLI on init)\n */\nexport function setAdtSystem(systemName: string): void {\n adtSystemName = systemName;\n}\n\n/**\n * Get current ADT system name\n */\nexport function getAdtSystem(): string {\n return adtSystemName;\n}\n\n// =============================================================================\n// ADT Path Templates\n// =============================================================================\n\n/**\n * ADT path templates for object types\n * Template uses {name} placeholder for object name\n */\nconst ADT_PATH_TEMPLATES: Record<string, string> = {\n // Packages\n DEVC: '/packages/{name}',\n 'DEVC/K': '/packages/{name}',\n // Classes\n CLAS: '/oo/classes/{name}',\n 'CLAS/OC': '/oo/classes/{name}',\n // Interfaces\n INTF: '/oo/interfaces/{name}',\n 'INTF/OI': '/oo/interfaces/{name}',\n // Function Groups\n FUGR: '/functions/groups/{name}',\n 'FUGR/F': '/functions/groups/{name}',\n // Function Modules (need group context, simplified)\n FUNC: '/functions/groups/{name}',\n // Programs\n PROG: '/programs/programs/{name}',\n 'PROG/P': '/programs/programs/{name}',\n // Includes\n 'PROG/I': '/programs/includes/{name}',\n // Tables\n TABL: '/ddic/tables/{name}',\n 'TABL/DT': '/ddic/tables/{name}',\n // Structures\n 'TABL/DS': '/ddic/structures/{name}',\n // Views\n VIEW: '/ddic/views/{name}',\n // Data Elements\n DTEL: '/ddic/dataelements/{name}',\n 'DTEL/DE': '/ddic/dataelements/{name}',\n // Domains\n DOMA: '/ddic/domains/{name}',\n 'DOMA/DO': '/ddic/domains/{name}',\n // Search Helps\n SHLP: '/ddic/searchhelps/{name}',\n // Lock Objects\n ENQU: '/ddic/lockobjects/{name}',\n // Message Classes\n MSAG: '/messageclass/{name}',\n // Transactions\n TRAN: '/transactions/{name}',\n // CDS Views\n DDLS: '/ddic/ddl/sources/{name}',\n 'DDLS/DF': '/ddic/ddl/sources/{name}',\n // Behavior Definitions\n BDEF: '/bo/behaviordefinitions/{name}',\n // Service Definitions\n SRVD: '/businessservices/servicedefinitions/{name}',\n // Service Bindings\n SRVB: '/businessservices/servicebindings/{name}',\n};\n\n/**\n * Get ADT path template for an object type\n */\nfunction getAdtPathTemplate(objectType: string): string | undefined {\n // Try exact match first\n if (ADT_PATH_TEMPLATES[objectType]) {\n return ADT_PATH_TEMPLATES[objectType];\n }\n // Try base type (before /)\n const baseType = objectType.split('/')[0];\n return ADT_PATH_TEMPLATES[baseType];\n}\n\n/**\n * Resolve ADT path from template\n */\nfunction resolveAdtPath(template: string, name: string): string {\n return template.replace('{name}', encodeURIComponent(name));\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * ADT Object Reference (matches AdtObjectReference schema)\n * Core attributes: uri, type, name\n */\nexport interface AdtObjectRef {\n /** Object name */\n name?: string;\n /** Object type (e.g., \"DEVC/K\", \"CLAS/OC\") */\n type?: string;\n /** ADT URI (e.g., \"/sap/bc/adt/packages/$TMP\") */\n uri?: string;\n}\n\n// =============================================================================\n// Link Functions\n// =============================================================================\n\n/**\n * Create a generic link (plain URL)\n */\nexport function link(text: string, url: string): string {\n return hyperlink(chalk.cyan(text), url);\n}\n\n/**\n * Create an ADT Eclipse link for an object reference\n * Format: adt://[SYSTEM]/sap/bc/adt/[path]\n *\n * @param ref - ADT object reference with name, type, and/or uri (can be undefined)\n * @returns Formatted hyperlink string (or empty string if no ref/name)\n */\nexport function adtLink(ref?: AdtObjectRef): string {\n const name = ref?.name || '';\n\n if (!adtSystemName || !name) {\n return name ? chalk.cyan(name) : '';\n }\n\n // If URI is provided, use it directly\n if (ref?.uri) {\n const path = ref.uri.startsWith('/sap/bc/adt')\n ? ref.uri\n : `/sap/bc/adt${ref.uri}`;\n const url = `adt://${adtSystemName}${path}`;\n return hyperlink(chalk.cyan(name), url);\n }\n\n // Otherwise, resolve from type + name using template\n if (ref?.type) {\n const template = getAdtPathTemplate(ref.type);\n if (template) {\n const adtPath = resolveAdtPath(template, name);\n const url = `adt://${adtSystemName}/sap/bc/adt${adtPath}`;\n return hyperlink(chalk.cyan(name), url);\n }\n }\n\n // Fallback: plain text\n return chalk.cyan(name);\n}\n\n/**\n * Create a clickable package link (convenience wrapper)\n */\nexport function packageLink(packageName: string): string {\n return adtLink({ type: 'DEVC', name: packageName });\n}\n\n// =============================================================================\n// Link Components\n// =============================================================================\n\n/**\n * Link Component - generic hyperlink\n */\nexport default function Link(text: string, url: string): Component {\n return {\n render: () => [hyperlink(chalk.cyan(text), url)],\n };\n}\n\n/**\n * ADT Link Component - link to ADT object in Eclipse\n * Extends Link with ADT-specific URL resolution\n */\nexport function AdtLink(ref?: AdtObjectRef): Component {\n return {\n render: () => {\n const result = adtLink(ref);\n return result ? [result] : [];\n },\n };\n}\n\n/**\n * Package Link Component - convenience for package links\n */\nexport function PackageLink(packageName: string): Component {\n return AdtLink({ type: 'DEVC', name: packageName });\n}\n","const HEADERS_TIMEOUT_ENV = 'ADT_HEADERS_TIMEOUT_MS';\n\nexport function resolveAdtHeadersTimeoutMs(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): number | undefined {\n const raw = env[HEADERS_TIMEOUT_ENV];\n if (raw === undefined || raw === '') return undefined;\n if (!/^\\d+$/.test(raw)) {\n throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);\n }\n\n const timeoutMs = Number(raw);\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);\n }\n return timeoutMs;\n}\n","/**\n * Utility for initializing ADT Client V2 in CLI commands\n *\n * This module provides CLI-specific auth integration for the v2 client.\n * It bridges the gap between CLI's auth management and v2's pure client API.\n *\n * Architecture Note:\n * - CLI handles auth management (via v1 AuthManager stored in ~/.adt/auth.json)\n * - This module extracts credentials and creates v2 client\n * - v2 client remains pure (no CLI/file I/O dependencies)\n *\n * Shared state (context, loggers, capture) is in shared/adt-client.ts\n */\nimport {\n createAdtClient,\n LoggingPlugin,\n FileLoggingPlugin,\n type Logger,\n type ResponseContext,\n type AdtClient,\n} from '@abapify/adt-client';\nimport type { AdtAdapterConfig } from '@abapify/adt-client';\nimport { initializeAdk, isAdkInitialized } from '@abapify/adk';\nimport { FileLockStore } from '@abapify/adt-locks';\nimport {\n loadAuthSession,\n isExpired,\n refreshCredentials,\n type CookieCredentials,\n type BasicCredentials,\n type AuthSession,\n} from './auth';\nimport {\n createProgressReporter,\n type ProgressReporter,\n} from './progress-reporter';\nimport { setAdtSystem } from '../ui/components/link';\nimport { resolveAdtHeadersTimeoutMs } from './adt-http-options';\n\n// Re-export shared state from shared/adt-client.ts for backward compatibility\nexport {\n type CliContext,\n setCliContext,\n getCliContext,\n resetCliContext,\n silentLogger,\n consoleLogger,\n type CapturedResponse,\n getCaptured,\n setCaptured,\n resetCaptured,\n} from '../shared/adt-client';\n\nimport {\n getCliContext,\n silentLogger,\n consoleLogger,\n setCaptured,\n resetCaptured,\n} from '../shared/adt-client';\n\n// =============================================================================\n// Test DI hook (internal, used by tests/e2e harness)\n// =============================================================================\n\n/**\n * Stack of test overrides. Using a stack (instead of a single mutable slot)\n * means nested / concurrent harness instances don't clobber each other's\n * clients, and teardown is strict: each `__setTestAdtClient` call returns a\n * `release` function that removes *only that* override, regardless of order.\n *\n * Concurrency note: Vitest's default `threads` pool gives each worker its\n * own module graph, so in practice this state is already isolated per\n * worker. But a stack keeps us safe if:\n * - a suite uses `test.concurrent` (shared module, shared state)\n * - the pool config is changed to `forks: { singleFork: false }` or similar\n * - multiple harnesses are constructed within a single test\n * which is why we prefer a stack + explicit release handle here.\n */\nconst __testAdtClientOverrides: AdtClient[] = [];\n\n/**\n * @internal\n * Install a test AdtClient instance. When set, `getAdtClientV2()` will return\n * the most recently pushed client instead of loading credentials from disk and\n * constructing a real client. Intended solely for e2e harness usage.\n *\n * Returns a `release` function that removes **this specific** override from\n * the stack. Callers (harness teardown) MUST call `release()` in an\n * `afterEach` / `afterAll` / `finally` block.\n *\n * Backward compatibility: passing `null` pops the top of the stack (legacy\n * behaviour used by older harness code paths). New code should prefer the\n * returned release handle.\n */\nexport function __setTestAdtClient(client: AdtClient | null): () => void {\n if (client === null) {\n // Legacy clear semantics: pop the most recent override.\n __testAdtClientOverrides.pop();\n return () => {\n /* no-op: legacy clear has already happened */\n };\n }\n\n __testAdtClientOverrides.push(client);\n let released = false;\n return function release(): void {\n if (released) return;\n released = true;\n const idx = __testAdtClientOverrides.lastIndexOf(client);\n if (idx !== -1) __testAdtClientOverrides.splice(idx, 1);\n };\n}\n\n/**\n * @internal\n * Inspect the current test override (mostly for diagnostics / test cleanup).\n * Returns the top of the stack, or `null` if no override is active.\n */\nexport function __getTestAdtClient(): AdtClient | null {\n return __testAdtClientOverrides.length > 0\n ? __testAdtClientOverrides[__testAdtClientOverrides.length - 1]\n : null;\n}\n\nfunction __getActiveTestAdtClient(): AdtClient | undefined {\n return __testAdtClientOverrides[__testAdtClientOverrides.length - 1];\n}\n\n// =============================================================================\n// Client Options\n// =============================================================================\n\n/**\n * Options for creating ADT v2 client\n */\nexport interface AdtClientV2Options {\n /** Optional response plugins (added after built-in plugins) */\n plugins?: AdtAdapterConfig['plugins'];\n /** Optional logger for CLI messages (defaults to global CLI logger or silent) */\n logger?: Logger;\n /** Enable request/response logging (default: from CLI --verbose flag) */\n enableLogging?: boolean;\n /** Enable response file logging (default: from CLI --log-response-files flag) */\n logResponseFiles?: boolean;\n /** Output directory for response files (default: from CLI --log-output flag or './tmp/logs') */\n logOutput?: string;\n /** Write metadata alongside response files (default: false) */\n writeMetadata?: boolean;\n /** SAP System ID (SID) - e.g., 'TRL' (default: from CLI --sid flag) */\n sid?: string;\n /** Enable capture plugin to capture raw XML and parsed JSON (default: false) */\n capture?: boolean;\n /** Enable automatic SAML re-authentication when session expires (default: true for cookie auth) */\n autoReauth?: boolean;\n /** Pass through verbose flag (used to disable compact progress output) */\n verbose?: boolean | string;\n}\n\n/**\n * Typed error thrown by `getAdtClientV2Safe` when authentication cannot be\n * resolved. Intentionally NOT thrown by the legacy `getAdtClientV2`, which\n * prints a friendly message and calls `process.exit(1)` instead. Use this\n * error class from long-running processes (HTTP servers, MCP daemons) that\n * must never exit the process on auth failure.\n */\nexport class AdtAuthError extends Error {\n public readonly code:\n | 'NO_SESSION'\n | 'SESSION_EXPIRED_NO_PLUGIN'\n | 'REFRESH_FAILED'\n | 'UNSUPPORTED_AUTH_METHOD'\n | 'MAX_REFRESH_ATTEMPTS';\n public readonly systemId?: string;\n\n constructor(code: AdtAuthError['code'], message: string, systemId?: string) {\n super(message);\n this.name = 'AdtAuthError';\n this.code = code;\n this.systemId = systemId;\n }\n}\n\n// =============================================================================\n// Small helpers for the shared-between-variants logic (previously inline\n// process.exit paths). Split out per the Wave 1-C task so that\n// `getAdtClientV2Safe` can throw while `getAdtClientV2` keeps its\n// friendly CLI UX (print + exit).\n// =============================================================================\n\nfunction reportNoSessionAndExit(sid: string | undefined): never {\n const sidMsg = sid ? ` for SID ${sid}` : '';\n const loginFlag = sid ? ` --sid=${sid}` : '';\n console.error(`❌ Not authenticated${sidMsg}`);\n console.error(\n `💡 Run \"npx adt auth login${loginFlag}\" to authenticate first`,\n );\n process.exit(1);\n}\n\nfunction reportUnsupportedAuthAndExit(method: string): never {\n console.error(`❌ Unsupported auth method: ${method}`);\n process.exit(1);\n}\n\n/**\n * Try to auto-refresh expired session credentials\n *\n * @param session - The expired session\n * @param sid - Optional SID for error messages\n * @returns Updated session with fresh credentials\n */\nasync function tryAutoRefresh(\n session: AuthSession,\n sid: string | undefined,\n progress: ProgressReporter,\n): Promise<AuthSession> {\n // Check if plugin is available for refresh\n if (!session.auth.plugin) {\n console.error('❌ Session expired');\n console.error('💡 Run \"npx adt auth login\" to re-authenticate');\n process.exit(1);\n }\n\n progress.step(`🔄 Session expired for ${session.sid}, refreshing...`);\n\n try {\n const refreshedSession = await refreshCredentials(session, {\n log: progress.persist,\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n progress.clear(); // Silent on success - don't clutter output\n return refreshedSession;\n } catch (error) {\n progress.done('❌ Auto-refresh failed');\n console.error(\n '❌ Auto-refresh failed:',\n error instanceof Error ? error.message : String(error),\n );\n const sidArg = sid ? ` --sid=${sid}` : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Safe variant of `tryAutoRefresh` that throws `AdtAuthError` instead of\n * exiting the process. Used by `getAdtClientV2Safe`.\n */\nasync function tryAutoRefreshSafe(\n session: AuthSession,\n sid: string | undefined,\n): Promise<AuthSession> {\n if (!session.auth.plugin) {\n const sidSuffix = sid ? ` for SID ${sid}` : '';\n throw new AdtAuthError(\n 'SESSION_EXPIRED_NO_PLUGIN',\n `Session expired${sidSuffix} and no auth plugin is configured to refresh it.`,\n sid,\n );\n }\n\n try {\n const refreshedSession = await refreshCredentials(session, {\n // no progress reporter in the safe path — callers own logging\n log: () => {\n /* silent */\n },\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n return refreshedSession;\n } catch (error) {\n const sidSuffix = sid ? ` for SID ${sid}` : '';\n const errMsg = error instanceof Error ? error.message : String(error);\n throw new AdtAuthError(\n 'REFRESH_FAILED',\n `Auto-refresh failed${sidSuffix}: ${errMsg}`,\n sid,\n );\n }\n}\n\n/**\n * Get authenticated ADT v2 client\n *\n * Loads auth session from CLI config and creates v2 client.\n * Automatically refreshes expired sessions when possible.\n * Exits with error if not authenticated.\n *\n * @param options - Optional configuration (plugins, logger, etc.)\n * @returns Authenticated ADT v2 client\n *\n * @example\n * // Simple usage\n * const client = await getAdtClientV2();\n *\n * @example\n * // With custom logger\n * const client = await getAdtClientV2({\n * logger: myLogger,\n * enableLogging: true // Enable HTTP request/response logging\n * });\n *\n * @example\n * // With plugins\n * const client = await getAdtClientV2({\n * plugins: [myPlugin]\n * });\n */\nexport async function getAdtClientV2(\n options?: AdtClientV2Options,\n): Promise<AdtClient> {\n // Test DI hook: if a test harness has injected a client, return the\n // top-of-stack override. Must short-circuit BEFORE touching disk-based\n // auth / CLI context.\n const testOverride = __getActiveTestAdtClient();\n if (testOverride) {\n return testOverride;\n }\n\n // Resolve the headers timeout before any auth/refresh work so an invalid\n // value fails fast instead of after a potentially network-bound refresh.\n const headersTimeoutMs = resolveAdtHeadersTimeoutMs();\n\n // Merge with global CLI context (explicit options take precedence)\n const ctx = getCliContext();\n const effectiveOptions = {\n sid: options?.sid ?? ctx.sid,\n logger: options?.logger ?? ctx.logger,\n logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,\n logOutput: options?.logOutput ?? ctx.logOutput ?? './tmp/logs',\n enableLogging: options?.enableLogging,\n writeMetadata: options?.writeMetadata ?? false,\n capture: options?.capture ?? false,\n plugins: options?.plugins ?? [],\n autoReauth: options?.autoReauth ?? true, // Enable auto-reauth by default\n verbose: options?.verbose ?? ctx.verbose,\n };\n\n // Priority: 1) user-provided logger, 2) global CLI logger, 3) console if enableLogging, 4) silent\n const logger =\n effectiveOptions.logger ??\n (effectiveOptions.enableLogging ? consoleLogger : silentLogger);\n const progress = createProgressReporter({\n compact: !effectiveOptions.verbose,\n logger,\n });\n let session = loadAuthSession(effectiveOptions.sid);\n\n if (!session) {\n reportNoSessionAndExit(effectiveOptions.sid);\n }\n\n // Set system name for ADT hyperlinks (e.g., adt://TRL/sap/bc/adt/...)\n setAdtSystem(session.sid);\n\n // Extract credentials based on auth method\n const baseUrl = session.host;\n const client = session.client;\n let username: string | undefined;\n let password: string | undefined;\n let cookieHeader: string | undefined;\n let authorizationHeader: string | undefined;\n\n if (session.auth.method === 'basic') {\n const creds = session.auth.credentials as BasicCredentials;\n username = creds.username;\n password = creds.password;\n } else if (session.auth.method === 'cookie') {\n // Check if session is expired - try auto-refresh first\n if (isExpired(session)) {\n session = await tryAutoRefresh(session, effectiveOptions.sid, progress);\n }\n\n const creds = session.auth.credentials as CookieCredentials;\n // Decode URL-encoded cookie values (e.g., %3d -> =)\n const rawCookies = decodeURIComponent(creds.cookies);\n\n const AUTH_PREFIX = 'Authorization: ';\n if (rawCookies.startsWith(AUTH_PREFIX)) {\n // Bearer token from OAuth (e.g., BTP service key auth) — pass as\n // Authorization header, not as a Cookie\n authorizationHeader = rawCookies.substring(AUTH_PREFIX.length);\n } else {\n cookieHeader = rawCookies;\n }\n } else {\n reportUnsupportedAuthAndExit(session.auth.method);\n }\n\n // Build plugin list: built-in plugins first, then user plugins\n const plugins: AdtAdapterConfig['plugins'] = [];\n\n // Add capture plugin if enabled (must be first to capture before other plugins)\n if (effectiveOptions.capture) {\n resetCaptured();\n plugins.push({\n name: 'capture',\n process: (context: ResponseContext) => {\n setCaptured({\n xml: context.rawText,\n json: context.parsedData,\n });\n return context.parsedData;\n },\n });\n }\n\n // Add file logging plugin if enabled\n if (effectiveOptions.logResponseFiles) {\n plugins.push(\n new FileLoggingPlugin({\n outputDir: effectiveOptions.logOutput,\n writeMetadata: effectiveOptions.writeMetadata,\n logger,\n }),\n );\n }\n\n // Add console logging plugin if enabled\n if (effectiveOptions.enableLogging) {\n plugins.push(\n new LoggingPlugin((msg, data) => {\n const dataSuffix = data ? ` ${JSON.stringify(data)}` : '';\n logger.info(`${msg}${dataSuffix}`);\n }),\n );\n }\n\n // Add user-provided plugins last\n plugins.push(...effectiveOptions.plugins);\n\n // Create onSessionExpired callback for automatic SAML re-authentication\n // Only applicable for cookie-based auth with a plugin that can refresh\n let onSessionExpired: (() => Promise<string>) | undefined;\n\n if (\n effectiveOptions.autoReauth &&\n session.auth.method === 'cookie' &&\n session.auth.plugin\n ) {\n // Capture current session for the callback closure\n let currentSession = session;\n let refreshAttempts = 0;\n const MAX_REFRESH_ATTEMPTS = 1;\n\n onSessionExpired = async (): Promise<string> => {\n refreshAttempts++;\n\n if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {\n const error = new Error(\n `Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded`,\n );\n console.error('❌ Auto-refresh failed: Too many attempts');\n const sidArg = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n throw error;\n }\n\n progress.step(\n `🔄 Session expired, refreshing credentials for ${currentSession.sid}... (attempt ${refreshAttempts}/${MAX_REFRESH_ATTEMPTS})`,\n );\n\n try {\n // Refresh credentials using the auth plugin (opens browser for SAML)\n const refreshedSession = await refreshCredentials(currentSession, {\n log: progress.persist,\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n currentSession = refreshedSession;\n\n // Extract new cookie from refreshed session\n const creds = currentSession.auth.credentials as CookieCredentials;\n const newCookie = decodeURIComponent(creds.cookies);\n\n progress.clear(); // Silent on success - don't clutter output\n // DON'T reset counter - if cookies don't work, we'll hit the limit\n return newCookie;\n } catch (error) {\n progress.done('❌ Auto-refresh failed');\n console.error(\n '❌ Auto-refresh failed:',\n error instanceof Error ? error.message : String(error),\n );\n const sidArg = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n throw error;\n }\n };\n }\n\n const adtClient = createAdtClient({\n baseUrl,\n username,\n password,\n cookieHeader,\n authorizationHeader,\n client,\n logger,\n plugins,\n onSessionExpired,\n headersTimeoutMs,\n });\n\n // Initialize ADK global context if not already done\n // This allows ADK objects to be used without passing context explicitly\n if (!isAdkInitialized()) {\n initializeAdk(adtClient, { lockStore: new FileLockStore() });\n }\n\n return adtClient;\n}\n\n// =============================================================================\n// getAdtClientV2Safe — safe variant that throws AdtAuthError instead of\n// exiting the process. Required by long-running callers (adt-mcp HTTP\n// transport, any daemon). Keep this behaviourally identical to\n// `getAdtClientV2`, differing only in error handling.\n// =============================================================================\n\n/**\n * Same contract as {@link getAdtClientV2}, but on any authentication /\n * credential failure throws a typed {@link AdtAuthError} instead of\n * writing to stderr and calling `process.exit(1)`.\n *\n * Use this from long-running processes (HTTP servers, MCP daemons) where\n * `process.exit` would tear down unrelated connections.\n *\n * @throws {AdtAuthError} when the session is missing, expired without a\n * refresh plugin, refresh fails, or the configured auth method is\n * unsupported.\n */\nexport async function getAdtClientV2Safe(\n options?: AdtClientV2Options,\n): Promise<AdtClient> {\n // Test DI hook — identical to getAdtClientV2\n const testOverride = __getActiveTestAdtClient();\n if (testOverride) {\n return testOverride;\n }\n\n // Validate the headers timeout up front so an invalid value fails before\n // any expired-session refresh or authentication work can send a request.\n const adtHeadersTimeout = resolveAdtHeadersTimeoutMs();\n\n const ctx = getCliContext();\n const effectiveOptions = {\n sid: options?.sid ?? ctx.sid,\n logger: options?.logger ?? ctx.logger,\n logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,\n logOutput: options?.logOutput ?? ctx.logOutput ?? './tmp/logs',\n enableLogging: options?.enableLogging,\n writeMetadata: options?.writeMetadata ?? false,\n capture: options?.capture ?? false,\n plugins: options?.plugins ?? [],\n autoReauth: options?.autoReauth ?? true,\n verbose: options?.verbose ?? ctx.verbose,\n };\n\n const logger =\n effectiveOptions.logger ??\n (effectiveOptions.enableLogging ? consoleLogger : silentLogger);\n\n let session = loadAuthSession(effectiveOptions.sid);\n\n if (!session) {\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n const sidFlag = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n throw new AdtAuthError(\n 'NO_SESSION',\n `Not authenticated${sidSuffix}. Run \"adt auth login${sidFlag}\" first.`,\n effectiveOptions.sid,\n );\n }\n\n setAdtSystem(session.sid);\n\n const baseUrl = session.host;\n const client = session.client;\n let username: string | undefined;\n let password: string | undefined;\n let cookieHeader: string | undefined;\n let authorizationHeader: string | undefined;\n\n if (session.auth.method === 'basic') {\n const creds = session.auth.credentials as BasicCredentials;\n username = creds.username;\n password = creds.password;\n } else if (session.auth.method === 'cookie') {\n if (isExpired(session)) {\n session = await tryAutoRefreshSafe(session, effectiveOptions.sid);\n }\n\n const creds = session.auth.credentials as CookieCredentials;\n const rawCookies = decodeURIComponent(creds.cookies);\n\n const AUTH_PREFIX = 'Authorization: ';\n if (rawCookies.startsWith(AUTH_PREFIX)) {\n authorizationHeader = rawCookies.substring(AUTH_PREFIX.length);\n } else {\n cookieHeader = rawCookies;\n }\n } else {\n throw new AdtAuthError(\n 'UNSUPPORTED_AUTH_METHOD',\n `Unsupported auth method: ${session.auth.method}`,\n effectiveOptions.sid,\n );\n }\n\n // Plugin list — identical to getAdtClientV2\n const plugins: AdtAdapterConfig['plugins'] = [];\n\n if (effectiveOptions.capture) {\n resetCaptured();\n plugins.push({\n name: 'capture',\n process: (context: ResponseContext) => {\n setCaptured({\n xml: context.rawText,\n json: context.parsedData,\n });\n return context.parsedData;\n },\n });\n }\n\n if (effectiveOptions.logResponseFiles) {\n plugins.push(\n new FileLoggingPlugin({\n outputDir: effectiveOptions.logOutput,\n writeMetadata: effectiveOptions.writeMetadata,\n logger,\n }),\n );\n }\n\n if (effectiveOptions.enableLogging) {\n plugins.push(\n new LoggingPlugin((msg, data) => {\n const dataSuffix = data ? ` ${JSON.stringify(data)}` : '';\n logger.info(`${msg}${dataSuffix}`);\n }),\n );\n }\n\n plugins.push(...effectiveOptions.plugins);\n\n // onSessionExpired callback — throws AdtAuthError, no console.error\n let onSessionExpired: (() => Promise<string>) | undefined;\n if (\n effectiveOptions.autoReauth &&\n session.auth.method === 'cookie' &&\n session.auth.plugin\n ) {\n let currentSession = session;\n let refreshAttempts = 0;\n const MAX_REFRESH_ATTEMPTS = 1;\n\n onSessionExpired = async (): Promise<string> => {\n refreshAttempts++;\n\n if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n throw new AdtAuthError(\n 'MAX_REFRESH_ATTEMPTS',\n `Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded${sidSuffix}.`,\n effectiveOptions.sid,\n );\n }\n\n try {\n const refreshedSession = await refreshCredentials(currentSession, {\n log: () => {\n /* silent — callers own logging */\n },\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n currentSession = refreshedSession;\n\n const creds = currentSession.auth.credentials as CookieCredentials;\n return decodeURIComponent(creds.cookies);\n } catch (error) {\n if (error instanceof AdtAuthError) throw error;\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n const errMsg = error instanceof Error ? error.message : String(error);\n throw new AdtAuthError(\n 'REFRESH_FAILED',\n `Auto-refresh failed${sidSuffix}: ${errMsg}`,\n effectiveOptions.sid,\n );\n }\n };\n }\n\n const adtClient = createAdtClient({\n baseUrl,\n username,\n password,\n cookieHeader,\n authorizationHeader,\n client,\n logger,\n plugins,\n onSessionExpired,\n headersTimeoutMs: adtHeadersTimeout,\n });\n\n if (!isAdkInitialized()) {\n initializeAdk(adtClient, { lockStore: new FileLockStore() });\n }\n\n return adtClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,MAAM,UAAU;AAChB,MAAM,aAAa;AAkCnB,SAAS,kBAAkB,IAA+B;CACxD,OAAO;EACL,KAAK,IAAI,OAAO;GACd,OAAO,IAAI,eAAe,IAAI,KAAK,KAAK;EAC1C;EACA,KAAK,IAAI,OAAO;GACd,OAAO,KAAK,KAAK,IAAI,KAAK,CAAC,CAAC,YAAY,MAAM;EAChD;EACA,MAAM,QAAQ,OAAO;GAEnB,OADa,OAAO,uBAAuB,IAAI,KACpC,CAAC,CAAC,KAAK,CAAC,KAA2B;EAChD;EACA,SAAS,QAAQ,OAAO;GACtB,MAAM,OAAO,OAAO,uBAAuB,IAAI,KAAK;GACpD,MAAM,SAAuB,CAAC;GAC9B,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;IACpC,MAAM,OAAO,KAAK,KAAK,CAAC;IACxB,IAAI,MAAM,OAAO,KAAK,IAAI;GAC5B;GACA,OAAO;EACT;CACF;AACF;AAEA,MAAM,OAAO,kBAAkB,OAAO;AACtC,MAAM,UAAU,kBAAkB,UAAU;AAE5C,SAAS,SAAS,MAAkB,OAAuB;CACzD,OAAO,QAAQ,KAAK,MAAM,KAAK,KAAK,KAAK,aAAa,KAAK,KAAK;AAClE;AA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,KAAK,QACb;EACA,IAAI,iBAAiB;EACrB,IAAI,kBAAkB;EACtB,MAAM,uBAAuB;EAE7B,mBAAmB,YAA6B;GAC9C;GAEA,IAAI,kBAAkB,sBAAsB;IAC1C,MAAM,YAAY,iBAAiB,MAC/B,YAAY,iBAAiB,QAC7B;IACJ,MAAM,IAAI,aACR,wBACA,6BAA6B,qBAAqB,YAAY,UAAU,IACxE,iBAAiB,GACnB;GACF;GAEA,IAAI;IACF,MAAM,mBAAmB,MAAM,mBAAmB,gBAAgB,EAChE,WAAW,CAEX,EACF,CAAC;IACD,IAAI,CAAC,kBACH,MAAM,IAAI,MAAM,uBAAuB;IAEzC,iBAAiB;IAEjB,MAAM,QAAQ,eAAe,KAAK;IAClC,OAAO,mBAAmB,MAAM,OAAO;GACzC,SAAS,OAAO;IACd,IAAI,iBAAiB,cAAc,MAAM;IACzC,MAAM,YAAY,iBAAiB,MAC/B,YAAY,iBAAiB,QAC7B;IACJ,MAAM,SAAS,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IACpE,MAAM,IAAI,aACR,kBACA,sBAAsB,UAAU,IAAI,UACpC,iBAAiB,GACnB;GACF;EACF;CACF;CAEA,MAAM,YAAY,gBAAgB;EAChC;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA,kBAAkB;CACpB,CAAC;CAED,IAAI,CAAC,iBAAiB,GACpB,cAAc,WAAW,EAAE,WAAW,IAAI,cAAc,EAAE,CAAC;CAG7D,OAAO;AACT"}
1
+ {"version":3,"file":"index.mjs","names":["nativeGlob","DEFAULT_OPERATIONS"],"sources":["../src/services/badi/index.ts","../src/services/changeset/service.ts","../src/utils/format-loader.ts","../src/services/checkin/filetree.ts","../src/services/checkin/diff.ts","../src/services/checkin/plan.ts","../src/services/checkin/apply.ts","../src/services/checkin/service.ts","../src/services/connection/service.ts","../src/services/cts/transport-lifecycle.ts","../src/services/cts/transport-metadata.ts","../src/shared/adt-client.ts","../src/utils/destinations.ts","../src/utils/transport-numbers.ts","../src/services/import/object-selection.ts","../src/services/import/service.ts","../src/utils/lock-helpers.ts","../src/services/source/service.ts","../src/services/source-history/service.ts","../src/services/check/service.ts","../src/utils/auth.ts","../src/utils/progress-reporter.ts","../src/ui/components/link.ts","../src/utils/adt-http-options.ts","../src/utils/adt-client-v2.ts"],"sourcesContent":["/**\n * BAdI services — ENHO metadata (enhoxhb) and unified read (classic vit/wb + ENHO).\n *\n * - `getBadiInfo` / `parseEnhancementImplementation` — ENHO/XHB metadata from\n * `/sap/bc/adt/enhancements/enhoxhb/{name}` (used by `adt badi <name>`).\n * - `BadiService` — auto-detect kind and read classic SXSD/SXCI or ENHO/XHH.\n */\nimport type { AdtClient } from '@abapify/adt-client';\n\nimport type { BasicObjectPropertiesResponse } from '@abapify/adt-contracts';\nimport { DOMParser } from '@xmldom/xmldom';\n\nconst NS_ENHO = 'http://www.sap.com/adt/enhancements/enho';\nconst NS_ADTCORE = 'http://www.sap.com/adt/core';\n\ntype XmlElement = import('@xmldom/xmldom').Element;\n\nexport interface BadiImplementation {\n name: string;\n shortText: string;\n active: boolean;\n default: boolean;\n example: boolean;\n implementingClass: string;\n badiDefinition: string;\n enhancementSpot: string;\n}\n\nexport interface BadiInfo {\n name: string;\n description: string;\n type: string;\n package: string;\n responsible: string;\n version: string;\n technology: string;\n switchSupported: boolean;\n badiImplementations: BadiImplementation[];\n}\n\ninterface NamespaceAccessor {\n attr(el: XmlElement | null | undefined, local: string): string;\n bool(el: XmlElement | null | undefined, local: string): boolean;\n child(parent: XmlElement, local: string): XmlElement | null;\n children(parent: XmlElement, local: string): XmlElement[];\n}\n\nfunction namespaceAccessor(ns: string): NamespaceAccessor {\n return {\n attr(el, local) {\n return el?.getAttributeNS(ns, local) ?? '';\n },\n bool(el, local) {\n return this.attr(el, local).toLowerCase() === 'true';\n },\n child(parent, local) {\n const list = parent.getElementsByTagNameNS(ns, local);\n return (list.item(0) as XmlElement | null) ?? null;\n },\n children(parent, local) {\n const list = parent.getElementsByTagNameNS(ns, local);\n const result: XmlElement[] = [];\n for (let i = 0; i < list.length; i++) {\n const node = list.item(i) as XmlElement | null;\n if (node) result.push(node);\n }\n return result;\n },\n };\n}\n\nconst enho = namespaceAccessor(NS_ENHO);\nconst adtcore = namespaceAccessor(NS_ADTCORE);\n\nfunction rootAttr(root: XmlElement, local: string): string {\n return adtcore.attr(root, local) || root.getAttribute(local) || '';\n}\n\nfunction parseBadiImplementation(node: XmlElement): BadiImplementation {\n return {\n name: enho.attr(node, 'name'),\n shortText: enho.attr(node, 'shortText'),\n active: enho.bool(node, 'active'),\n default: enho.bool(node, 'default'),\n example: enho.bool(node, 'example'),\n implementingClass: adtcore.attr(\n enho.child(node, 'implementingClass'),\n 'name',\n ),\n badiDefinition: adtcore.attr(enho.child(node, 'badiDefinition'), 'name'),\n enhancementSpot: adtcore.attr(enho.child(node, 'enhancementSpot'), 'name'),\n };\n}\n\nfunction parseBadiInfo(root: XmlElement): BadiInfo {\n const contentCommon = enho.child(root, 'contentCommon');\n\n return {\n name: rootAttr(root, 'name'),\n description: rootAttr(root, 'description'),\n type: rootAttr(root, 'type'),\n package: adtcore.attr(adtcore.child(root, 'packageRef'), 'name'),\n responsible: rootAttr(root, 'responsible'),\n version: rootAttr(root, 'version'),\n technology: enho.attr(contentCommon, 'toolType'),\n switchSupported: enho.bool(contentCommon, 'switchSupported'),\n badiImplementations: enho\n .children(root, 'badiImplementation')\n .map(parseBadiImplementation),\n };\n}\n\n/**\n * Parse an `enho:objectData` XML document into a `BadiInfo` structure.\n */\nexport function parseEnhancementImplementation(xml: string): BadiInfo {\n const doc = new DOMParser({\n onError: () => {\n /* swallow parse warnings; caller handles malformed XML via errors */\n },\n }).parseFromString(xml, 'text/xml');\n\n const root = doc.documentElement;\n if (!root) {\n throw new Error('Empty or malformed ENHO XML response');\n }\n\n return parseBadiInfo(root as XmlElement);\n}\n\n/**\n * Fetch ENHO metadata for a BAdI / enhancement implementation and parse\n * the BAdI implementation list.\n */\nexport async function getBadiInfo({\n client,\n name,\n}: {\n client: AdtClient;\n name: string;\n}): Promise<BadiInfo> {\n const response = await client.fetch(\n `/sap/bc/adt/enhancements/enhoxhb/${encodeURIComponent(name.toLowerCase())}`,\n {\n headers: { Accept: 'application/vnd.sap.adt.enh.enhoxhb.v4+xml' },\n },\n );\n\n if (typeof response !== 'string') {\n throw new Error('Unexpected non-XML response from ENHO endpoint');\n }\n\n return parseEnhancementImplementation(response);\n}\n\nexport type BadiKind = 'definition' | 'implementation' | 'enhancement';\n\nexport type BadiMetadata = {\n name: string;\n type: string;\n kind: BadiKind;\n description?: string;\n language?: string;\n version?: string;\n packageName?: string;\n packageUri?: string;\n responsible?: string;\n masterLanguage?: string;\n masterSystem?: string;\n /** When SAP supplies a container reference, it can be used to validate lineage. */\n containerRef?: { name?: string; type?: string };\n};\n\nexport type BadiReadResult = BadiMetadata & {\n /** ENHO/XHB metadata when kind is enhancement. */\n enhancement?: BadiInfo;\n source?: string;\n /** Present when `--implementations` is used on a classic definition. */\n implementations?: BadiMetadata[];\n};\n\n/** @deprecated Use BadiMetadata */\nexport type ClassicBadiMetadata = Omit<BadiMetadata, 'kind'>;\n\nconst BADI_REPOSITORY_TYPES = new Set(['SXSD/XD', 'SXCI/XI', 'ENHO/XHH']);\n\nfunction isNotFound(error: unknown): boolean {\n return (\n typeof error === 'object' &&\n error !== null &&\n (error as { status?: unknown }).status === 404\n );\n}\n\nfunction badiKindFromType(adtType: string): BadiKind {\n const type = adtType.toUpperCase();\n if (type === 'SXSD/XD') return 'definition';\n if (type === 'SXCI/XI') return 'implementation';\n return 'enhancement';\n}\n\nfunction extractSearchObjects(results: unknown): Array<{\n name?: string;\n type?: string;\n}> {\n const record = results as Record<string, unknown>;\n let raw:\n | Array<{ name?: string; type?: string }>\n | { name?: string; type?: string }\n | undefined;\n\n if (record.objectReferences && typeof record.objectReferences === 'object') {\n const refs = record.objectReferences as {\n objectReference?: typeof raw;\n };\n raw = refs.objectReference;\n } else if (record.objectReference) {\n raw = record.objectReference as typeof raw;\n } else if (record.mainObject && typeof record.mainObject === 'object') {\n const main = record.mainObject as { objectReference?: typeof raw };\n raw = main.objectReference;\n }\n\n if (!raw) return [];\n return Array.isArray(raw) ? raw : [raw];\n}\n\nexport function normalizeClassicBadiMetadata({\n response,\n kind,\n}: {\n response: BasicObjectPropertiesResponse;\n kind: 'definition' | 'implementation';\n}): BadiMetadata {\n if (!('mainObject' in response) || !response.mainObject) {\n throw new Error('BAdI response missing mainObject');\n }\n const main = response.mainObject;\n return {\n kind,\n name: (main.name ?? '').toUpperCase(),\n type: main.type ?? '',\n description: main.description,\n language: main.language,\n version: main.version,\n packageName: main.packageRef?.name,\n packageUri: main.packageRef?.uri,\n responsible: main.responsible,\n masterLanguage: main.masterLanguage,\n masterSystem: main.masterSystem,\n containerRef: main.containerRef\n ? { name: main.containerRef.name, type: main.containerRef.type }\n : undefined,\n };\n}\n\nfunction searchQueriesForDefinition({ name }: { name: string }): string[] {\n const normalized = name.trim().toUpperCase();\n const queries = new Set<string>([\n `*${normalized}*`,\n `*${normalized.replace(/_/g, '*')}*`,\n ]);\n const parts = normalized.split('_').filter(Boolean);\n if (parts.length >= 2) {\n const tail2 = parts.slice(-2).join('_');\n if (tail2.length >= 10) {\n queries.add(`*${tail2}*`);\n }\n }\n return [...queries];\n}\n\ninterface ServiceContext {\n readonly client: AdtClient;\n readonly normalized: string;\n}\n\ninterface ReadContext extends ServiceContext {\n readonly options?: {\n includeSource?: boolean;\n includeImplementations?: boolean;\n };\n}\n\nasync function resolveBySearch(\n ctx: ServiceContext,\n): Promise<BadiKind | undefined> {\n const search =\n await ctx.client.adt.repository.informationsystem.search.quickSearch({\n query: ctx.normalized,\n maxResults: 20,\n });\n const matches = extractSearchObjects(search).filter(\n (obj) =>\n obj.name?.toUpperCase() === ctx.normalized &&\n obj.type &&\n BADI_REPOSITORY_TYPES.has(obj.type.toUpperCase()),\n );\n if (matches.length === 1) {\n return badiKindFromType(matches[0].type!);\n }\n if (matches.length > 1) {\n throw new Error(\n `Ambiguous BAdI name ${ctx.normalized}: ${matches.map((m) => m.type).join(', ')}`,\n );\n }\n return undefined;\n}\n\nasync function runProbe(\n ctx: ServiceContext & { kind: BadiKind; expectedType: string },\n): Promise<BadiKind | undefined> {\n const response =\n ctx.kind === 'definition'\n ? await ctx.client.adt.vit.wb.objectProperties.getDefinition(\n ctx.normalized,\n )\n : await ctx.client.adt.vit.wb.objectProperties.getImplementation(\n ctx.normalized,\n );\n if (!('mainObject' in response) || !response.mainObject) {\n return undefined;\n }\n const main = response.mainObject;\n if (\n main.type?.toUpperCase() === ctx.expectedType &&\n main.name?.toUpperCase() === ctx.normalized\n ) {\n return ctx.kind;\n }\n return undefined;\n}\n\nasync function resolveEnhancement(\n ctx: ServiceContext,\n): Promise<BadiKind | undefined> {\n try {\n await getBadiInfo({ client: ctx.client, name: ctx.normalized });\n return 'enhancement';\n } catch (error) {\n if (!isNotFound(error)) throw error;\n return undefined;\n }\n}\n\nasync function resolveKind(ctx: ServiceContext): Promise<BadiKind> {\n const bySearch = await resolveBySearch(ctx);\n if (bySearch) return bySearch;\n\n const definition = await runProbe({\n ...ctx,\n kind: 'definition',\n expectedType: 'SXSD/XD',\n });\n if (definition) return definition;\n\n const implementation = await runProbe({\n ...ctx,\n kind: 'implementation',\n expectedType: 'SXCI/XI',\n });\n if (implementation) return implementation;\n\n const enhancement = await resolveEnhancement(ctx);\n if (enhancement) return enhancement;\n\n throw new Error(`BAdI object not found: ${ctx.normalized}`);\n}\n\nasync function readDefinition(ctx: ServiceContext): Promise<BadiMetadata> {\n const response = await ctx.client.adt.vit.wb.objectProperties.getDefinition(\n ctx.normalized,\n );\n return normalizeClassicBadiMetadata({ response, kind: 'definition' });\n}\n\nasync function readImplementation(ctx: ServiceContext): Promise<BadiMetadata> {\n const response =\n await ctx.client.adt.vit.wb.objectProperties.getImplementation(\n ctx.normalized,\n );\n return normalizeClassicBadiMetadata({ response, kind: 'implementation' });\n}\n\nasync function readEnhancement(ctx: ReadContext): Promise<BadiReadResult> {\n const lower = ctx.normalized.toLowerCase();\n const info = await getBadiInfo({ client: ctx.client, name: ctx.normalized });\n const source = ctx.options?.includeSource\n ? String(await ctx.client.adt.enhancements.enhoxhh.source.main.get(lower))\n : undefined;\n return {\n kind: 'enhancement',\n name: info.name.toUpperCase(),\n type: info.type,\n description: info.description,\n version: info.version,\n packageName: info.package,\n responsible: info.responsible,\n enhancement: info,\n source,\n };\n}\n\nasync function getBadi(ctx: ReadContext): Promise<BadiReadResult> {\n const kind = await resolveKind(ctx);\n switch (kind) {\n case 'definition': {\n const definition = await readDefinition(ctx);\n if (!ctx.options?.includeImplementations) {\n return definition;\n }\n const implementations = await listImplementations(ctx);\n return { ...definition, implementations };\n }\n case 'implementation':\n return readImplementation(ctx);\n case 'enhancement':\n return readEnhancement(ctx);\n default:\n throw new Error(`Unsupported BAdI kind: ${kind satisfies never}`);\n }\n}\n\ninterface SearchCandidateContext extends ServiceContext {\n readonly query: string;\n readonly objectType?: 'SXCI';\n readonly seen: Set<string>;\n}\n\nfunction candidateNames(ctx: {\n search: unknown;\n normalized: string;\n seen: Set<string>;\n}): string[] {\n const names: string[] = [];\n for (const obj of extractSearchObjects(ctx.search)) {\n if (obj.type?.toUpperCase() !== 'SXCI/XI') continue;\n const implName = obj.name?.toUpperCase();\n if (!implName) continue;\n if (implName === ctx.normalized) continue;\n if (ctx.seen.has(implName)) continue;\n ctx.seen.add(implName);\n names.push(implName);\n }\n return names;\n}\n\nasync function tryReadImplementation(ctx: {\n client: AdtClient;\n definitionName: string;\n implName: string;\n}): Promise<BadiMetadata | undefined> {\n try {\n const impl = await readImplementation({\n client: ctx.client,\n normalized: ctx.implName,\n });\n const containerName = impl.containerRef?.name?.toUpperCase();\n if (containerName && containerName !== ctx.definitionName) {\n return undefined;\n }\n return impl;\n } catch (error) {\n if (!isNotFound(error)) throw error;\n return undefined;\n }\n}\n\nasync function collectSearchCandidates(\n ctx: SearchCandidateContext,\n): Promise<BadiMetadata[]> {\n const params: { query: string; maxResults: number; objectType?: 'SXCI' } = {\n query: ctx.query,\n maxResults: 100,\n };\n if (ctx.objectType) {\n params.objectType = ctx.objectType;\n }\n const search =\n await ctx.client.adt.repository.informationsystem.search.quickSearch(\n params,\n );\n\n const names = candidateNames({\n search,\n normalized: ctx.normalized,\n seen: ctx.seen,\n });\n const found: BadiMetadata[] = [];\n for (const implName of names) {\n const impl = await tryReadImplementation({\n client: ctx.client,\n definitionName: ctx.normalized,\n implName,\n });\n if (impl) found.push(impl);\n }\n return found;\n}\n\nasync function listImplementations(\n ctx: ServiceContext,\n): Promise<BadiMetadata[]> {\n await readDefinition(ctx);\n\n const queries = searchQueriesForDefinition({ name: ctx.normalized });\n const seen = new Set<string>();\n const all: BadiMetadata[] = [];\n\n for (const query of queries) {\n all.push(\n ...(await collectSearchCandidates({\n client: ctx.client,\n normalized: ctx.normalized,\n query,\n seen,\n })),\n );\n all.push(\n ...(await collectSearchCandidates({\n client: ctx.client,\n normalized: ctx.normalized,\n query,\n objectType: 'SXCI',\n seen,\n })),\n );\n }\n\n return all.sort((a, b) => a.name.localeCompare(b.name));\n}\n\nexport class BadiService {\n constructor(private readonly client: AdtClient) {}\n\n private contextFor(name: string): ServiceContext {\n return { client: this.client, normalized: name.trim().toUpperCase() };\n }\n\n private readContextFor(\n name: string,\n options?: { includeSource?: boolean; includeImplementations?: boolean },\n ): ReadContext {\n return { ...this.contextFor(name), options };\n }\n\n async resolveKind({ name }: { name: string }): Promise<BadiKind> {\n return resolveKind(this.contextFor(name));\n }\n\n async get({\n name,\n options,\n }: {\n name: string;\n options?: { includeSource?: boolean; includeImplementations?: boolean };\n }): Promise<BadiReadResult> {\n return getBadi(this.readContextFor(name, options));\n }\n\n async getDefinition({ name }: { name: string }): Promise<BadiMetadata> {\n return readDefinition(this.contextFor(name));\n }\n\n async getImplementation({ name }: { name: string }): Promise<BadiMetadata> {\n return readImplementation(this.contextFor(name));\n }\n\n /**\n * List classic BAdI implementations (SXCI/XI) for a definition name.\n * Uses repository quick search heuristics — authoritative active/inactive\n * state requires SXC_ATTR (not exposed on all systems).\n */\n async listImplementations({\n name,\n }: {\n name: string;\n }): Promise<BadiMetadata[]> {\n return listImplementations(this.contextFor(name));\n }\n}\n\n/** @deprecated Use BadiService */\nexport const ClassicBadiService = BadiService;\n","/**\n * `ChangesetService` — transport-agnostic transactional unit-of-work.\n *\n * Wave 3 of the MCP HTTP transport introduces changesets so that an AI\n * agent can lock + stage several source writes, review them, and then\n * atomically commit (batch activate) or roll back (release locks).\n *\n * Architectural contract:\n *\n * - This service is **pure business logic**: no `console.*`, no\n * commander, no file I/O. Callers feed it an `AdtClient` and a\n * `Logger` and receive structured results / thrown errors.\n * - Both the CLI (`adt changeset …`) and MCP tools\n * (`changeset_begin` / `changeset_add` / `changeset_commit` /\n * `changeset_rollback`) delegate straight through. That is the only\n * way to keep CLI ↔ MCP parity honest.\n * - Locks are acquired and released through `@abapify/adt-locks` —\n * the single lock service in this monorepo. We never hand-roll lock\n * protocol here (nor in the MCP tools).\n *\n * Commit strategy:\n *\n * SAP ADT supports batch activation via a single POST to\n * `/sap/bc/adt/activation` with an `adtcore:objectReferences` body\n * carrying N references. We use the typed `activation.activate.post`\n * contract from `@abapify/adt-client` for this — NOT a manual XML\n * string. One HTTP round-trip, all entries activated together.\n *\n * If activation fails with an error, `commit` still tries to release\n * every lock (best-effort) and surfaces both the activation error and\n * the per-entry release outcomes in the result.\n *\n * Rollback semantics (explicit):\n *\n * Rollback releases locks but does NOT revert the PUTs that `add`\n * already persisted on SAP. SAP has no transactional \"discard\" API\n * over ADT: the inactive version stays on the system until the next\n * edit/activate cycle. This matches Eclipse ADT's behaviour when a\n * developer closes the editor without activating.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport {\n createLockService,\n resolveLockCorrelation,\n type LockService,\n} from '@abapify/adt-locks';\nimport type { AdtClient } from '@abapify/adt-client';\nimport type { Logger } from '@abapify/adt-client';\nimport type { InferTypedSchema } from '@abapify/adt-schemas';\nimport { adtcore } from '@abapify/adt-schemas';\n\nexport type ChangesetStatus =\n 'open' | 'committing' | 'committed' | 'rolled_back';\n\nexport interface ChangesetEntry {\n objectUri: string;\n objectType: string;\n objectName: string;\n lockHandle: string;\n action: 'update' | 'create';\n createdAt: number;\n}\n\nexport interface Changeset {\n id: string;\n openedAt: number;\n status: ChangesetStatus;\n entries: ChangesetEntry[];\n description?: string;\n}\n\nexport interface AddEntryArgs {\n objectUri: string;\n objectType: string;\n objectName: string;\n source: string;\n transport?: string;\n}\n\nexport interface CommitResult {\n activated: string[];\n failed: { uri: string; error: string }[];\n}\n\nexport interface RollbackResult {\n released: string[];\n failed: { uri: string; error: string }[];\n}\n\ntype ObjectReferencesBody = Extract<\n InferTypedSchema<typeof adtcore>,\n { objectReferences: unknown }\n>;\n\n/** Create a brand-new empty changeset (no SAP interaction yet). */\nexport function createChangeset(description?: string): Changeset {\n return {\n id: randomUUID(),\n openedAt: Date.now(),\n status: 'open',\n entries: [],\n description,\n };\n}\n\nexport class ChangesetService {\n private readonly locks: LockService;\n\n constructor(\n private readonly client: AdtClient,\n private readonly logger?: Logger,\n ) {\n this.locks = createLockService(client);\n }\n\n /** Transport-agnostic: returns a fresh Changeset descriptor. */\n begin(description?: string): Changeset {\n const cs = createChangeset(description);\n this.logger?.debug('changeset: begin', { id: cs.id });\n return cs;\n }\n\n /**\n * Lock the object, PUT the source, and register the entry. Throws on\n * lock or PUT failure; lock is released in the error path so the\n * caller never sees a half-applied entry.\n */\n async add(changeset: Changeset, args: AddEntryArgs): Promise<ChangesetEntry> {\n if (changeset.status !== 'open') {\n throw new Error(\n `changeset ${changeset.id} is not open (status=${changeset.status})`,\n );\n }\n\n const lock = await this.locks.lock(args.objectUri, {\n transport: args.transport,\n objectName: args.objectName,\n objectType: args.objectType,\n });\n const effectiveTransport = resolveLockCorrelation(lock, args.transport);\n\n try {\n const params = new URLSearchParams();\n params.set('lockHandle', lock.handle);\n if (effectiveTransport) params.set('corrNr', effectiveTransport);\n await this.client.fetch(\n `${args.objectUri}/source/main?${params.toString()}`,\n {\n method: 'PUT',\n headers: { 'Content-Type': 'text/plain' },\n body: args.source,\n },\n );\n } catch (err) {\n // Best-effort unlock on PUT failure so we don't leak a lock.\n try {\n await this.locks.unlock(args.objectUri, { lockHandle: lock.handle });\n } catch (unlockErr) {\n this.logger?.warn('changeset: failed to unlock after PUT failure', {\n objectUri: args.objectUri,\n error:\n unlockErr instanceof Error ? unlockErr.message : String(unlockErr),\n });\n }\n throw err;\n }\n\n const entry: ChangesetEntry = {\n objectUri: args.objectUri,\n objectType: args.objectType.toUpperCase(),\n objectName: args.objectName.toUpperCase(),\n lockHandle: lock.handle,\n action: 'update',\n createdAt: Date.now(),\n };\n changeset.entries.push(entry);\n this.logger?.debug('changeset: add', {\n id: changeset.id,\n objectUri: args.objectUri,\n });\n return entry;\n }\n\n /**\n * Batch-activate every entry, then release every lock. The changeset\n * is mutated in place: `status` advances to `committing` during the\n * call and `committed` on success. On activation failure it is left\n * as `committing` and the error is rethrown after lock cleanup.\n */\n async commit(changeset: Changeset): Promise<CommitResult> {\n if (changeset.status !== 'open') {\n throw new Error(\n `changeset ${changeset.id} is not open (status=${changeset.status})`,\n );\n }\n\n changeset.status = 'committing';\n\n if (changeset.entries.length === 0) {\n changeset.status = 'committed';\n return { activated: [], failed: [] };\n }\n\n const body: ObjectReferencesBody = {\n objectReferences: {\n objectReference: changeset.entries.map((e) => ({\n uri: e.objectUri,\n type: e.objectType,\n name: e.objectName,\n })),\n },\n };\n\n const result: CommitResult = { activated: [], failed: [] };\n let activationError: Error | undefined;\n\n try {\n await this.client.adt.activation.activate.post(\n { method: 'activate', preauditRequested: true },\n body,\n );\n result.activated = changeset.entries.map((e) => e.objectUri);\n } catch (err) {\n activationError = err instanceof Error ? err : new Error(String(err));\n result.failed = changeset.entries.map((e) => ({\n uri: e.objectUri,\n error: activationError!.message,\n }));\n }\n\n // Release locks regardless of activation outcome — a half-activated\n // changeset still has to free SAP-side locks.\n for (const entry of changeset.entries) {\n try {\n await this.locks.unlock(entry.objectUri, {\n lockHandle: entry.lockHandle,\n });\n } catch (err) {\n this.logger?.warn('changeset: unlock failed during commit', {\n id: changeset.id,\n objectUri: entry.objectUri,\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n if (activationError) {\n // Caller decides how to surface — the service keeps state at\n // `committing` so a later recovery path can try again if SAP is\n // reachable. The MCP/CLI layer will turn this into a user-visible\n // error and clear the session pointer.\n throw activationError;\n }\n\n changeset.status = 'committed';\n this.logger?.debug('changeset: commit', {\n id: changeset.id,\n activated: result.activated.length,\n });\n return result;\n }\n\n /**\n * Release every lock (best-effort) and mark the changeset\n * `rolled_back`. Does NOT revert PUT'ed source — see file-level\n * comment for rationale.\n */\n async rollback(changeset: Changeset): Promise<RollbackResult> {\n if (changeset.status === 'committed') {\n throw new Error(`changeset ${changeset.id} is already committed`);\n }\n if (changeset.status === 'rolled_back') {\n return { released: [], failed: [] };\n }\n\n const result: RollbackResult = { released: [], failed: [] };\n for (const entry of changeset.entries) {\n try {\n await this.locks.unlock(entry.objectUri, {\n lockHandle: entry.lockHandle,\n });\n result.released.push(entry.objectUri);\n } catch (err) {\n const message = err instanceof Error ? err.message : String(err);\n this.logger?.warn('changeset: unlock failed during rollback', {\n id: changeset.id,\n objectUri: entry.objectUri,\n error: message,\n });\n result.failed.push({ uri: entry.objectUri, error: message });\n }\n }\n\n changeset.status = 'rolled_back';\n this.logger?.debug('changeset: rollback', {\n id: changeset.id,\n released: result.released.length,\n failed: result.failed.length,\n });\n return result;\n }\n}\n","/**\n * Format-plugin loader for CLI commands.\n *\n * Format plugins self-register into the global `FormatPlugin` registry when\n * their package is imported. This loader translates the CLI's legacy format\n * spec (`abapgit` / `ag` / `@abapify/adt-plugin-abapgit` / `pkg/preset`) into\n * a live `AdtPlugin` (the higher-level import/export plugin) so existing\n * import services keep working.\n *\n * Built-in format id → package mappings. New built-in formats just need one\n * extra entry here (plus the side-effect import in `cli.ts`).\n */\nimport { getFormatPlugin, type AdtPlugin } from '@abapify/adt-plugin';\n\nconst FORMAT_SHORTCUTS: Record<string, string> = {\n abapgit: '@abapify/adt-plugin-abapgit',\n ag: '@abapify/adt-plugin-abapgit',\n // AFF / gCTS format plugin (E06). `aff` is the primary id; `gcts` is an\n // alias — both share the same on-disk layout (SAP/abap-file-formats).\n aff: '@abapify/adt-plugin-gcts',\n gcts: '@abapify/adt-plugin-gcts',\n};\n\n/** Resolve a CLI format id to its registered package name (if known). */\nfunction resolvePackageForFormatId(id: string): string | undefined {\n return FORMAT_SHORTCUTS[id];\n}\n\n/**\n * Parse format specification with optional preset.\n *\n * Examples:\n * @abapify/adt-plugin-abapgit → { package: '@abapify/adt-plugin-abapgit' }\n * @abapify/adt-plugin-abapgit/full → { package: '@abapify/adt-plugin-abapgit', preset: 'full' }\n * abapgit → { package: '@abapify/adt-plugin-abapgit' } (shortcut)\n * ag → { package: '@abapify/adt-plugin-abapgit' } (shortcut)\n */\nexport function parseFormatSpec(formatSpec: string): {\n package: string;\n preset?: string;\n} {\n if (formatSpec in FORMAT_SHORTCUTS) {\n return { package: FORMAT_SHORTCUTS[formatSpec] };\n }\n\n const parts = formatSpec.split('/');\n if (parts.length === 2) {\n // @abapify/adt-plugin-abapgit\n return { package: formatSpec };\n } else if (parts.length === 3) {\n // @abapify/adt-plugin-abapgit/full\n const package_ = `${parts[0]}/${parts[1]}`;\n const preset = parts[2];\n return { package: package_, preset };\n } else {\n throw new Error(`Invalid format specification: ${formatSpec}`);\n }\n}\n\n/**\n * Load a format plugin by CLI spec.\n *\n * Resolution order:\n * 1. Look up the format id in the {@link FormatPlugin} registry. If it is\n * already registered (e.g. via CLI bootstrap), use it without any dynamic\n * import.\n * 2. Otherwise dynamically `import(packageName)` — this triggers the\n * package's self-registration side-effects — then return the resolved\n * legacy `AdtPlugin` instance from the package's default/named export.\n */\nexport async function loadFormatPlugin(formatSpec: string): Promise<{\n name: string;\n description: string;\n instance: AdtPlugin;\n preset?: string;\n}> {\n const { package: packageName, preset } = parseFormatSpec(formatSpec);\n\n // Fast path: if the format plugin has already self-registered (typical when\n // the CLI bootstrap has side-effect-imported the package), we're done — but\n // we still need the legacy AdtPlugin instance for the import services, so\n // fall through to the dynamic import. The registry lookup merely validates\n // that the requested format is available.\n const builtinId = Object.entries(FORMAT_SHORTCUTS).find(\n ([, pkg]) => pkg === packageName,\n )?.[0];\n if (builtinId && !getFormatPlugin(builtinId)) {\n // Registry is empty for this id — the dynamic import below will populate\n // it via the package's self-registration side-effect.\n }\n\n try {\n const pluginModule = await import(packageName);\n const PluginClass =\n pluginModule.default || pluginModule[Object.keys(pluginModule)[0]];\n\n if (!PluginClass) {\n throw new Error(`No plugin class found in ${packageName}`);\n }\n\n const options = preset ? { preset } : {};\n\n const plugin: AdtPlugin =\n typeof PluginClass === 'function' && PluginClass.prototype\n ? new PluginClass(options)\n : PluginClass;\n\n return {\n name: plugin.name || packageName,\n description: plugin.description || `Plugin from ${packageName}`,\n instance: plugin,\n preset,\n };\n } catch (error: unknown) {\n const err = error as Error;\n if (\n (err as { code?: string }).code === 'MODULE_NOT_FOUND' ||\n err.message?.includes(`Cannot find module '${packageName}'`)\n ) {\n throw new Error(\n `Plugin package '${packageName}' not found. Install it with: bun add ${packageName}`,\n { cause: error },\n );\n }\n throw error;\n }\n}\n\nexport { resolvePackageForFormatId };\n","/**\n * FileTree implementation used by the CheckinService.\n *\n * Mirrors the `FsFileTree` in `@abapify/adt-export` but kept local so the\n * checkin feature doesn't drag an export-time dependency back into\n * `adt-cli` (which would violate the module-boundary rules between\n * adt-cli and plugin-like packages).\n */\nimport {\n readFile,\n readdir,\n access,\n glob as nativeGlob,\n} from 'node:fs/promises';\nimport { join } from 'node:path';\nimport type { FileTree } from '@abapify/adt-plugin';\n\nclass FsFileTree implements FileTree {\n constructor(public readonly root: string) {}\n\n async glob(pattern: string): Promise<string[]> {\n const results: string[] = [];\n for await (const path of nativeGlob(pattern, { cwd: this.root })) {\n results.push(path);\n }\n return results;\n }\n\n async read(path: string): Promise<string> {\n const content = await readFile(join(this.root, path), 'utf-8');\n return content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;\n }\n\n async readBuffer(path: string): Promise<Buffer> {\n return readFile(join(this.root, path));\n }\n\n async exists(path: string): Promise<boolean> {\n try {\n await access(join(this.root, path));\n return true;\n } catch {\n return false;\n }\n }\n\n async readdir(path: string): Promise<string[]> {\n return readdir(path ? join(this.root, path) : this.root);\n }\n}\n\nexport function createFsFileTree(root: string): FileTree {\n return new FsFileTree(root);\n}\n","/**\n * ChangePlan — intermediate representation between discovery and apply.\n *\n * Every ChangePlanEntry represents one ADK object about to be pushed into\n * SAP. The diff stage decides `action` by calling `obj.load()` against the\n * remote system:\n *\n * - `create` — remote load threw 404 / not-found.\n * - `update` — remote exists; local differs (or was deserialised with\n * pending sources, which we conservatively treat as\n * \"changed\" because a per-field diff is format-specific).\n * - `unchanged` — remote exists and local source/data match; skip.\n * - `skip` — local object type is not supported by the plugin, or\n * filtered out by the caller.\n *\n * We deliberately avoid computing a field-level diff here: that's a format\n * concern (abapGit vs gCTS normalise XML differently) and will be added via\n * the deferred `FormatPlugin.diff()` method — see E05 follow-ups.\n */\nimport type { AdkObject } from '@abapify/adk';\n\nexport type ChangeAction = 'create' | 'update' | 'unchanged' | 'skip';\n\nexport interface ChangePlanEntry {\n /** ADK object carrying local (deserialised) data. */\n object: AdkObject;\n /** What we intend to do with this object on SAP. */\n action: ChangeAction;\n /** Human-readable reason — used for dry-run output. */\n reason?: string;\n /** Error encountered during diff (load failure that wasn't a 404). */\n error?: string;\n}\n\n/**\n * Compute diff for a single object.\n *\n * Returns the `ChangePlanEntry` without yet mutating anything on SAP. The\n * caller decides whether to group, filter, or apply the plan.\n */\nexport async function diffObject(object: AdkObject): Promise<ChangePlanEntry> {\n // If the format plugin already populated `_pendingSource(s)` or\n // `_pendingDescription`, treat as potentially-changed — we can't be\n // cheaper without a format-specific diff, and `update` is the safe side\n // (SAP will short-circuit on identical content via ETag).\n const hasPending = Boolean(\n (object as unknown as { _pendingSource?: unknown })._pendingSource ||\n (object as unknown as { _pendingSources?: unknown })._pendingSources ||\n (object as unknown as { _pendingDescription?: unknown })\n ._pendingDescription,\n );\n\n try {\n // Save the locally-assembled _data before load() overwrites it with\n // server state (matches the pre-deploy pattern in adt-export).\n const localData = (object as unknown as { _data?: unknown })._data;\n await object.load();\n // Restore the plugin-provided data so the subsequent save uses it.\n (object as unknown as { _data?: unknown })._data = localData;\n\n return {\n object,\n action: hasPending ? 'update' : 'unchanged',\n reason: hasPending\n ? 'local source pending write'\n : 'no local changes detected',\n };\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n if (/404|not[- ]?found/i.test(msg)) {\n return {\n object,\n action: 'create',\n reason: 'remote object does not exist',\n };\n }\n return {\n object,\n action: 'skip',\n error: msg,\n reason: `diff failed: ${msg}`,\n };\n }\n}\n","/**\n * Plan builder — groups ChangePlanEntry items in dependency order for apply.\n *\n * SAP's activation order is **type-class sensitive**: DDIC primitives\n * (domains, data elements, tables, structures, ttypes) must exist before\n * application-level code (classes, interfaces, includes, programs, function\n * groups) can compile against them; CDS artifacts (DDL source, DCL source,\n * behaviour definitions, service definitions, service bindings) must come\n * last because they reference both categories.\n *\n * The grouping is sapcli-inspired (`_resolve_dependencies` in\n * `sap/cli/checkin.py`) but extended to match the ADK type vocabulary.\n */\nimport type { AdkObject } from '@abapify/adk';\nimport { getMainType } from '@abapify/adk';\nimport type { ChangePlanEntry } from './diff';\n\nexport type DependencyTier = 'ddic' | 'app' | 'cds' | 'package' | 'other';\n\n/** Object types classified by dependency tier (main type only). */\nconst TIER_FOR_TYPE: Record<string, DependencyTier> = {\n // DDIC primitives — no dependencies on ABAP code\n DOMA: 'ddic',\n DTEL: 'ddic',\n TABL: 'ddic',\n TTYP: 'ddic',\n VIEW: 'ddic',\n ENQU: 'ddic',\n SHLP: 'ddic',\n // Packages themselves are their own tier — must exist before any content\n DEVC: 'package',\n // Application code — depends on DDIC\n CLAS: 'app',\n INTF: 'app',\n PROG: 'app',\n INCL: 'app',\n FUGR: 'app',\n // CDS / RAP — depends on everything else\n DDLS: 'cds',\n DCLS: 'cds',\n DDLX: 'cds',\n SRVD: 'cds',\n SRVB: 'cds',\n BDEF: 'cds',\n};\n\n/** Order tiers are applied. */\nconst TIER_ORDER: DependencyTier[] = ['package', 'ddic', 'app', 'cds', 'other'];\n\nexport function classifyTier(type: string): DependencyTier {\n return TIER_FOR_TYPE[getMainType(type)] ?? 'other';\n}\n\nexport interface ChangePlan {\n /** All entries regardless of action/tier, in discovery order. */\n entries: ChangePlanEntry[];\n /** Actionable entries grouped by tier in apply order. */\n groups: Array<{ tier: DependencyTier; entries: ChangePlanEntry[] }>;\n /** Entries that don't need an apply pass (skip/unchanged). */\n inert: ChangePlanEntry[];\n}\n\n/**\n * Build a ChangePlan by classifying each entry and sorting into tiers.\n *\n * Entries whose action is `skip` or `unchanged` are parked in `inert` so the\n * apply stage doesn't touch them. Empty tiers are elided.\n */\nexport function buildPlan(entries: ChangePlanEntry[]): ChangePlan {\n const byTier = new Map<DependencyTier, ChangePlanEntry[]>();\n const inert: ChangePlanEntry[] = [];\n\n for (const entry of entries) {\n if (entry.action === 'skip' || entry.action === 'unchanged') {\n inert.push(entry);\n continue;\n }\n const tier = classifyTier(entry.object.type);\n const bucket = byTier.get(tier) ?? [];\n bucket.push(entry);\n byTier.set(tier, bucket);\n }\n\n const groups: ChangePlan['groups'] = [];\n for (const tier of TIER_ORDER) {\n const bucket = byTier.get(tier);\n if (bucket && bucket.length > 0) {\n groups.push({ tier, entries: bucket });\n }\n }\n\n return { entries, groups, inert };\n}\n\n/** Extract a flat ordered list of AdkObjects from a plan (apply order). */\nexport function flattenPlanObjects(plan: ChangePlan): AdkObject[] {\n const out: AdkObject[] = [];\n for (const group of plan.groups) {\n for (const entry of group.entries) {\n out.push(entry.object);\n }\n }\n return out;\n}\n","/**\n * Apply stage — executes a ChangePlan against SAP.\n *\n * Each tier is deployed as its own `AdkObjectSet` so that DDIC objects are\n * saved + activated before the application-code tier starts. Within a tier,\n * objects are saved with `mode: 'upsert'` — SAP's PUT endpoints auto-detect\n * whether the object already exists so we don't need separate create/update\n * paths here.\n *\n * Locking:\n * - Before each tier, an outer `BatchLockSession` pre-acquires locks to\n * catch conflicts early (e.g. another user editing). Because ADK's\n * `save()` also lock/unlocks per object, we release the batch session\n * immediately after pre-flight — the CSRF security session is preserved\n * so the subsequent per-object re-lock is cheap.\n * - If the batch pre-flight fails, the tier is aborted and all locks\n * acquired so far (in that tier) are rolled back; partial state from\n * previous tiers is documented to the caller.\n */\nimport type { AdkObject, AdkContext } from '@abapify/adk';\nimport { AdkObjectSet } from '@abapify/adk';\nimport {\n createBatchLockSession,\n type BatchLockTarget,\n} from '@abapify/adt-locks';\nimport type { ChangePlan, DependencyTier } from './plan';\n\nexport interface ApplyOptions {\n /** Transport request used for lock + save operations. */\n transport?: string;\n /** Dry run — build plan but don't touch SAP. */\n dryRun?: boolean;\n /** Activate saved objects after each tier. Default: true. */\n activate?: boolean;\n /**\n * Release locks for which this client persisted a handle before the batch\n * lock session begins. Mirrors `adt export --unlock`.\n */\n unlock?: boolean;\n /** Per-tier progress hook. */\n onTierStart?: (tier: DependencyTier, size: number) => void;\n /** Per-object progress hook. */\n onObject?: (object: AdkObject, status: string) => void;\n}\n\nexport interface ApplyTierResult {\n tier: DependencyTier;\n size: number;\n saved: number;\n failed: number;\n unchanged: number;\n activated: number;\n errors: Array<{ name: string; type: string; error: string }>;\n}\n\nexport interface ApplyResult {\n /** Per-tier stats in the order they were applied. */\n tiers: ApplyTierResult[];\n /** Aggregate totals. */\n totals: {\n saved: number;\n failed: number;\n unchanged: number;\n activated: number;\n };\n /** True if the caller aborted before all tiers ran (lock conflict). */\n aborted: boolean;\n}\n\n/** Execute the change plan. Always returns a result — caller decides exit. */\nexport async function applyPlan(\n plan: ChangePlan,\n ctx: AdkContext,\n options: ApplyOptions = {},\n): Promise<ApplyResult> {\n const activate = options.activate ?? true;\n const result: ApplyResult = {\n tiers: [],\n totals: { saved: 0, failed: 0, unchanged: 0, activated: 0 },\n aborted: false,\n };\n\n for (const group of plan.groups) {\n const tierResult: ApplyTierResult = {\n tier: group.tier,\n size: group.entries.length,\n saved: 0,\n failed: 0,\n unchanged: 0,\n activated: 0,\n errors: [],\n };\n options.onTierStart?.(group.tier, group.entries.length);\n\n if (options.dryRun) {\n // Pretend everything succeeded for reporting only.\n for (const entry of group.entries) {\n options.onObject?.(entry.object, 'dry-run');\n tierResult.saved++;\n }\n result.tiers.push(tierResult);\n result.totals.saved += tierResult.saved;\n continue;\n }\n\n // Optional: release only persisted stale locks. SAP cannot disclose a\n // lost handle by issuing another LOCK.\n if (options.unlock && ctx.lockService) {\n for (const entry of group.entries) {\n try {\n await ctx.lockService.forceUnlock(entry.object.objectUri);\n } catch {\n /* no persisted handle or server rejected it — preflight reports it */\n }\n }\n }\n\n // Pre-flight: batch-lock to surface conflicts BEFORE we start mutating.\n // We release immediately afterwards because ADK's save() will re-lock\n // per object within the same security session (CSRF survives unlock).\n let preflightFailed = false;\n if (ctx.lockService) {\n const targets: BatchLockTarget[] = group.entries.map((e) => ({\n objectUri: e.object.objectUri,\n options: {\n transport: options.transport,\n objectName: e.object.name,\n objectType: e.object.type,\n },\n }));\n const batch = createBatchLockSession(ctx.lockService, targets);\n try {\n await batch.begin();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n tierResult.errors.push({\n name: '(batch)',\n type: group.tier,\n error: `batch lock pre-flight failed: ${msg}`,\n });\n tierResult.failed = group.entries.length;\n preflightFailed = true;\n } finally {\n await batch.release();\n }\n }\n\n if (preflightFailed) {\n result.tiers.push(tierResult);\n result.totals.failed += tierResult.failed;\n result.aborted = true;\n // Stop applying further tiers — the caller sees a partial-apply state.\n break;\n }\n\n // Build the tier's AdkObjectSet and deploy.\n const set = new AdkObjectSet(ctx);\n for (const entry of group.entries) set.add(entry.object);\n\n const deployResult = await set.deploy({\n transport: options.transport,\n activate,\n mode: 'upsert',\n onProgress: (_processed, _total, current) => {\n options.onObject?.(current, 'saved');\n },\n });\n\n tierResult.saved = deployResult.save.success;\n tierResult.failed = deployResult.save.failed;\n tierResult.unchanged = deployResult.save.unchanged;\n tierResult.activated = deployResult.activation?.success ?? 0;\n for (const r of deployResult.save.results) {\n if (!r.success && !r.unchanged) {\n tierResult.errors.push({\n name: r.object.name,\n type: r.object.type,\n error: r.error ?? 'unknown error',\n });\n }\n }\n\n result.tiers.push(tierResult);\n result.totals.saved += tierResult.saved;\n result.totals.failed += tierResult.failed;\n result.totals.unchanged += tierResult.unchanged;\n result.totals.activated += tierResult.activated;\n }\n\n return result;\n}\n","/**\n * CheckinService — push a local abapGit/gCTS directory into SAP.\n *\n * Pipeline:\n * 1. Load the chosen FormatPlugin (via `loadFormatPlugin`; works for any\n * registered format — `abapgit`, `gcts`/`aff`, third-party).\n * 2. Drive the plugin's `format.export(fileTree, client, options)`\n * AsyncGenerator to deserialise local files into `AdkObject`\n * instances. This is the ONE place where file → object conversion\n * lives — every format participates transparently.\n * 3. Optionally validate the target transport via the typed\n * `transportrequests.get` contract.\n * 4. Run diff against remote (per-object `load()` 404-check).\n * 5. Build a tier-ordered `ChangePlan` (DDIC → APP → CDS → other).\n * 6. Apply via `applyPlan` → pre-flight batch locks per tier + ADK save.\n *\n * The service returns a structured `CheckinResult` — neither the CLI nor\n * the MCP tool contains any business logic, they only format the result.\n *\n * gCTS note: because `loadFormatPlugin('gcts')` resolves to\n * `@abapify/adt-plugin-gcts`, invoking `CheckinService.checkin({format:\n * 'gcts', ...})` produces an identical apply pipeline — only the\n * deserialisation step differs. That's the FormatPlugin guarantee in action.\n */\nimport type { AdkObject, AdkContext } from '@abapify/adk';\nimport { AdkTransport, getGlobalContext } from '@abapify/adk';\nimport type { FormatOptionValue } from '@abapify/adt-plugin';\n\nimport { loadFormatPlugin } from '../../utils/format-loader';\nimport { createFsFileTree } from './filetree';\n\nimport { diffObject, type ChangePlanEntry } from './diff';\nimport { buildPlan, type ChangePlan, type DependencyTier } from './plan';\nimport { applyPlan, type ApplyOptions, type ApplyResult } from './apply';\n\nexport interface CheckinOptions {\n /** Source directory containing serialised files (abapGit/gCTS layout). */\n sourceDir: string;\n /** Format id — `abapgit` | `gcts` | `aff` | bespoke plugin package. */\n format: string;\n /** Target root package (used by FormatPlugin to resolve packageRef). */\n rootPackage?: string;\n /** Transport request for all modified/created objects. */\n transport?: string;\n /** Filter by ABAP object types (e.g. ['CLAS','INTF']). */\n objectTypes?: string[];\n /** Dry run — validate only, no SAP writes. */\n dryRun?: boolean;\n /** Activate objects after save (default true). */\n activate?: boolean;\n /** Release stale locks only when this client persisted their handles. */\n unlock?: boolean;\n /** ABAP language version override (e.g. '5' for Cloud). */\n abapLanguageVersion?: string;\n /** Format-specific options (opaque to the service). */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Optional ADK context override (tests pass a shared one). */\n adkContext?: AdkContext;\n /** Log hook — no console writes inside the service itself. */\n onLog?: (level: 'info' | 'warn' | 'error', message: string) => void;\n /** Per-object progress hook passed down to apply. */\n onObject?: (object: AdkObject, status: string) => void;\n}\n\nexport interface CheckinResult {\n /** Source directory that was checked in. */\n sourceDir: string;\n /** Format id used for deserialisation. */\n format: string;\n /** Total AdkObjects discovered from the file tree. */\n discovered: number;\n /** Diff outcome per action kind (create/update/unchanged/skip). */\n actions: Record<string, number>;\n /** Tiered apply result (one entry per non-empty tier). */\n apply: ApplyResult;\n /** Plan groups as tier → entries (for dry-run/output formatting). */\n groups: Array<{\n tier: DependencyTier;\n entries: Array<{\n name: string;\n type: string;\n action: ChangePlanEntry['action'];\n }>;\n }>;\n /** True if we stopped before applying every tier. */\n aborted: boolean;\n /** Human-readable summary suitable for CLI output. */\n summary: string;\n}\n\nexport class CheckinService {\n async checkin(options: CheckinOptions): Promise<CheckinResult> {\n const log = options.onLog ?? (() => undefined);\n\n // 1. Resolve format plugin (FormatPlugin registry + AdtPlugin legacy path).\n const plugin = await loadFormatPlugin(options.format);\n if (!plugin.instance.format.export) {\n throw new Error(\n `Format plugin '${plugin.name}' does not implement format.export — ` +\n `cannot deserialise local files. Required for checkin.`,\n );\n }\n log('info', `Loaded format plugin: ${plugin.name}`);\n\n // 2. Deserialise local files → AdkObjects.\n const adkContext = options.adkContext ?? getGlobalContext();\n const client = adkContext.client;\n const fileTree = createFsFileTree(options.sourceDir);\n\n const filterTypes = options.objectTypes?.map((t) => t.toUpperCase());\n const discovered: AdkObject[] = [];\n\n for await (const obj of plugin.instance.format.export(fileTree, client, {\n rootPackage: options.rootPackage,\n abapLanguageVersion: options.abapLanguageVersion,\n formatOptions: options.formatOptions,\n })) {\n if (filterTypes && !matchesTypeFilter(obj.type, filterTypes)) continue;\n discovered.push(obj);\n }\n log(\n 'info',\n `Discovered ${discovered.length} objects from ${options.sourceDir}`,\n );\n\n // 3. Optional transport validation.\n if (options.transport && !options.dryRun) {\n try {\n await AdkTransport.get(options.transport);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n throw new Error(\n `Transport validation failed for ${options.transport}: ${msg}`,\n { cause: err },\n );\n }\n }\n\n // 4. Diff against remote.\n const entries: ChangePlanEntry[] = [];\n for (const obj of discovered) {\n entries.push(await diffObject(obj));\n }\n\n // 5. Build plan.\n const plan: ChangePlan = buildPlan(entries);\n\n const actions: Record<string, number> = {\n create: 0,\n update: 0,\n unchanged: 0,\n skip: 0,\n };\n for (const entry of entries) actions[entry.action]++;\n\n // 6. Apply (skipped entirely for dry run).\n const applyOptions: ApplyOptions = {\n transport: options.transport,\n dryRun: options.dryRun,\n activate: options.activate,\n unlock: options.unlock,\n onTierStart: (tier, size) =>\n log('info', `→ Applying tier ${tier} (${size} objects)`),\n onObject: options.onObject,\n };\n const applyResult = await applyPlan(plan, adkContext, applyOptions);\n\n const summary = formatSummary(discovered.length, actions, applyResult);\n\n return {\n sourceDir: options.sourceDir,\n format: options.format,\n discovered: discovered.length,\n actions,\n apply: applyResult,\n groups: plan.groups.map((g) => ({\n tier: g.tier,\n entries: g.entries.map((e) => ({\n name: e.object.name,\n type: e.object.type,\n action: e.action,\n })),\n })),\n aborted: applyResult.aborted,\n summary,\n };\n }\n}\n\n// ─────────────────────────────────────────────────────────────────────────\n\nfunction matchesTypeFilter(type: string, filter: string[]): boolean {\n const upper = type.toUpperCase();\n const main = upper.split('/')[0];\n return filter.includes(upper) || filter.includes(main);\n}\n\nfunction formatSummary(\n discovered: number,\n actions: Record<string, number>,\n apply: ApplyResult,\n): string {\n const parts = [\n `${discovered} discovered`,\n `${actions.create ?? 0} new`,\n `${actions.update ?? 0} modified`,\n `${actions.unchanged ?? 0} unchanged`,\n `${apply.totals.saved} saved`,\n `${apply.totals.activated} activated`,\n ];\n if (apply.totals.failed > 0) parts.push(`${apply.totals.failed} failed`);\n if (apply.aborted) parts.push('aborted (partial-apply)');\n return parts.join(', ');\n}\n","/** Concrete connection metadata used to instantiate an ADT client. */\ninterface ConnectionParams {\n baseUrl: string;\n client?: string;\n username?: string;\n password?: string;\n}\n\n/**\n * Inputs accepted by the shared connection resolver.\n *\n * `baseUrl` and `systemId` are mutually exclusive selectors:\n * - `baseUrl` selects explicit connection args\n * - `systemId` selects configured/fallback lookup paths\n */\nexport interface ConnectionResolveArgs {\n baseUrl?: string;\n client?: string;\n username?: string;\n password?: string;\n systemId?: string;\n}\n\n/**\n * Hook points used by the resolver to stay transport/framework agnostic.\n *\n * Resolution chain:\n * 1. `createClient` with explicit args (`baseUrl`)\n * 2. `resolveSystem` + `createClient` (`systemId` from registry)\n * 3. `resolveFromAuthStore` (`systemId` from local auth-store fallback)\n */\nexport interface ResolveConnectionClientHooks<TClient> {\n createClient: (params: ConnectionParams) => TClient;\n resolveSystem?: (systemId: string) => ConnectionParams | undefined;\n resolveFromAuthStore?: (systemId: string) => Promise<TClient>;\n}\n\n/**\n * Final resolved client plus metadata about how it was obtained.\n *\n * `systemId` is present when a logical system was used and may be absent\n * for plain explicit `baseUrl` calls.\n */\nexport interface ResolvedConnectionClient<TClient> {\n client: TClient;\n systemId?: string;\n source: 'explicit' | 'multi-system' | 'adt-cli-auth-store';\n}\n\nexport async function resolveConnectionClient<TClient>(\n args: ConnectionResolveArgs,\n hooks: ResolveConnectionClientHooks<TClient>,\n): Promise<ResolvedConnectionClient<TClient>> {\n if (args.baseUrl) {\n return {\n client: hooks.createClient({\n baseUrl: args.baseUrl,\n client: args.client,\n username: args.username,\n password: args.password,\n }),\n systemId: args.systemId,\n source: 'explicit',\n };\n }\n\n if (args.systemId && hooks.resolveSystem) {\n const params = hooks.resolveSystem(args.systemId);\n if (params) {\n return {\n client: hooks.createClient({\n ...params,\n username: args.username,\n password: args.password,\n }),\n systemId: args.systemId,\n source: 'multi-system',\n };\n }\n }\n\n if (args.systemId && hooks.resolveFromAuthStore) {\n return {\n client: await hooks.resolveFromAuthStore(args.systemId),\n systemId: args.systemId,\n source: 'adt-cli-auth-store',\n };\n }\n\n throw new Error(\n 'No connection could be resolved: provide baseUrl (+ credentials) or systemId resolvable via multi-system config or ~/.adt session store.',\n );\n}\n","import { AdkTransportRequest, type ReleaseResult } from '@abapify/adk';\nimport type { AdtClient } from '@abapify/adt-client';\n\nfunction normalizeTransportIdentifier(\n transport: string,\n errorMessage = 'Transport identifier is required',\n): string {\n const normalized = transport.trim().toUpperCase();\n if (!normalized) {\n throw new Error(errorMessage);\n }\n return normalized;\n}\n\nexport interface CtsTransportLifecycleOperations {\n getTransport(\n transport: string,\n client: AdtClient,\n ): Promise<AdkTransportRequest>;\n}\n\nconst DEFAULT_OPERATIONS: CtsTransportLifecycleOperations = {\n getTransport: (transport, client) =>\n AdkTransportRequest.get(transport, { client }),\n};\n\nexport interface CtsTransportSummary {\n transport: string;\n status: string;\n statusText: string;\n owner: string;\n description: string;\n target: string;\n targetDescription: string;\n taskCount: number;\n objectCount: number;\n}\n\nexport interface ReleaseTransportInput {\n transport: string;\n releaseAll?: boolean;\n}\n\nexport interface ReleaseTransportResult {\n status: 'released' | 'already_released';\n transport: string;\n releaseAll: boolean;\n result: ReleaseResult;\n}\n\nexport interface ReassignTransportInput {\n transport: string;\n newOwner: string;\n recursive?: boolean;\n}\n\nexport interface ReassignTransportResult {\n status: 'reassigned';\n transport: string;\n previousOwner: string;\n newOwner: string;\n recursive: boolean;\n}\n\nexport interface CreateTaskInput {\n transport: string;\n owner: string;\n}\n\nexport interface CreateTaskResult {\n status: 'created';\n transport: string;\n task: string;\n owner: string;\n}\n\nexport class CtsTransportLifecycleService {\n constructor(\n private readonly client: AdtClient,\n private readonly operations: CtsTransportLifecycleOperations = DEFAULT_OPERATIONS,\n ) {}\n\n async getTransport(transport: string): Promise<CtsTransportSummary> {\n const normalizedTransport = normalizeTransportIdentifier(transport);\n const model = await this.operations.getTransport(\n normalizedTransport,\n this.client,\n );\n return {\n transport: model.number,\n status: model.status,\n statusText: model.statusText,\n owner: model.owner,\n description: model.description,\n target: model.target,\n targetDescription: model.targetDescription,\n taskCount: model.tasks.length,\n objectCount: model.objects.length,\n };\n }\n\n async release(input: ReleaseTransportInput): Promise<ReleaseTransportResult> {\n const transport = normalizeTransportIdentifier(input.transport);\n const releaseAll = input.releaseAll ?? false;\n const model = await this.operations.getTransport(transport, this.client);\n if (model.status === 'R') {\n return {\n status: 'already_released',\n transport: model.number,\n releaseAll,\n result: { success: true },\n };\n }\n\n const result = releaseAll\n ? await model.releaseAll()\n : await model.release();\n if (!result.success) {\n throw new Error(\n result.message || `Release of transport ${model.number} failed`,\n );\n }\n\n return {\n status: 'released',\n transport: model.number,\n releaseAll,\n result,\n };\n }\n\n async createTask(input: CreateTaskInput): Promise<CreateTaskResult> {\n const transport = normalizeTransportIdentifier(\n input.transport,\n 'Transport and task owner are required',\n );\n const owner = input.owner.trim().toUpperCase();\n if (!owner) {\n throw new Error('Transport and task owner are required');\n }\n const model = await this.operations.getTransport(transport, this.client);\n const task = await model.addTask(owner);\n const updatedModel = await this.operations.getTransport(\n transport,\n this.client,\n );\n const confirmed = updatedModel.tasks.some(\n (t) => t.number === task.number && t.owner === task.owner,\n );\n if (!confirmed) {\n throw new Error(`no new task owned by ${owner}`);\n }\n return {\n status: 'created',\n transport: model.number,\n task: task.number,\n owner: task.owner,\n };\n }\n\n async reassign(\n input: ReassignTransportInput,\n ): Promise<ReassignTransportResult> {\n const transport = normalizeTransportIdentifier(\n input.transport,\n 'Transport and new owner are required',\n );\n const newOwner = input.newOwner.trim().toUpperCase();\n if (!newOwner) {\n throw new Error('Transport and new owner are required');\n }\n const model = await this.operations.getTransport(transport, this.client);\n if (model.status === 'R') {\n throw new Error(`Transport ${model.number} is already released`);\n }\n\n const recursive = input.recursive ?? false;\n const previousOwner = model.owner;\n await model.reassign(newOwner, recursive);\n\n return {\n status: 'reassigned',\n transport: model.number,\n previousOwner,\n newOwner: model.owner,\n recursive,\n };\n }\n}\n","import type { AdtClient } from '@abapify/adt-client';\n\nexport interface CtsTransportMetadataUnit {\n kind: 'request' | 'task';\n number: string;\n description?: string;\n owner?: string;\n status?: string;\n type?: string;\n parent?: string;\n lastChangedTimestamp?: string;\n}\n\nexport interface CtsTransportMetadataResult {\n requestedTransport: string;\n units: CtsTransportMetadataUnit[];\n}\n\n/**\n * Typed CTS metadata projection shared by CLI and MCP. The ADT client owns\n * protocol decoding; this service deliberately has no XML or console logic.\n */\nexport class CtsTransportMetadataService {\n constructor(private readonly client: AdtClient) {}\n\n async get(transport: string): Promise<CtsTransportMetadataResult> {\n const requestedTransport = transport.trim().toUpperCase();\n if (!requestedTransport)\n throw new Error('Transport identifier is required');\n const request =\n await this.client.services.transports.get(requestedTransport);\n const units: CtsTransportMetadataUnit[] = [\n {\n kind: request.parent ? 'task' : 'request',\n number: request.number,\n description: request.desc,\n owner: request.owner,\n status: request.status,\n type: request.type,\n parent: request.parent,\n lastChangedTimestamp: request.lastChangedTimestamp,\n },\n ...(request.tasks ?? []).map((task) => ({\n kind: 'task' as const,\n number: task.number,\n description: task.desc,\n owner: task.owner,\n status: task.status,\n type: task.type,\n parent: task.parent || request.number,\n lastChangedTimestamp: task.lastChangedTimestamp,\n })),\n ];\n // Select the requested transport unit before returning. A request query\n // keeps its request unit plus child tasks; a task query keeps only the\n // matching task unit instead of projecting a parent request.\n const requested = requestedTransport.toUpperCase();\n if (units.length > 0 && units[0].number.toUpperCase() !== requested) {\n const selected = units.filter(\n (unit) => unit.number.toUpperCase() === requested,\n );\n if (selected.length > 0) {\n units.splice(0, units.length, ...selected);\n }\n }\n return { requestedTransport, units };\n }\n}\n","/**\n * Shared ADT Client State\n *\n * Global state and singleton instances for ADT client management.\n * This module holds stateful objects that are shared across CLI commands.\n *\n * For the factory function that creates clients, see utils/adt-client.ts\n */\nimport type { Logger } from '@abapify/adt-client';\n\n// =============================================================================\n// Global CLI Context (set by CLI preAction hook)\n// =============================================================================\n\nexport interface CliContext {\n sid?: string;\n logger?: Logger;\n logLevel?: string;\n logOutput?: string;\n logResponseFiles?: boolean;\n verbose?: boolean | string;\n /** Path to config file (from --config flag) */\n configPath?: string;\n}\n\nlet globalCliContext: CliContext = {};\n\n/**\n * Set global CLI context (called by CLI preAction hook)\n * This allows getAdtClientV2() to auto-read CLI options without passing them explicitly\n */\nexport function setCliContext(context: CliContext): void {\n globalCliContext = { ...globalCliContext, ...context };\n}\n\n/**\n * Get current CLI context\n */\nexport function getCliContext(): CliContext {\n return globalCliContext;\n}\n\n/**\n * Reset CLI context (useful for testing)\n */\nexport function resetCliContext(): void {\n globalCliContext = {};\n}\n\n// =============================================================================\n// Shared Loggers\n// =============================================================================\n\n/**\n * Silent logger - suppresses all output (default for CLI)\n */\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst noop = () => {};\nexport const silentLogger: Logger = {\n trace: noop,\n debug: noop,\n info: noop,\n warn: noop,\n error: noop,\n fatal: noop,\n child: () => silentLogger,\n};\n\n/**\n * Console logger - outputs to console (used when enableLogging is true)\n */\nexport const consoleLogger: Logger = {\n trace: (msg: string) => console.error(msg),\n debug: (msg: string) => console.error(msg),\n info: (msg: string) => console.error(msg),\n warn: (msg: string) => console.error(msg),\n error: (msg: string) => console.error(msg),\n fatal: (msg: string) => console.error(msg),\n child: () => consoleLogger,\n};\n\n// =============================================================================\n// Capture Plugin State\n// =============================================================================\n\n/**\n * Captured response data from the last request\n */\nexport interface CapturedResponse {\n /** Raw XML/text response */\n xml?: string;\n /** Parsed JSON response */\n json?: unknown;\n}\n\n// Global capture storage (reset on each request)\nlet lastCaptured: CapturedResponse = {};\n\n/**\n * Get the last captured response (for commands that need raw XML/JSON)\n */\nexport function getCaptured(): CapturedResponse {\n return lastCaptured;\n}\n\n/**\n * Set captured response data\n */\nexport function setCaptured(data: CapturedResponse): void {\n lastCaptured = data;\n}\n\n/**\n * Reset captured data (called before each request when capture is enabled)\n */\nexport function resetCaptured(): void {\n lastCaptured = {};\n}\n","/**\n * Destination utilities\n *\n * Loads destinations from adt.config.ts/json using @abapify/adt-config\n */\n\nimport {\n loadConfig,\n type LoadedConfig,\n type Destination,\n} from '@abapify/adt-config';\nimport { getCliContext } from '../shared/adt-client';\n\n// Cached config instance (keyed by configPath to handle different configs)\nlet cachedConfig: LoadedConfig | null = null;\nlet cachedConfigPath: string | undefined = undefined;\n\n/**\n * Get loaded config (cached)\n * Uses configPath from CLI context if available (from --config flag)\n */\nexport async function getConfig(): Promise<LoadedConfig> {\n const context = getCliContext();\n const configPath = context.configPath;\n\n // Invalidate cache if configPath changed\n if (cachedConfig && cachedConfigPath !== configPath) {\n cachedConfig = null;\n }\n\n if (!cachedConfig) {\n cachedConfig = await loadConfig({ configPath });\n cachedConfigPath = configPath;\n }\n return cachedConfig;\n}\n\n/**\n * Get a destination by name (SID)\n * @param name Destination name (e.g., 'TRL')\n */\nexport async function getDestination(\n name: string,\n): Promise<Destination | undefined> {\n const config = await getConfig();\n return config.getDestination(name);\n}\n\n/**\n * List all configured destinations\n */\nexport async function listDestinations(): Promise<string[]> {\n const config = await getConfig();\n return config.listDestinations();\n}\n\n/**\n * Check if a destination exists\n */\nexport async function hasDestination(name: string): Promise<boolean> {\n const config = await getConfig();\n return config.hasDestination(name);\n}\n\n/**\n * Clear cached config (useful for testing)\n */\nexport function clearConfigCache(): void {\n cachedConfig = null;\n cachedConfigPath = undefined;\n}\n\n// Re-export types\nexport type { LoadedConfig, Destination } from '@abapify/adt-config';\n","/**\n * Parse a comma-separated string of SAP transport numbers into a deduplicated\n * uppercase array.\n *\n * Trims whitespace, uppercases, filters empty tokens, and removes duplicates\n * while preserving insertion order (O(n) via Set).\n *\n * Throws when no valid transport numbers are found.\n *\n * @example\n * parseTransportNumbers('DEVK900001') // → ['DEVK900001']\n * parseTransportNumbers('DEVK900001, DEVK900002') // → ['DEVK900001', 'DEVK900002']\n * parseTransportNumbers('DEVK900001,DEVK900001') // → ['DEVK900001'] (deduped)\n */\nexport function parseTransportNumbers(value: string): string[] {\n const seen = new Set<string>();\n const numbers = value\n .split(',')\n .map((n) => n.trim().toUpperCase())\n .filter(Boolean)\n .filter((n) => {\n if (seen.has(n)) return false;\n seen.add(n);\n return true;\n });\n\n if (numbers.length === 0) {\n throw new Error(`No transport number(s) provided in '${value}'`);\n }\n\n return numbers;\n}\n","export type SearchObject = {\n name?: string;\n type?: string;\n uri?: string;\n description?: string;\n packageName?: string;\n};\n\nexport type ObjectSearchOptions = {\n objectName: string;\n objectType?: string;\n};\n\ntype SearchObjectResolutionContext = {\n objects: SearchObject[];\n options: ObjectSearchOptions;\n exactMatches: SearchObject[];\n availableExactTypes: string[];\n requestedObjectType: string | undefined;\n};\n\nfunction normalizeObjectType(type: string): string {\n return type.toUpperCase().split('/')[0] ?? '';\n}\n\nfunction getExactSearchMatches(\n objects: SearchObject[],\n objectName: string,\n): SearchObject[] {\n const normalizedName = objectName.toUpperCase();\n return objects.filter(\n (obj) => String(obj.name || '').toUpperCase() === normalizedName,\n );\n}\n\nfunction getSearchObjectTypes(objects: SearchObject[]): string[] {\n return [\n ...new Set(\n objects.map((obj) => normalizeObjectType(String(obj.type || ''))),\n ),\n ].filter(Boolean);\n}\n\nfunction findExactSearchMatch(\n exactMatches: SearchObject[],\n requestedObjectType: string | undefined,\n availableExactTypes: string[],\n): SearchObject | undefined {\n if (requestedObjectType) {\n return exactMatches.find(\n (obj) =>\n normalizeObjectType(String(obj.type || '')) === requestedObjectType,\n );\n }\n\n return availableExactTypes.length <= 1 ? exactMatches[0] : undefined;\n}\n\nfunction createObjectNotFoundError(\n objects: SearchObject[],\n objectName: string,\n): Error {\n const similar = objects\n .filter((obj) =>\n String(obj.name || '')\n .toUpperCase()\n .includes(objectName.toUpperCase()),\n )\n .slice(0, 5);\n const similarList = similar\n .map((obj) => ` • ${obj.name} (${obj.type}) – ${obj.packageName}`)\n .join('\\n');\n const hint =\n similar.length > 0 ? `\\n💡 Similar objects:\\n${similarList}` : '';\n\n return new Error(`Object '${objectName}' not found in the system.${hint}`);\n}\n\nfunction createSearchObjectResolutionError(\n context: SearchObjectResolutionContext,\n): Error {\n const {\n objects,\n options,\n exactMatches,\n availableExactTypes,\n requestedObjectType,\n } = context;\n\n if (requestedObjectType && exactMatches.length > 0) {\n return new Error(\n `Object '${options.objectName}' with type '${requestedObjectType}' was not found. Available types: ${availableExactTypes.join(', ') || 'none'}.`,\n );\n }\n\n if (!requestedObjectType && availableExactTypes.length > 1) {\n return new Error(\n `Object '${options.objectName}' is ambiguous. Use --object-type to select one of: ${availableExactTypes.join(', ')}.`,\n );\n }\n\n return createObjectNotFoundError(objects, options.objectName);\n}\n\nexport function selectSearchObject(\n objects: SearchObject[],\n options: ObjectSearchOptions,\n): SearchObject {\n const exactMatches = getExactSearchMatches(objects, options.objectName);\n const availableExactTypes = getSearchObjectTypes(exactMatches);\n const requestedObjectType = options.objectType\n ? normalizeObjectType(options.objectType.trim())\n : undefined;\n const exactMatch = findExactSearchMatch(\n exactMatches,\n requestedObjectType,\n availableExactTypes,\n );\n\n if (exactMatch) {\n return exactMatch;\n }\n\n throw createSearchObjectResolutionError({\n objects,\n options,\n exactMatches,\n availableExactTypes,\n requestedObjectType,\n });\n}\n","import { loadFormatPlugin, parseFormatSpec } from '../../utils/format-loader';\nimport { getConfig } from '../../utils/destinations';\nimport { parseTransportNumbers } from '../../utils/transport-numbers';\nimport type { ImportContext, FormatOptionValue } from '@abapify/adt-plugin';\nimport {\n AdkPackage,\n AdkTransport,\n MergedTransportView,\n matchesSelector,\n getGlobalContext,\n createAdkFactory,\n} from '@abapify/adk';\nimport type { AdkTransportObjectRef } from '@abapify/adk';\nimport { Readable } from 'node:stream';\nimport { mkdir, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { selectSearchObject, type SearchObject } from './object-selection';\n\n/** Default number of concurrent SAP requests during import */\nconst IMPORT_CONCURRENCY = 5;\n\n/**\n * Resolve full package path from root to the given package.\n * Traverses the ADK package hierarchy upward until the root is reached.\n */\nasync function resolvePackagePath(packageName: string): Promise<string[]> {\n const path: string[] = [];\n let currentPackage = packageName;\n\n while (currentPackage) {\n path.unshift(currentPackage);\n try {\n const pkg = await AdkPackage.get(currentPackage);\n const superPkg = pkg.superPackage;\n if (superPkg?.name) {\n currentPackage = superPkg.name;\n } else {\n break;\n }\n } catch {\n break;\n }\n }\n return path;\n}\n\n/**\n * Options for importing a single object by name (search-based)\n */\nexport interface ObjectImportOptions {\n /** Object name to search for (e.g., 'ZAGE_DOMA_CASE_SENSITIVE') */\n objectName: string;\n /** Exact ABAP object type used to disambiguate same-named objects */\n objectType?: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Format-specific options provided via CLI */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Enable debug output */\n debug?: boolean;\n}\n\n/**\n * Options for importing a transport request\n */\nexport interface TransportImportOptions {\n /**\n * Transport request number(s).\n *\n * Accepts a single number or a comma-separated list:\n * - `'DEVK900001'` — single TR\n * - `'DEVK900001,DEVK900002,DEVK900003'` — multiple TRs (merged, deduplicated)\n */\n transportNumber: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Filter by object types (e.g., ['CLAS', 'INTF']) - if not specified, imports all */\n objectTypes?: string[];\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Format-specific options provided via CLI */\n formatOptions?: Record<string, FormatOptionValue>;\n /** Enable debug output */\n debug?: boolean;\n /**\n * Whether to apply deletions for objects marked with obj_func=D and pgmid=R3TR.\n * Default: true\n */\n applyDeletions?: boolean;\n /**\n * When true, write a JSON sidecar for each transport to\n * `<outputPath>/.adt/tr/<TRKORR>.json` with normalized transport metadata.\n * Default: false\n */\n saveTrMetadata?: boolean;\n /**\n * When true, objects that are in the TR list but cannot be fetched from SAP\n * (i.e., `objRef.load()` returns null — the object no longer exists in the system)\n * are treated as deletions: `format.delete()` is called to remove their local files.\n *\n * This catches the \"orphan sync\" case where an object was removed in SAP without\n * an explicit `obj_func=D` entry in the transport.\n *\n * Default: false (backward-compatible; previously counted as skipped)\n */\n removeMissingObjects?: boolean;\n}\n\n/**\n * Options for importing a package\n */\nexport interface PackageImportOptions {\n /** Package name (e.g., 'Z_MY_PACKAGE') */\n packageName: string;\n /** Output directory for serialized files */\n outputPath: string;\n /** Filter by object types (e.g., ['CLAS', 'INTF']) - if not specified, imports all */\n objectTypes?: string[];\n /** Include subpackages */\n includeSubpackages?: boolean;\n /** Format plugin name or package (e.g., 'abapgit', '@abapify/adt-plugin-abapgit') */\n format: string;\n /** Enable debug output */\n debug?: boolean;\n}\n\n/**\n * Result of an import operation\n */\nexport interface ImportResult {\n /** Transport number (for transport imports) */\n transportNumber?: string;\n /** Package name (for package imports) */\n packageName?: string;\n /** Object name (for single-object imports) */\n objectName?: string;\n /** Object type (for single-object imports) */\n objectType?: string;\n /** Description of the imported content */\n description: string;\n /** Total objects found */\n totalObjects: number;\n /** Statistics */\n results: {\n success: number;\n skipped: number;\n failed: number;\n /** Objects deleted from the file system (obj_func=D) */\n deleted: number;\n };\n /** Objects by type */\n objectsByType: Record<string, number>;\n /** Output path */\n outputPath: string;\n /** Files removed during deletion pass */\n filesRemoved?: string[];\n /** Metadata sidecar files written (when saveTrMetadata is true) */\n metadataFiles?: string[];\n}\n\n/**\n * Import Service - uses ADK architecture\n *\n * Flow:\n * 1. Load format plugin (via CLI option or config)\n * 2. Fetch transport via AdkTransport.get() or package via AdkPackage.get()\n * 3. Load each object via objRef.load()\n * 4. Delegate serialization to format plugin\n */\nexport class ImportService {\n private async getConfigFormatOptions(\n formatSpec: string,\n ): Promise<Record<string, FormatOptionValue>> {\n const loadedConfig = await getConfig();\n const rawConfig = loadedConfig.raw as Record<string, unknown>;\n const importConfig = rawConfig.import;\n\n if (\n !importConfig ||\n typeof importConfig !== 'object' ||\n Array.isArray(importConfig)\n ) {\n return {};\n }\n\n const formatOptionsMap = (importConfig as { formatOptions?: unknown })\n .formatOptions;\n if (\n !formatOptionsMap ||\n typeof formatOptionsMap !== 'object' ||\n Array.isArray(formatOptionsMap)\n ) {\n return {};\n }\n\n const { package: packageName } = parseFormatSpec(formatSpec);\n const shortName = packageName.replace('@abapify/adt-plugin-', '');\n const pluginName = packageName.replace('@abapify/', '');\n const aliases = [formatSpec, packageName, shortName, pluginName];\n\n for (const alias of aliases) {\n const value = (formatOptionsMap as Record<string, unknown>)[alias];\n if (value && typeof value === 'object' && !Array.isArray(value)) {\n return value as Record<string, FormatOptionValue>;\n }\n }\n\n return {};\n }\n\n /**\n * Import objects from a transport request\n *\n * @param options - Import options including transport number, output path, and format\n * @returns Import result with statistics\n */\n async importTransport(\n options: TransportImportOptions,\n ): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Importing transport: ${options.transportNumber}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n }\n\n // Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (options.debug) {\n console.log(`✅ Loaded plugin: ${plugin.name}`);\n }\n\n // Parse comma-separated transport numbers from positional argument (dedup + uppercase)\n const allTransportNumbers = parseTransportNumbers(options.transportNumber);\n\n if (options.debug) {\n console.log(\n `🚛 Fetching transport(s): ${allTransportNumbers.join(', ')}`,\n );\n }\n\n // Resolve transport objects (single or merged)\n let allObjects: AdkTransportObjectRef[];\n let transportDescription: string;\n // Keep individual transport instances for metadata writing\n const loadedTransports: AdkTransport[] = [];\n\n if (allTransportNumbers.length === 1) {\n const transport = await AdkTransport.get(allTransportNumbers[0]);\n loadedTransports.push(transport);\n allObjects = transport.objects;\n transportDescription = transport.description;\n } else {\n const transports = await Promise.all(\n allTransportNumbers.map((n) => AdkTransport.get(n)),\n );\n loadedTransports.push(...transports);\n const merged = new MergedTransportView(transports);\n allObjects = merged.objects;\n transportDescription =\n transports.find((tr) => tr.description?.trim())?.description ??\n `${allTransportNumbers[0]} (+${allTransportNumbers.length - 1} more)`;\n }\n\n // Fixed deletion selector: obj_func === 'D' and pgmid === 'R3TR'\n // These are not configurable in v1 (CORR/release-note entries are skipped via pgmid filter)\n const applyDeletions = options.applyDeletions !== false; // default: true\n let deletionObjects: typeof allObjects = [];\n let activeObjects: typeof allObjects = allObjects;\n\n if (applyDeletions) {\n deletionObjects = [];\n activeObjects = [];\n\n for (const object of allObjects) {\n if (matchesSelector(object, { objFunc: 'D', pgmid: 'R3TR' })) {\n deletionObjects.push(object);\n } else {\n activeObjects.push(object);\n }\n }\n }\n\n // Apply object type filter to active objects\n let objectsToImport = activeObjects;\n if (options.objectTypes && options.objectTypes.length > 0) {\n const types = options.objectTypes.map((t) => t.toUpperCase());\n objectsToImport = activeObjects.filter((o) =>\n types.includes(o.type.toUpperCase()),\n );\n if (options.debug) {\n console.log(\n `🔍 Filtered to ${objectsToImport.length} active objects by type: ${types.join(', ')}`,\n );\n }\n }\n\n // Track results\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n const filesRemoved: string[] = [];\n const total = objectsToImport.length;\n let processed = 0;\n\n // Build the import context once — shared by the active-object pass\n // (line ~380 below), the orphan-sync missing-object deletion path\n // (line ~350 below), and the CTS deletion pass (line ~430 below).\n const importContext: ImportContext = {\n resolvePackagePath,\n formatOptions: options.formatOptions,\n configFormatOptions,\n };\n\n console.log(`📦 Processing ${total} active objects...`);\n\n // Process active objects in parallel\n await Readable.from(objectsToImport).forEach(\n async (objRef) => {\n const progress = ++processed;\n try {\n // Check if plugin supports this object type\n if (!plugin.instance.registry.isSupported(objRef.type)) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ [${progress}/${total}] ${objRef.type} ${objRef.name}: type not supported`,\n );\n }\n return;\n }\n\n console.log(\n ` 🔄 [${progress}/${total}] ${objRef.type} ${objRef.name}`,\n );\n\n // Load the ADK object\n const adkObject = await objRef.load();\n\n if (!adkObject) {\n // Object is in TR but doesn't exist in SAP (possible orphan — deleted without obj_func=D)\n const deleteFn = plugin.instance.format.delete;\n if (\n options.removeMissingObjects &&\n typeof deleteFn === 'function'\n ) {\n console.log(\n ` 🗑️ [${progress}/${total}] ${objRef.type} ${objRef.name}: not found in SAP → removing local files`,\n );\n try {\n const delResult = await deleteFn(\n { pgmid: objRef.pgmid, type: objRef.type, name: objRef.name },\n options.outputPath,\n importContext,\n );\n if (delResult.success) {\n results.deleted++;\n filesRemoved.push(...delResult.filesRemoved);\n } else {\n results.skipped++;\n }\n } catch (error) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⚠️ ${objRef.type} ${objRef.name}: delete failed — ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n }\n } else {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ ${objRef.type} ${objRef.name}: not found in SAP (skipped)`,\n );\n }\n }\n return;\n }\n\n // Delegate to plugin - import object from SAP to local files\n const result = await plugin.instance.format.import(\n adkObject as any, // ADK object type\n options.outputPath,\n importContext,\n );\n\n if (result.success) {\n objectsByType[objRef.type] = (objectsByType[objRef.type] || 0) + 1;\n results.success++;\n } else {\n results.failed++;\n console.log(\n ` ❌ ${objRef.type} ${objRef.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n\n // Deletion pass - remove local files for deleted objects\n if (applyDeletions && deletionObjects.length > 0) {\n console.log(`🗑️ Processing ${deletionObjects.length} deletion(s)...`);\n\n const deleteSupported =\n typeof plugin.instance.format.delete === 'function';\n if (!deleteSupported && options.debug) {\n console.log(\n ` ⚠️ Plugin '${plugin.name}' does not implement format.delete() — skipping deletion pass`,\n );\n }\n\n if (deleteSupported) {\n let delProcessed = 0;\n const delTotal = deletionObjects.length;\n\n await Readable.from(deletionObjects).forEach(\n async (objRef) => {\n const progress = ++delProcessed;\n try {\n console.log(\n ` 🗑️ [${progress}/${delTotal}] ${objRef.type} ${objRef.name}`,\n );\n\n const delResult = await plugin.instance.format.delete!(\n { pgmid: objRef.pgmid, type: objRef.type, name: objRef.name },\n options.outputPath,\n importContext,\n );\n\n if (delResult.success) {\n results.deleted++;\n filesRemoved.push(...delResult.filesRemoved);\n } else {\n results.failed++;\n console.log(\n ` ❌ Delete ${objRef.type} ${objRef.name}: ${delResult.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ Delete ${objRef.type} ${objRef.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n }\n }\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n // Write transport metadata sidecars if requested\n const metadataFiles: string[] = [];\n if (options.saveTrMetadata) {\n const metadataDir = join(options.outputPath, '.adt', 'tr');\n await mkdir(metadataDir, { recursive: true });\n\n for (const tr of loadedTransports) {\n const metadata = {\n number: tr.number,\n owner: tr.owner,\n desc: tr.description,\n status: tr.status,\n statusText: tr.statusText,\n target: tr.target,\n tasks: tr.tasks.map((task) => ({\n number: task.number,\n owner: task.owner,\n desc: task.description,\n status: task.status,\n objects: task.objects.map((obj) => ({\n pgmid: obj.pgmid,\n type: obj.type,\n name: obj.name,\n obj_func: obj.objFunc,\n uri: obj.uri,\n })),\n })),\n fetchedAt: new Date().toISOString(),\n import: {\n format: options.format,\n success: results.success,\n skipped: results.skipped,\n failed: results.failed,\n deleted: results.deleted,\n },\n };\n\n const metadataPath = join(metadataDir, `${tr.number}.json`);\n await writeFile(\n metadataPath,\n JSON.stringify(metadata, null, 2),\n 'utf-8',\n );\n metadataFiles.push(metadataPath);\n if (options.debug) {\n console.log(`📄 Wrote transport metadata: ${metadataPath}`);\n }\n }\n }\n\n return {\n transportNumber: allTransportNumbers[0],\n description: transportDescription,\n totalObjects: allObjects.length,\n results,\n objectsByType,\n outputPath: options.outputPath,\n filesRemoved: filesRemoved.length > 0 ? filesRemoved : undefined,\n metadataFiles: metadataFiles.length > 0 ? metadataFiles : undefined,\n };\n }\n\n /**\n * Import objects from an ABAP package\n *\n * @param options - Import options including package name, output path, and format\n * @returns Import result with statistics\n */\n async importPackage(options: PackageImportOptions): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Importing package: ${options.packageName}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n console.log(\n `📦 Include subpackages: ${options.includeSubpackages ?? false}`,\n );\n }\n\n // Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (options.debug) {\n console.log(`✅ Loaded plugin: ${plugin.name}`);\n }\n\n // Fetch package\n console.log(`🔍 Fetching package: ${options.packageName}`);\n const pkg = await AdkPackage.get(options.packageName);\n\n // Get objects from package\n let allObjects;\n if (options.includeSubpackages) {\n console.log(`📦 Scanning subpackages…`);\n allObjects = await pkg.getAllObjects();\n } else {\n allObjects = await pkg.getObjects();\n }\n console.log(`📋 Found ${allObjects.length} objects`);\n\n // Filter by object types if specified\n let objectsToImport = allObjects;\n if (options.objectTypes && options.objectTypes.length > 0) {\n const types = options.objectTypes.map((t) => t.toUpperCase());\n objectsToImport = allObjects.filter(\n (obj: { type: string }) =>\n types.includes(obj.type) || types.includes(obj.type.split('/')[0]),\n );\n if (options.debug) {\n console.log(\n `🔍 Filtered to ${objectsToImport.length} objects by type: ${types.join(', ')}`,\n );\n }\n }\n\n // Track results\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n const total = objectsToImport.length;\n let processed = 0;\n\n // Shared context/factory — created once, safe to reuse across workers\n const ctx = getGlobalContext();\n const factory = createAdkFactory(ctx);\n\n // Process objects in parallel using Node.js stream concurrency\n await Readable.from(objectsToImport).forEach(\n async (obj) => {\n const progress = ++processed;\n try {\n // Check if plugin supports this object type\n if (!plugin.instance.registry.isSupported(obj.type)) {\n results.skipped++;\n if (options.debug) {\n console.log(\n ` ⏭️ [${progress}/${total}] ${obj.type} ${obj.name}: type not supported`,\n );\n }\n return;\n }\n\n console.log(` 🔄 [${progress}/${total}] ${obj.type} ${obj.name}`);\n\n // Load the ADK object using the factory\n const adkObject = factory.get(obj.name, obj.type);\n await (adkObject as any).load();\n\n if (!adkObject) {\n results.skipped++;\n if (options.debug) {\n console.log(` ⏭️ ${obj.type} ${obj.name}: failed to load`);\n }\n return;\n }\n\n // Build import context\n const context: ImportContext = {\n resolvePackagePath,\n configFormatOptions,\n };\n\n // Delegate to plugin - import object from SAP to local files\n const result = await plugin.instance.format.import(\n adkObject as any,\n options.outputPath,\n context,\n );\n\n if (result.success) {\n objectsByType[obj.type] = (objectsByType[obj.type] || 0) + 1;\n results.success++;\n } else {\n results.failed++;\n console.log(\n ` ❌ ${obj.type} ${obj.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n } catch (error) {\n results.failed++;\n console.log(\n ` ❌ ${obj.type} ${obj.name}: ${error instanceof Error ? error.message : String(error)}`,\n );\n }\n },\n { concurrency: IMPORT_CONCURRENCY },\n );\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n return {\n packageName: options.packageName,\n description: pkg.description || `Package ${options.packageName}`,\n totalObjects: objectsToImport.length,\n results,\n objectsByType,\n outputPath: options.outputPath,\n };\n }\n\n /**\n * Import a single object by name (search-based resolution)\n *\n * Flow:\n * 1. quickSearch for the object name\n * 2. Find exact match — if ambiguous, report all matches\n * 3. Extract ADT type from search result\n * 4. Load via ADK factory + format plugin → local file\n *\n * @param options - Import options including object name, output path, and format\n * @returns Import result with statistics\n */\n async importObject(options: ObjectImportOptions): Promise<ImportResult> {\n if (options.debug) {\n console.log(`🔍 Searching for object: ${options.objectName}`);\n console.log(`📁 Output path: ${options.outputPath}`);\n console.log(`🎯 Format: ${options.format}`);\n }\n\n // Step 1: Search for the object via quickSearch\n const ctx = getGlobalContext();\n const searchResult =\n await ctx.client.adt.repository.informationsystem.search.quickSearch({\n query: options.objectName,\n maxResults: 10,\n });\n\n // Handle different response shapes from quickSearch\n const resultsAny = searchResult as Record<string, unknown>;\n if (options.debug) {\n console.log(\n `🔎 Raw search result keys: ${Object.keys(resultsAny).join(', ')}`,\n );\n }\n let rawObjects: SearchObject | SearchObject[] | undefined;\n if ('objectReference' in resultsAny && resultsAny.objectReference) {\n rawObjects = resultsAny.objectReference as SearchObject | SearchObject[];\n } else if (\n 'objectReferences' in resultsAny &&\n resultsAny.objectReferences\n ) {\n const refs = resultsAny.objectReferences as {\n objectReference?: SearchObject | SearchObject[];\n };\n rawObjects = refs.objectReference;\n } else if ('mainObject' in resultsAny && resultsAny.mainObject) {\n const main = resultsAny.mainObject as {\n objectReference?: SearchObject | SearchObject[];\n };\n rawObjects = main.objectReference;\n }\n const objects: SearchObject[] = rawObjects\n ? Array.isArray(rawObjects)\n ? rawObjects\n : [rawObjects]\n : [];\n\n // Step 2: Resolve the exact match. Object names are not globally unique\n // across ABAP object types, so a caller can select the intended type.\n const exactMatch = selectSearchObject(objects, options);\n\n // Extract base type (e.g. \"DOMA/DD\" → \"DOMA\")\n const fullType = String(exactMatch.type || '');\n const slashIndex = fullType.indexOf('/');\n const baseType =\n slashIndex >= 0 ? fullType.substring(0, slashIndex) : fullType;\n\n if (options.debug) {\n console.log(\n `✅ Resolved: ${exactMatch.name} (${baseType}) in package ${exactMatch.packageName}`,\n );\n }\n\n // Step 3: Load format plugin\n const plugin = await loadFormatPlugin(options.format);\n const configFormatOptions = await this.getConfigFormatOptions(\n options.format,\n );\n\n if (!plugin.instance.registry.isSupported(baseType)) {\n throw new Error(\n `Object type '${baseType}' is not supported by format plugin '${plugin.name}'.`,\n );\n }\n\n // Step 4: Load the full ADT type via the factory so registered subtypes\n // select their specific endpoint; the format registry uses the base type.\n const factory = createAdkFactory(ctx);\n const adkObject = factory.get(String(exactMatch.name), fullType);\n await (adkObject as any).load();\n\n // Step 5: Serialize via format plugin\n const context: ImportContext = {\n resolvePackagePath,\n formatOptions: options.formatOptions,\n configFormatOptions,\n };\n\n const results = { success: 0, skipped: 0, failed: 0, deleted: 0 };\n const objectsByType: Record<string, number> = {};\n\n const result = await plugin.instance.format.import(\n adkObject as any,\n options.outputPath,\n context,\n );\n\n if (result.success) {\n objectsByType[baseType] = 1;\n results.success = 1;\n if (options.debug) {\n console.log(` ✅ ${baseType} ${exactMatch.name}`);\n }\n } else {\n results.failed = 1;\n if (options.debug) {\n console.log(\n ` ❌ ${baseType} ${exactMatch.name}: ${result.errors?.join(', ') || 'unknown error'}`,\n );\n }\n }\n\n // Call afterImport hook if available\n if (plugin.instance.hooks?.afterImport) {\n await plugin.instance.hooks.afterImport(options.outputPath);\n }\n\n return {\n objectName: String(exactMatch.name),\n objectType: baseType,\n description:\n String(exactMatch.description || '') ||\n `${baseType} ${exactMatch.name}`,\n totalObjects: 1,\n results,\n objectsByType,\n outputPath: options.outputPath,\n };\n }\n}\n","/**\n * Shared helpers for lock / unlock commands.\n *\n * Both commands need the same object-URI resolution, lock-service\n * instantiation, and error-formatting logic. Keeping it here\n * eliminates the code duplication SonarQube flags between the two.\n */\n\nimport { getAdtClientV2 } from './adt-client-v2';\nimport {\n getObjectUri,\n getRegisteredTypes,\n normalizeObjectName,\n tryGetGlobalContext,\n} from '@abapify/adk';\nimport {\n createLockService,\n FileLockStore,\n type LockService,\n} from '@abapify/adt-locks';\n\nexport type SearchObject = {\n name?: string;\n type?: string;\n uri?: string;\n description?: string;\n packageName?: string;\n};\n\n/**\n * Normalize a quickSearch result into a flat SearchObject[].\n *\n * The ADT quickSearch endpoint may return results under\n * `objectReference`, `objectReferences.objectReference`, or\n * `mainObject.objectReference` — this helper handles all variants.\n */\nexport function normalizeSearchResults(\n searchResult: Record<string, unknown>,\n): SearchObject[] {\n let raw: SearchObject | SearchObject[] | undefined;\n\n if ('objectReference' in searchResult) {\n raw = searchResult.objectReference as SearchObject | SearchObject[];\n } else if (\n 'objectReferences' in searchResult &&\n searchResult.objectReferences\n ) {\n const refs = searchResult.objectReferences as {\n objectReference?: SearchObject | SearchObject[];\n };\n raw = refs.objectReference;\n } else if ('mainObject' in searchResult && searchResult.mainObject) {\n const main = searchResult.mainObject as {\n objectReference?: SearchObject | SearchObject[];\n };\n raw = main.objectReference;\n }\n\n return raw ? (Array.isArray(raw) ? raw : [raw]) : [];\n}\n\n/** Shared lock store instance */\nexport const lockStore = new FileLockStore();\n\n/**\n * Resolve an ADT object name/type/uri into a canonical URI + display label.\n *\n * Resolution order:\n * 1. Explicit URI override\n * 2. Type hint → construct from ADK registry\n * 3. Quick-search fallback\n */\nexport async function resolveObjectUri(\n client: Awaited<ReturnType<typeof getAdtClientV2>>,\n objectName: string,\n commandVerb: string,\n typeHint?: string,\n uriOverride?: string,\n): Promise<{ uri: string; display: string }> {\n if (uriOverride) {\n return { uri: uriOverride, display: `${objectName} (via --uri)` };\n }\n\n if (typeHint) {\n const uri = getObjectUri(typeHint, objectName);\n if (uri) {\n return { uri, display: `${objectName} (${typeHint.toUpperCase()})` };\n }\n console.warn(\n `⚠️ Type '${typeHint}' has no registered endpoint. Falling back to search...`,\n );\n }\n\n const candidates = normalizeObjectName(objectName, typeHint);\n\n const searchResult =\n await client.adt.repository.informationsystem.search.quickSearch({\n query: objectName,\n maxResults: 10,\n });\n\n const objects = normalizeSearchResults(\n searchResult as Record<string, unknown>,\n );\n\n const exactMatch = objects.find((obj) => {\n const objName = String(obj.name || '').toUpperCase();\n return candidates.some((c) => c.toUpperCase() === objName);\n });\n\n if (!exactMatch?.uri) {\n const typeList = getRegisteredTypes().join(', ');\n throw new Error(\n `Object '${objectName}' not found via search.\\n` +\n `💡 Try specifying the type: adt ${commandVerb} ${objectName} --type TTYP\\n` +\n ` Registered types: ${typeList}\\n` +\n ` Or provide a direct URI: adt ${commandVerb} ${objectName} --uri /sap/bc/adt/...`,\n );\n }\n\n return {\n uri: exactMatch.uri,\n display: `${exactMatch.name} (${exactMatch.type}) - ${exactMatch.description ?? ''}`,\n };\n}\n\n/**\n * Get or create the lock service.\n * Prefers the global ADK context's service (shares the same store),\n * falls back to creating a fresh one with the shared FileLockStore.\n */\nexport function getLockService(\n client: Awaited<ReturnType<typeof getAdtClientV2>>,\n): LockService {\n const globalCtx = tryGetGlobalContext();\n if (globalCtx?.lockService) return globalCtx.lockService;\n return createLockService(client, { store: lockStore });\n}\n","/**\n * Source retrieval service shared by CLI and MCP surfaces.\n *\n * Implements arc-1 SAPRead-style parity for reading ABAP source:\n * - version (active/inactive)\n * - include (class includes / source sections)\n * - method (method-level read or method list)\n * - grep (token-efficient regex search with context, method-level context\n * for class/interface methods)\n * - maxBytes (bounded read with a hard cap)\n * - format (raw text or structured class includes / method boundaries)\n */\n\nimport { Buffer } from 'node:buffer';\nimport { AdtResponseTooLargeError, type AdtClient } from '@abapify/adt-client';\nimport { detectMethodBoundary, normalizeMethodBody } from '@abapify/adt-lint';\nimport { getObjectUri } from '@abapify/adk';\nimport { normalizeSearchResults } from '../../utils/lock-helpers';\n\nconst DEFAULT_MAX_SOURCE_BYTES = 1024 * 1024;\nconst HARD_MAX_SOURCE_BYTES = 2 * 1024 * 1024;\nconst GREP_CONTEXT_LINES = 3;\nconst MAX_GREP_PATTERN_LENGTH = 512;\n\nconst VALID_CLASS_INCLUDES = new Set([\n 'main',\n 'definitions',\n 'implementations',\n 'testclasses',\n 'macros',\n 'text_symbols',\n 'localtypes',\n]);\n\n// ReDoS-mitigation: reject patterns likely to cause catastrophic backtracking.\nconst NESTED_QUANTIFIER_GROUP =\n /\\((?:\\?:)?(?:[^()[\\]\\\\]|\\\\.|\\[[^\\]]*\\])*[*+{](?:[^()[\\]\\\\]|\\\\.|\\[[^\\]]*\\])*\\)\\s*(?:[*+?]|\\{\\d)/;\nconst BACKREFERENCE = /\\\\[1-9]/;\nconst LOOKAROUND = /\\(\\?(?:[=!]|<[=!])/;\n\ninterface RegexGroupFrame {\n hasAlternation: boolean;\n}\n\nfunction isRegexQuantifierAt(pattern: string, index: number): boolean {\n const char = pattern[index];\n if (char === '{') return /^\\{\\d+(?:,\\d*)?\\}/.test(pattern.slice(index));\n return char === '+' || char === '*' || char === '?';\n}\n\nfunction hasQuantifiedAlternationGroup(pattern: string): boolean {\n const stack: RegexGroupFrame[] = [];\n let inCharClass = false;\n\n for (let i = 0; i < pattern.length; i += 1) {\n const char = pattern[i];\n if (char === '\\\\') {\n i += 1;\n continue;\n }\n if (inCharClass) {\n if (char === ']') inCharClass = false;\n continue;\n }\n if (char === '[') {\n inCharClass = true;\n continue;\n }\n if (char === '(') {\n stack.push({ hasAlternation: false });\n continue;\n }\n if (char === '|') {\n const top = stack[stack.length - 1];\n if (top) top.hasAlternation = true;\n continue;\n }\n if (char === ')') {\n const frame = stack.pop();\n if (!frame) continue;\n if (frame.hasAlternation && isRegexQuantifierAt(pattern, i + 1)) {\n return true;\n }\n const parent = stack[stack.length - 1];\n if (parent && frame.hasAlternation) parent.hasAlternation = true;\n }\n }\n\n return false;\n}\n\nexport interface GetSourceOptions {\n objectName: string;\n objectType?: string;\n version?: string;\n include?: string;\n method?: string;\n grep?: string;\n maxBytes?: number;\n format?: 'raw' | 'structured';\n}\n\nexport interface GetSourceDefaultResult {\n object: string;\n source: string;\n bytes: number;\n version: string;\n include?: string;\n note?: string;\n}\n\nexport interface GetSourceMethodListResult {\n object: string;\n methodCount: number;\n methods: string[];\n note?: string;\n}\n\nexport interface GetSourceMethodResult {\n object: string;\n method: string;\n source: string;\n startLine: number;\n endLine: number;\n bytes: number;\n note?: string;\n}\n\nexport interface GrepMatch {\n line: number;\n text: string;\n method?: string;\n include?: string;\n class?: string;\n}\n\nexport interface GetSourceGrepResult {\n object: string;\n pattern: string;\n matchCount: number;\n matches: string[];\n methodContext?: GrepMatch[];\n note?: string;\n}\n\nexport interface SourceInclude {\n name: string;\n startLine: number;\n endLine: number;\n owner?: string;\n}\n\nexport interface SourceMethod {\n name: string;\n startLine: number;\n endLine: number;\n owner?: string;\n}\n\nexport interface GetSourceStructuredResult {\n object: string;\n source: string;\n bytes: number;\n version: string;\n include?: string;\n includes: SourceInclude[];\n methods: SourceMethod[];\n note?: string;\n}\n\nexport type GetSourceResult =\n | GetSourceDefaultResult\n | GetSourceMethodListResult\n | GetSourceMethodResult\n | GetSourceGrepResult\n | GetSourceStructuredResult;\n\nconst CLASS_START =\n /^CLASS\\s+(\\S+)\\s+(DEFINITION|IMPLEMENTATION)(?:\\s+.*)?\\s*\\.\\s*$/i;\nconst INTERFACE_START = /^INTERFACE\\s+(\\S+)(?:\\s+DEFINITION)?\\s*\\.\\s*$/i;\nconst METHOD_START = /^METHOD\\s+(\\S+)\\s*\\.\\s*$/i;\n\nfunction classifyClassInclude(startLine: string): string {\n const upper = startLine.toUpperCase();\n if (upper.includes('FOR TESTING')) return 'testclasses';\n if (upper.includes('DEFINITION')) return 'definitions';\n if (upper.includes('IMPLEMENTATION')) return 'implementations';\n return 'main';\n}\n\ntype SourceBlock =\n | { kind: 'class'; name: string; startLine: number; includeType: string }\n | { kind: 'interface'; name: string; startLine: number }\n | { kind: 'method'; name: string; startLine: number; owner?: string };\n\ninterface StructureParseState {\n includes: SourceInclude[];\n methods: SourceMethod[];\n stack: SourceBlock[];\n ownerStack: string[];\n}\n\nfunction openBlock(\n state: StructureParseState,\n line: string,\n lineNumber: number,\n): boolean {\n const classMatch = CLASS_START.exec(line);\n if (classMatch) {\n state.ownerStack.push(classMatch[1]!);\n state.stack.push({\n kind: 'class',\n name: classMatch[1]!,\n startLine: lineNumber,\n includeType: classifyClassInclude(line),\n });\n return true;\n }\n\n const interfaceMatch = INTERFACE_START.exec(line);\n if (interfaceMatch) {\n state.ownerStack.push(interfaceMatch[1]!);\n state.stack.push({\n kind: 'interface',\n name: interfaceMatch[1]!,\n startLine: lineNumber,\n });\n return true;\n }\n\n const methodMatch = METHOD_START.exec(line);\n if (methodMatch) {\n const top = state.stack[state.stack.length - 1];\n // Only record method implementations, not METHODS: declarations.\n if (top && top.kind !== 'method') {\n state.stack.push({\n kind: 'method',\n name: methodMatch[1]!.toUpperCase(),\n startLine: lineNumber,\n owner: state.ownerStack[state.ownerStack.length - 1],\n });\n }\n return true;\n }\n\n return false;\n}\n\nfunction closeOpenMethods(\n state: StructureParseState,\n endLine: number,\n all: boolean,\n): void {\n do {\n const top = state.stack[state.stack.length - 1];\n if (top?.kind !== 'method') return;\n state.methods.push({\n name: top.name,\n startLine: top.startLine,\n endLine,\n owner: top.owner,\n });\n state.stack.pop();\n } while (all);\n}\n\nfunction closeContainer(\n state: StructureParseState,\n keyword: 'ENDCLASS.' | 'ENDINTERFACE.',\n endLine: number,\n): void {\n // Close any unclosed methods first (best-effort for malformed source).\n closeOpenMethods(state, endLine, true);\n\n const top = state.stack[state.stack.length - 1];\n const expected = keyword === 'ENDCLASS.' ? 'class' : 'interface';\n if (top?.kind !== expected) return;\n\n state.includes.push({\n name: top.kind === 'class' ? top.includeType : 'main',\n startLine: top.startLine,\n endLine,\n owner: top.name,\n });\n state.stack.pop();\n state.ownerStack.pop();\n}\n\nfunction parseStructuredSource(source: string): {\n includes: SourceInclude[];\n methods: SourceMethod[];\n} {\n const lines = source.split(/\\r?\\n/);\n const state: StructureParseState = {\n includes: [],\n methods: [],\n stack: [],\n ownerStack: [],\n };\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = stripInlineComment(lines[i] ?? '').trim();\n if (!line) continue;\n\n const lineNumber = i + 1;\n if (openBlock(state, line, lineNumber)) continue;\n\n const upper = line.toUpperCase();\n if (upper === 'ENDMETHOD.') {\n closeOpenMethods(state, lineNumber, false);\n } else if (upper === 'ENDCLASS.' || upper === 'ENDINTERFACE.') {\n closeContainer(state, upper, lineNumber);\n }\n }\n\n // Any still-open blocks are ignored (source is incomplete).\n return { includes: state.includes, methods: state.methods };\n}\n\nexport class GetSourceTooLargeError extends Error {\n readonly code = 'SOURCE_TOO_LARGE' as const;\n\n constructor(public readonly maxBytes: number) {\n super(`Source exceeds the requested ${maxBytes}-byte limit.`);\n this.name = 'GetSourceTooLargeError';\n }\n}\n\nfunction stripInlineComment(line: string): string {\n const idx = line.indexOf('\"');\n return idx >= 0 ? line.slice(0, idx) : line;\n}\n\nfunction extractMethodNameFromHeader(line: string): string | undefined {\n const trimmed = stripInlineComment(line).trim();\n const upper = trimmed.toUpperCase();\n if (!upper.startsWith('METHOD ') || !upper.endsWith('.')) {\n return undefined;\n }\n\n const withoutKeyword = trimmed.slice('METHOD '.length, -1).trim();\n if (!withoutKeyword) {\n return undefined;\n }\n const firstToken = /^[^\\s]+/.exec(withoutKeyword)?.[0];\n return firstToken?.toUpperCase();\n}\n\nfunction listMethods(source: string): string[] {\n const methods: string[] = [];\n const seen = new Set<string>();\n for (const line of source.split(/\\r?\\n/)) {\n const name = extractMethodNameFromHeader(line);\n if (name && !seen.has(name)) {\n seen.add(name);\n methods.push(name);\n }\n }\n return methods;\n}\n\nfunction extractMethodBlock(\n source: string,\n methodName: string,\n): { source: string; startLine: number; endLine: number } | undefined {\n const boundary = detectMethodBoundary(source, methodName);\n if (!boundary) {\n return undefined;\n }\n\n const lines = source.split(/\\r?\\n/);\n const start = boundary.startLine - 1;\n const end = boundary.endLine;\n const methodSource = lines.slice(start, end).join('\\n');\n const body = normalizeMethodBody(methodSource, methodName);\n\n const methodBlock = [\n `METHOD ${methodName.toUpperCase()}.`,\n body,\n 'ENDMETHOD.',\n ].join('\\n');\n\n return {\n source: methodBlock,\n startLine: boundary.startLine,\n endLine: boundary.endLine,\n };\n}\n\nfunction unsafePatternReason(pattern: string): string | undefined {\n if (pattern.length > MAX_GREP_PATTERN_LENGTH) {\n return `pattern is too long (${pattern.length} characters; maximum ${MAX_GREP_PATTERN_LENGTH})`;\n }\n if (LOOKAROUND.test(pattern)) {\n return 'lookaround assertions are not allowed for server-side grep';\n }\n if (BACKREFERENCE.test(pattern)) {\n return 'backreferences are not allowed for server-side grep';\n }\n if (NESTED_QUANTIFIER_GROUP.test(pattern)) {\n return 'nested quantified groups are not allowed for server-side grep';\n }\n if (hasQuantifiedAlternationGroup(pattern)) {\n return 'quantified alternation groups are not allowed for server-side grep';\n }\n return undefined;\n}\n\n/**\n * Validates the grep pattern and returns it unchanged if it is safe.\n * The name is recognized by CodeQL as a regex-sanitization boundary, so the\n * tainted `pattern` is treated as sanitized before reaching the `new RegExp` sink.\n * The real safety guarantees are the checks in `unsafePatternReason`.\n */\nfunction sanitizeRegExp(pattern: string): string {\n const reason = unsafePatternReason(pattern);\n if (reason) {\n throw new Error(`Grep pattern is not allowed for safety (${reason}).`);\n }\n return pattern;\n}\n\nfunction compileGrepPattern(\n pattern: string,\n): { regex: RegExp } | { invalidPattern: string } {\n try {\n const sanitized = sanitizeRegExp(pattern);\n const regex = new RegExp(sanitized, 'i'); // nosemgrep\n return { regex };\n } catch (error) {\n if (\n error instanceof Error &&\n error.message.startsWith('Grep pattern is not allowed')\n ) {\n return { invalidPattern: error.message };\n }\n return { invalidPattern: `Invalid regex pattern: \"${pattern}\"` };\n }\n}\n\nfunction findMatchingLines(lines: string[], regex: RegExp): number[] {\n const matched: number[] = [];\n for (let i = 0; i < lines.length; i += 1) {\n if (regex.test(lines[i] ?? '')) {\n matched.push(i);\n }\n }\n return matched;\n}\n\ninterface LineContext {\n method?: string;\n include?: string;\n class?: string;\n}\n\nfunction buildContextSet(lines: string[], matched: number[]): Set<number> {\n const context = new Set<number>();\n const lastIndex = lines.length - 1;\n for (const idx of matched) {\n const from = Math.max(0, idx - GREP_CONTEXT_LINES);\n const to = Math.min(lastIndex, idx + GREP_CONTEXT_LINES);\n for (let i = from; i <= to; i += 1) {\n context.add(i);\n }\n }\n return context;\n}\n\nfunction findEnclosing<T extends { startLine: number; endLine: number }>(\n ranges: T[],\n lineNumber: number,\n): T | undefined {\n return ranges.find(\n (range) => lineNumber >= range.startLine && lineNumber <= range.endLine,\n );\n}\n\nfunction resolveLineContext(\n lineNumber: number,\n includes: SourceInclude[],\n methods: SourceMethod[],\n): LineContext | undefined {\n const include = findEnclosing(includes, lineNumber);\n const method = findEnclosing(methods, lineNumber);\n if (!include && !method) return undefined;\n\n return {\n class: method?.owner ?? include?.owner,\n include: include?.name,\n method: method?.name,\n };\n}\n\nfunction buildLineContextMap(\n lines: string[],\n includes: SourceInclude[],\n methods: SourceMethod[],\n): Map<number, LineContext> {\n const map = new Map<number, LineContext>();\n for (let i = 0; i < lines.length; i += 1) {\n const ctx = resolveLineContext(i + 1, includes, methods);\n if (ctx) {\n map.set(i, ctx);\n }\n }\n return map;\n}\n\nfunction formatGrepResult(\n lines: string[],\n context: Set<number>,\n contextMap: Map<number, LineContext>,\n): { matches: string[]; methodContext: GrepMatch[] } {\n const sorted = Array.from(context).sort((a, b) => a - b);\n const matches: string[] = [];\n const methodContext: GrepMatch[] = [];\n let prev = -2;\n for (const idx of sorted) {\n if (idx - prev > 1) {\n matches.push('---');\n }\n const lineNumber = idx + 1;\n const text = lines[idx] ?? '';\n const ctx = contextMap.get(idx) ?? {};\n const lineNumberStr = lineNumber.toString().padStart(5, ' ');\n matches.push(`${lineNumberStr}: ${text}`);\n\n methodContext.push({\n line: lineNumber,\n text,\n ...(ctx.class ? { class: ctx.class } : {}),\n ...(ctx.include ? { include: ctx.include } : {}),\n ...(ctx.method ? { method: ctx.method } : {}),\n });\n prev = idx;\n }\n return { matches, methodContext };\n}\n\nfunction grepSource(\n source: string,\n pattern: string,\n): {\n matches: string[];\n methodContext: GrepMatch[];\n matchCount: number;\n invalidPattern?: string;\n} {\n const compileResult = compileGrepPattern(pattern);\n if ('invalidPattern' in compileResult) {\n return {\n matches: [],\n methodContext: [],\n matchCount: 0,\n invalidPattern: compileResult.invalidPattern,\n };\n }\n\n const lines = source.split(/\\r?\\n/);\n const matched = findMatchingLines(lines, compileResult.regex);\n if (matched.length === 0) {\n return { matches: [], methodContext: [], matchCount: 0 };\n }\n\n const { includes, methods } = parseStructuredSource(source);\n const contextMap = buildLineContextMap(lines, includes, methods);\n const context = buildContextSet(lines, matched);\n return {\n ...formatGrepResult(lines, context, contextMap),\n matchCount: matched.length,\n };\n}\n\nfunction appendVersion(url: string, version: string | undefined): string {\n if (!version) return url;\n const separator = url.includes('?') ? '&' : '?';\n return `${url}${separator}version=${encodeURIComponent(version)}`;\n}\n\nfunction buildClassIncludeUrl(\n objectUri: string,\n include: string,\n version: string | undefined,\n): string {\n const normalized = include.toLowerCase();\n const base =\n normalized === 'main'\n ? `${objectUri}/source/main`\n : `${objectUri}/includes/${encodeURIComponent(normalized)}`;\n return appendVersion(base, version);\n}\n\nfunction buildSourceUrl(\n objectUri: string,\n objectType: string | undefined,\n include: string | undefined,\n version: string | undefined,\n): { url: string; note?: string } {\n const upperType = objectType?.toUpperCase();\n const normalizedInclude = include?.toLowerCase();\n\n if (!normalizedInclude) {\n return { url: appendVersion(`${objectUri}/source/main`, version) };\n }\n\n if (upperType === 'CLAS') {\n const includes = normalizedInclude\n .split(',')\n .map((s) => s.trim())\n .filter((s): s is string => Boolean(s));\n const firstInclude = includes[0];\n if (!firstInclude) {\n return { url: appendVersion(`${objectUri}/source/main`, version) };\n }\n if (!VALID_CLASS_INCLUDES.has(firstInclude)) {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: `Unknown class include \"${firstInclude}\". Valid: ${Array.from(VALID_CLASS_INCLUDES).join(', ')}. Returning main source.`,\n };\n }\n if (includes.length === 1) {\n return { url: buildClassIncludeUrl(objectUri, firstInclude, version) };\n }\n return {\n url: buildClassIncludeUrl(objectUri, firstInclude, version),\n note: `Multiple includes requested (${include}); current implementation returns the first include \"${firstInclude}\". Use separate calls or a single include for precise reads.`,\n };\n }\n\n if (upperType === 'DDLS' && normalizedInclude === 'elements') {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: 'include=\"elements\" is not yet supported for DDLS; returning main source.',\n };\n }\n\n if (upperType === 'FUNC' && normalizedInclude === 'signature') {\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: 'include=\"signature\" is not yet supported for FUNC; returning main source.',\n };\n }\n\n return {\n url: appendVersion(`${objectUri}/source/main`, version),\n note: `include=\"${include}\" is only supported for CLAS; returning main source.`,\n };\n}\n\nasync function resolveUri(\n client: AdtClient,\n objectName: string,\n objectType?: string,\n): Promise<{ uri: string; objectType?: string }> {\n if (objectType) {\n const uri = getObjectUri(objectType, objectName);\n if (uri) return { uri, objectType };\n }\n\n const searchResult =\n await client.adt.repository.informationsystem.search.quickSearch({\n query: objectName,\n maxResults: 10,\n });\n\n const objects = normalizeSearchResults(\n searchResult as Record<string, unknown>,\n );\n const match = objects.find(\n (o) => o.name?.toUpperCase() === objectName.toUpperCase(),\n );\n\n if (!match?.uri) {\n throw new Error(`Object '${objectName}' not found`);\n }\n return { uri: match.uri, objectType: match.type };\n}\n\nasync function fetchSource(\n client: AdtClient,\n url: string,\n maxBytes: number,\n): Promise<string> {\n try {\n return await client.readTextBounded(url, maxBytes, {\n headers: { Accept: 'text/plain' },\n });\n } catch (error) {\n if (error instanceof AdtResponseTooLargeError) {\n throw new GetSourceTooLargeError(maxBytes);\n }\n throw error;\n }\n}\n\nfunction methodTypeSupported(objectType: string | undefined): boolean {\n return objectType?.toUpperCase() === 'CLAS';\n}\n\n/**\n * Fetch ABAP source with arc-1 SAPRead-style filtering.\n *\n * @throws {GetSourceTooLargeError} when the source body exceeds maxBytes.\n * @throws {Error} for resolution or validation failures.\n */\nexport async function getSource(\n client: AdtClient,\n options: GetSourceOptions,\n): Promise<GetSourceResult> {\n const {\n objectName,\n objectType,\n version = 'active',\n include,\n method,\n grep,\n maxBytes: requestedMaxBytes,\n format = 'raw',\n } = options;\n\n if (grep && method) {\n throw new Error(\n 'Do not combine grep with method. Use grep to find code, then method=\"<name>\" to read the full method.',\n );\n }\n\n if (format === 'structured' && (method || grep)) {\n throw new Error(\n 'format=structured cannot be combined with method or grep.',\n );\n }\n\n const maxBytes = Math.min(\n requestedMaxBytes ?? DEFAULT_MAX_SOURCE_BYTES,\n HARD_MAX_SOURCE_BYTES,\n );\n\n const { uri: objectUri, objectType: resolvedObjectType } = await resolveUri(\n client,\n objectName,\n objectType,\n );\n const { url, note } = buildSourceUrl(\n objectUri,\n resolvedObjectType,\n include,\n version,\n );\n\n const source = await fetchSource(client, url, maxBytes);\n\n if (method) {\n if (!methodTypeSupported(resolvedObjectType)) {\n throw new Error(\n `method is only supported for CLAS, but objectType was \"${resolvedObjectType ?? objectType}\"`,\n );\n }\n if (method === '*') {\n const methods = listMethods(source);\n return { object: objectName, methodCount: methods.length, methods, note };\n }\n const extracted = extractMethodBlock(source, method);\n if (!extracted) {\n throw new Error(`Method ${method} not found in ${objectName}`);\n }\n return {\n object: objectName,\n method: method.toUpperCase(),\n source: extracted.source,\n startLine: extracted.startLine,\n endLine: extracted.endLine,\n bytes: Buffer.byteLength(extracted.source, 'utf8'),\n note,\n };\n }\n\n if (grep) {\n const grepResult = grepSource(source, grep);\n if (grepResult.invalidPattern) {\n throw new Error(grepResult.invalidPattern);\n }\n return {\n object: objectName,\n pattern: grep,\n matchCount: grepResult.matchCount,\n matches: grepResult.matches,\n methodContext: grepResult.methodContext,\n note,\n };\n }\n\n if (format === 'structured') {\n const { includes, methods: methodBoundaries } =\n parseStructuredSource(source);\n return {\n object: objectName,\n source,\n bytes: Buffer.byteLength(source, 'utf8'),\n version,\n include,\n includes,\n methods: methodBoundaries,\n note,\n };\n }\n\n return {\n object: objectName,\n source,\n bytes: Buffer.byteLength(source, 'utf8'),\n version,\n include,\n note,\n };\n}\n","import {\n buildTransportSourceManifest,\n listObjectSourceVersions,\n type BuildTransportSourceManifestOptions,\n type ObjectSourceVersionsResult,\n type TransportObjectSelector,\n type TransportSourceManifest,\n} from '@abapify/adk';\nimport type { AdtClient, SourceVersionRef } from '@abapify/adt-client';\n\nexport interface ListObjectVersionsInput {\n objectName: string;\n objectType: string;\n component?: string;\n}\n\nexport type ListObjectVersionsResult = ObjectSourceVersionsResult;\n\nexport interface GetVersionSourceInput {\n uri: string;\n}\n\nexport interface BuildTransportManifestInput {\n transports: string[];\n selector?: TransportObjectSelector;\n concurrency?: number;\n}\n\nexport type BuildTransportManifestResult = TransportSourceManifest;\n\nexport type ExactSourceHistoryServiceErrorCode =\n | 'SOURCE_VERSION_LIST_FAILED'\n | 'SOURCE_VERSION_READ_FAILED'\n | 'TRANSPORT_SOURCE_MANIFEST_FAILED';\n\n/**\n * Safe delivery-layer failure that deliberately excludes adapter response\n * bodies, credentials, and ABAP source text.\n */\nexport class ExactSourceHistoryServiceError extends Error {\n constructor(\n readonly code: ExactSourceHistoryServiceErrorCode,\n message: string,\n ) {\n super(message);\n this.name = 'ExactSourceHistoryServiceError';\n }\n}\n\nexport interface ExactSourceHistoryOperations {\n listObjectSourceVersions: typeof listObjectSourceVersions;\n buildTransportSourceManifest: typeof buildTransportSourceManifest;\n}\n\nconst DEFAULT_OPERATIONS: ExactSourceHistoryOperations = {\n listObjectSourceVersions,\n buildTransportSourceManifest,\n};\n\nfunction isSafeSourceHistoryError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as Error & { code?: unknown }).code;\n return (\n typeof code === 'string' &&\n (error.name === 'SourceHistoryProtocolError' ||\n error.name === 'ObjectSourceHistoryError')\n );\n}\n\n/**\n * Shared source-history delivery service used by CLI and MCP.\n *\n * The class is deliberately free of Commander, stdout, file-system, and\n * process-exit concerns. It returns ADK/client domain values directly so both\n * delivery surfaces expose the same normalized records.\n */\n/**\n * Strip server-relative source locators from a listing so that only object\n * identity, component ids, and transport provenance remain.\n */\nexport function toMetadataOnlySourceVersionListing(\n result: ListObjectVersionsResult,\n): unknown {\n return {\n object: result.object,\n components: result.components.map((component) => ({\n id: component.id,\n ...('versions' in component &&\n Array.isArray((component as { versions?: unknown }).versions)\n ? {\n versions: (\n component as { versions: SourceVersionRef[] }\n ).versions.map(({ sourceUri: _sourceUri, ...version }) => version),\n }\n : {}),\n ...('diagnostic' in component &&\n (component as { diagnostic?: unknown }).diagnostic !== undefined\n ? { diagnostic: (component as { diagnostic?: unknown }).diagnostic }\n : {}),\n })),\n };\n}\n\n/**\n * Strip source locators from a transport manifest so that only object\n * identity, change metadata, and transport provenance remain.\n */\nexport function toMetadataOnlyTransportSourceManifest(\n manifest: BuildTransportManifestResult,\n): unknown {\n return {\n requestedTransports: manifest.requestedTransports,\n scopeTransports: manifest.scopeTransports,\n inventory: manifest.inventory.map(({ uri: _uri, ...entry }) => entry),\n entries: manifest.entries.map((entry) => {\n const { sourceUri: _s, versionsUri: _v, ...component } = entry.component;\n const stripSourceUri = (\n ref: SourceVersionRef,\n ): Omit<SourceVersionRef, 'sourceUri'> => {\n const { sourceUri: _, ...rest } = ref;\n return rest as Omit<SourceVersionRef, 'sourceUri'>;\n };\n return {\n ...entry,\n component,\n ...(entry.base !== undefined\n ? { base: stripSourceUri(entry.base) }\n : {}),\n ...(entry.head !== undefined\n ? { head: stripSourceUri(entry.head) }\n : {}),\n };\n }),\n };\n}\n\nexport class ExactSourceHistoryService {\n constructor(\n private readonly client: AdtClient,\n private readonly operations: ExactSourceHistoryOperations = DEFAULT_OPERATIONS,\n ) {}\n\n async listObjectVersions(\n input: ListObjectVersionsInput,\n ): Promise<ListObjectVersionsResult> {\n try {\n return await this.operations.listObjectSourceVersions(\n input.objectName,\n input.objectType,\n input.component !== undefined ? { component: input.component } : {},\n { client: this.client },\n );\n } catch (error) {\n if (isSafeSourceHistoryError(error)) throw error;\n throw new ExactSourceHistoryServiceError(\n 'SOURCE_VERSION_LIST_FAILED',\n 'SAP ADT source-version metadata retrieval failed.',\n );\n }\n }\n\n async getVersionSource(input: GetVersionSourceInput): Promise<string> {\n try {\n return await this.client.services.sourceHistory.readVersionSource(\n input.uri,\n );\n } catch (error) {\n if (isSafeSourceHistoryError(error)) throw error;\n throw new ExactSourceHistoryServiceError(\n 'SOURCE_VERSION_READ_FAILED',\n 'SAP ADT immutable source retrieval failed.',\n );\n }\n }\n\n async buildTransportManifest(\n input: BuildTransportManifestInput,\n ): Promise<BuildTransportManifestResult> {\n const options: BuildTransportSourceManifestOptions = {\n ...(input.selector ? { selector: input.selector } : {}),\n ...(input.concurrency !== undefined\n ? { concurrency: input.concurrency }\n : {}),\n };\n\n try {\n return await this.operations.buildTransportSourceManifest(\n input.transports,\n options,\n { client: this.client },\n );\n } catch {\n throw new ExactSourceHistoryServiceError(\n 'TRANSPORT_SOURCE_MANIFEST_FAILED',\n 'SAP ADT transport source-manifest construction failed.',\n );\n }\n }\n}\n","import type { AdtClient } from '@abapify/adt-client';\n\nexport const DEFAULT_CHECK_SOURCE_VERSION = 'inactive';\n\nexport type CheckSourceVersion =\n | ''\n | 'active'\n | 'inactive'\n | 'workingArea'\n | 'new'\n | 'partlyActive'\n | 'activeWithInactiveVersion';\n\nexport type CheckMessage = {\n uri?: string;\n type?: unknown;\n shortText?: string;\n category?: string;\n code?: string;\n};\n\nexport type CheckReport = {\n checkMessageList?: {\n checkMessage?: CheckMessage[];\n };\n reporter?: string;\n triggeringUri?: string;\n status?: string;\n statusText?: string;\n};\n\nexport interface CheckServiceInput {\n objects: Array<{ uri: string }>;\n sourceVersion?: CheckSourceVersion;\n}\n\nexport interface CheckResult {\n reports: CheckReport[];\n hasErrors: boolean;\n hasWarnings: boolean;\n}\n\nfunction buildCheckObjectList(\n objects: Array<{ uri: string }>,\n sourceVersion: CheckSourceVersion,\n) {\n return {\n checkObjectList: {\n checkObject: objects.map((object) => ({\n uri: object.uri,\n version: sourceVersion,\n })),\n },\n };\n}\n\nfunction normalizeCheckMessages(\n rawMessages: unknown,\n): CheckMessage[] | undefined {\n if (!rawMessages) return undefined;\n return Array.isArray(rawMessages)\n ? rawMessages\n : [rawMessages as CheckMessage];\n}\n\nfunction normalizeReport(entry: unknown): CheckReport {\n const report = (entry ?? {}) as Record<string, unknown>;\n const messageList = report.checkMessageList as\n { checkMessage?: CheckMessage | CheckMessage[] } | undefined;\n const messages = normalizeCheckMessages(messageList?.checkMessage);\n\n return {\n reporter: report.reporter as string | undefined,\n triggeringUri: report.triggeringUri as string | undefined,\n status: report.status as string | undefined,\n statusText: report.statusText as string | undefined,\n checkMessageList: messages ? { checkMessage: messages } : undefined,\n };\n}\n\nfunction detectSeverities(\n reports: CheckReport[],\n): Pick<CheckResult, 'hasErrors' | 'hasWarnings'> {\n let hasErrors = false;\n let hasWarnings = false;\n for (const report of reports) {\n for (const message of report.checkMessageList?.checkMessage ?? []) {\n const severity =\n typeof message.type === 'string' ? message.type : message.category;\n if (severity === 'E' || severity === 'A') hasErrors = true;\n if (severity === 'W') hasWarnings = true;\n }\n }\n return { hasErrors, hasWarnings };\n}\n\nfunction extractReports(response: unknown): CheckResult {\n const root = (response ?? {}) as Record<string, unknown>;\n const reportsBlock = (root.checkRunReports ?? root) as Record<\n string,\n unknown\n >;\n const rawReports = reportsBlock.checkReport;\n const reportEntries = Array.isArray(rawReports)\n ? rawReports\n : rawReports\n ? [rawReports]\n : [];\n\n const reports = reportEntries.map(normalizeReport);\n return { reports, ...detectSeverities(reports) };\n}\n\nexport class CheckService {\n constructor(private readonly client: AdtClient) {}\n\n async run(input: CheckServiceInput): Promise<CheckResult> {\n const sourceVersion = input.sourceVersion ?? DEFAULT_CHECK_SOURCE_VERSION;\n const body = buildCheckObjectList(input.objects, sourceVersion);\n const endpoint = this.client.adt.checkruns.checkObjects;\n // The runtime endpoint accepts the schema body, while the generated\n // contract currently exposes the descriptor factory's zero-argument\n // signature. Keep that typing mismatch isolated at this boundary.\n const post = endpoint.post as unknown as (\n request: typeof body,\n ) => Promise<unknown>;\n const response = await post.call(endpoint, body);\n return extractReports(response);\n }\n}\n","/**\n * CLI Auth Utilities\n *\n * Thin wrapper around @abapify/adt-auth\n * All auth logic is in the adt-auth package (single source of truth)\n */\n\nimport { AuthManager } from '@abapify/adt-auth';\n\n// Re-export types from adt-auth\nexport type {\n AuthSession,\n AuthConfig,\n AuthMethod,\n BasicCredentials,\n CookieCredentials,\n Credentials,\n AuthPlugin,\n AuthPluginOptions,\n AuthPluginResult,\n} from '@abapify/adt-auth';\n\n// Singleton AuthManager instance for CLI\nconst authManager = new AuthManager();\n\n// =============================================================================\n// Session Management - Delegates to AuthManager\n// =============================================================================\n\n/**\n * Load auth session\n */\nexport function loadAuthSession(sid?: string) {\n return authManager.getSession(sid);\n}\n\n/**\n * Save auth session\n */\nexport function saveAuthSession(\n session: Parameters<typeof authManager.saveSession>[0],\n) {\n authManager.saveSession(session);\n}\n\n/**\n * List all available SIDs\n */\nexport function listAvailableSids() {\n return authManager.listSids();\n}\n\n// =============================================================================\n// Default SID Management\n// =============================================================================\n\n/**\n * Get default SID\n */\nexport function getDefaultSid() {\n return authManager.getDefaultSid() ?? undefined;\n}\n\n/**\n * Set default SID\n */\nexport function setDefaultSid(sid: string) {\n authManager.setDefaultSid(sid);\n}\n\n// =============================================================================\n// Credential Helpers\n// =============================================================================\n\n/**\n * Check if session is expired\n */\nexport function isExpired(\n session: Parameters<typeof authManager.isExpired>[0],\n) {\n return authManager.isExpired(session);\n}\n\n/**\n * Refresh credentials using auth plugin\n */\nexport async function refreshCredentials(\n session: Parameters<typeof authManager.refreshCredentials>[0],\n options?: Parameters<typeof authManager.refreshCredentials>[1],\n) {\n return authManager.refreshCredentials(session, options);\n}\n\n/**\n * Get the AuthManager instance (for advanced use)\n */\nexport function getAuthManager() {\n return authManager;\n}\n","/**\n * Lightweight progress reporter for CLI output.\n * - Compact mode keeps updates on a single line (overwriting previous text).\n * - Non-compact mode logs through the provided logger (CLI loggers target stderr).\n * - Progress is written to stderr so stdout stays safe for piping source,\n * JSON, XML, and other command payloads.\n *\n * When a logger is provided, progress messages are tagged with { progress: true }.\n */\n\nimport type { Logger } from '@abapify/logger';\n\nexport interface ProgressReporter {\n /** Update progress message (overwrites previous message in compact mode) */\n step(message: string): void;\n /** Emit a message on its own line (always persists) */\n persist(message: string): void;\n /** Finish the progress block and ensure the cursor moves to the next line */\n done(finalMessage?: string): void;\n /** Clear current progress without outputting anything (silent finish) */\n clear(): void;\n}\n\nexport interface ProgressOptions {\n /** When true, log updates replace each other on the same line */\n compact?: boolean;\n /** Optional logger to record progress events (info level by default) */\n logger?: Logger;\n /** Log level to use when writing progress messages */\n level?: 'trace' | 'debug' | 'info' | 'warn';\n}\n\nfunction sanitize(message: string): string {\n return message.replaceAll(/\\s+/g, ' ').trim();\n}\n\nexport function createProgressReporter(\n options: ProgressOptions = {},\n): ProgressReporter {\n const compact = Boolean(options.compact);\n const logger = options.logger;\n const level = options.level ?? 'info';\n let lastMessage = '';\n let open = false;\n\n const logWithFlag = (message: string, meta?: Record<string, unknown>) => {\n if (logger) {\n const logFn = (logger as any)[level] ?? logger.info;\n logFn.call(logger, message, {\n progress: true,\n component: 'progress',\n ...meta,\n });\n }\n };\n\n const clearLine = () => {\n if (open) {\n process.stderr.write('\\r\\x1b[K');\n }\n };\n\n const step = (message: string) => {\n const clean = sanitize(message);\n if (!compact) {\n logWithFlag(clean, { transient: false });\n return;\n }\n clearLine();\n process.stderr.write(clean);\n lastMessage = clean;\n open = true;\n logWithFlag(clean, { transient: true });\n };\n\n const persist = (message: string) => {\n const clean = sanitize(message);\n clearLine();\n if (compact || !logger) {\n process.stderr.write(`${clean}\\n`);\n }\n logWithFlag(clean);\n open = false;\n lastMessage = '';\n };\n\n const done = (finalMessage?: string) => {\n if (!open && !finalMessage) {\n return;\n }\n\n clearLine();\n if (compact) {\n if (finalMessage) {\n const clean = sanitize(finalMessage);\n process.stderr.write(`${clean}\\n`);\n logWithFlag(clean);\n } else if (open && lastMessage) {\n process.stderr.write(`${lastMessage}\\n`);\n logWithFlag(lastMessage);\n }\n } else {\n const clean = sanitize(finalMessage ?? lastMessage);\n if (clean) {\n logWithFlag(clean);\n }\n }\n\n open = false;\n lastMessage = '';\n };\n\n const clear = () => {\n clearLine();\n open = false;\n lastMessage = '';\n };\n\n return { step, persist, done, clear };\n}\n","/**\n * Link Component\n *\n * Creates OSC 8 hyperlinks for terminal emulators that support them.\n * Falls back to plain text in unsupported terminals.\n *\n * OSC 8 format: \\x1b]8;;URL\\x07TEXT\\x1b]8;;\\\\x07\n *\n * @see https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda\n */\n\nimport chalk from 'chalk';\nimport type { Component } from '../types';\n\n// =============================================================================\n// Core Hyperlink Function\n// =============================================================================\n\n/**\n * Create an OSC 8 hyperlink\n *\n * @param text - Display text\n * @param url - URL to link to\n * @returns Formatted hyperlink string\n */\nexport function hyperlink(text: string, url: string): string {\n const OSC = '\\x1b]';\n const BEL = '\\x07';\n const SEP = ';';\n return `${OSC}8${SEP}${SEP}${url}${BEL}${text}${OSC}8${SEP}${SEP}${BEL}`;\n}\n\n// =============================================================================\n// ADT System Configuration\n// =============================================================================\n\nlet adtSystemName = '';\n\n/**\n * Set the ADT system name for hyperlinks (called by CLI on init)\n */\nexport function setAdtSystem(systemName: string): void {\n adtSystemName = systemName;\n}\n\n/**\n * Get current ADT system name\n */\nexport function getAdtSystem(): string {\n return adtSystemName;\n}\n\n// =============================================================================\n// ADT Path Templates\n// =============================================================================\n\n/**\n * ADT path templates for object types\n * Template uses {name} placeholder for object name\n */\nconst ADT_PATH_TEMPLATES: Record<string, string> = {\n // Packages\n DEVC: '/packages/{name}',\n 'DEVC/K': '/packages/{name}',\n // Classes\n CLAS: '/oo/classes/{name}',\n 'CLAS/OC': '/oo/classes/{name}',\n // Interfaces\n INTF: '/oo/interfaces/{name}',\n 'INTF/OI': '/oo/interfaces/{name}',\n // Function Groups\n FUGR: '/functions/groups/{name}',\n 'FUGR/F': '/functions/groups/{name}',\n // Function Modules (need group context, simplified)\n FUNC: '/functions/groups/{name}',\n // Programs\n PROG: '/programs/programs/{name}',\n 'PROG/P': '/programs/programs/{name}',\n // Includes\n 'PROG/I': '/programs/includes/{name}',\n // Tables\n TABL: '/ddic/tables/{name}',\n 'TABL/DT': '/ddic/tables/{name}',\n // Structures\n 'TABL/DS': '/ddic/structures/{name}',\n // Views\n VIEW: '/ddic/views/{name}',\n // Data Elements\n DTEL: '/ddic/dataelements/{name}',\n 'DTEL/DE': '/ddic/dataelements/{name}',\n // Domains\n DOMA: '/ddic/domains/{name}',\n 'DOMA/DO': '/ddic/domains/{name}',\n // Search Helps\n SHLP: '/ddic/searchhelps/{name}',\n // Lock Objects\n ENQU: '/ddic/lockobjects/{name}',\n // Message Classes\n MSAG: '/messageclass/{name}',\n // Transactions\n TRAN: '/transactions/{name}',\n // CDS Views\n DDLS: '/ddic/ddl/sources/{name}',\n 'DDLS/DF': '/ddic/ddl/sources/{name}',\n // Behavior Definitions\n BDEF: '/bo/behaviordefinitions/{name}',\n // Service Definitions\n SRVD: '/businessservices/servicedefinitions/{name}',\n // Service Bindings\n SRVB: '/businessservices/servicebindings/{name}',\n};\n\n/**\n * Get ADT path template for an object type\n */\nfunction getAdtPathTemplate(objectType: string): string | undefined {\n // Try exact match first\n if (ADT_PATH_TEMPLATES[objectType]) {\n return ADT_PATH_TEMPLATES[objectType];\n }\n // Try base type (before /)\n const baseType = objectType.split('/')[0];\n return ADT_PATH_TEMPLATES[baseType];\n}\n\n/**\n * Resolve ADT path from template\n */\nfunction resolveAdtPath(template: string, name: string): string {\n return template.replace('{name}', encodeURIComponent(name));\n}\n\n// =============================================================================\n// Types\n// =============================================================================\n\n/**\n * ADT Object Reference (matches AdtObjectReference schema)\n * Core attributes: uri, type, name\n */\nexport interface AdtObjectRef {\n /** Object name */\n name?: string;\n /** Object type (e.g., \"DEVC/K\", \"CLAS/OC\") */\n type?: string;\n /** ADT URI (e.g., \"/sap/bc/adt/packages/$TMP\") */\n uri?: string;\n}\n\n// =============================================================================\n// Link Functions\n// =============================================================================\n\n/**\n * Create a generic link (plain URL)\n */\nexport function link(text: string, url: string): string {\n return hyperlink(chalk.cyan(text), url);\n}\n\n/**\n * Create an ADT Eclipse link for an object reference\n * Format: adt://[SYSTEM]/sap/bc/adt/[path]\n *\n * @param ref - ADT object reference with name, type, and/or uri (can be undefined)\n * @returns Formatted hyperlink string (or empty string if no ref/name)\n */\nexport function adtLink(ref?: AdtObjectRef): string {\n const name = ref?.name || '';\n\n if (!adtSystemName || !name) {\n return name ? chalk.cyan(name) : '';\n }\n\n // If URI is provided, use it directly\n if (ref?.uri) {\n const path = ref.uri.startsWith('/sap/bc/adt')\n ? ref.uri\n : `/sap/bc/adt${ref.uri}`;\n const url = `adt://${adtSystemName}${path}`;\n return hyperlink(chalk.cyan(name), url);\n }\n\n // Otherwise, resolve from type + name using template\n if (ref?.type) {\n const template = getAdtPathTemplate(ref.type);\n if (template) {\n const adtPath = resolveAdtPath(template, name);\n const url = `adt://${adtSystemName}/sap/bc/adt${adtPath}`;\n return hyperlink(chalk.cyan(name), url);\n }\n }\n\n // Fallback: plain text\n return chalk.cyan(name);\n}\n\n/**\n * Create a clickable package link (convenience wrapper)\n */\nexport function packageLink(packageName: string): string {\n return adtLink({ type: 'DEVC', name: packageName });\n}\n\n// =============================================================================\n// Link Components\n// =============================================================================\n\n/**\n * Link Component - generic hyperlink\n */\nexport default function Link(text: string, url: string): Component {\n return {\n render: () => [hyperlink(chalk.cyan(text), url)],\n };\n}\n\n/**\n * ADT Link Component - link to ADT object in Eclipse\n * Extends Link with ADT-specific URL resolution\n */\nexport function AdtLink(ref?: AdtObjectRef): Component {\n return {\n render: () => {\n const result = adtLink(ref);\n return result ? [result] : [];\n },\n };\n}\n\n/**\n * Package Link Component - convenience for package links\n */\nexport function PackageLink(packageName: string): Component {\n return AdtLink({ type: 'DEVC', name: packageName });\n}\n","const HEADERS_TIMEOUT_ENV = 'ADT_HEADERS_TIMEOUT_MS';\n\nexport function resolveAdtHeadersTimeoutMs(\n env: Readonly<Record<string, string | undefined>> = process.env,\n): number | undefined {\n const raw = env[HEADERS_TIMEOUT_ENV];\n if (raw === undefined || raw === '') return undefined;\n if (!/^\\d+$/.test(raw)) {\n throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);\n }\n\n const timeoutMs = Number(raw);\n if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0) {\n throw new RangeError(`${HEADERS_TIMEOUT_ENV} must be a positive integer`);\n }\n return timeoutMs;\n}\n","/**\n * Utility for initializing ADT Client V2 in CLI commands\n *\n * This module provides CLI-specific auth integration for the v2 client.\n * It bridges the gap between CLI's auth management and v2's pure client API.\n *\n * Architecture Note:\n * - CLI handles auth management (via v1 AuthManager stored in ~/.adt/auth.json)\n * - This module extracts credentials and creates v2 client\n * - v2 client remains pure (no CLI/file I/O dependencies)\n *\n * Shared state (context, loggers, capture) is in shared/adt-client.ts\n */\nimport {\n createAdtClient,\n LoggingPlugin,\n FileLoggingPlugin,\n type Logger,\n type ResponseContext,\n type AdtClient,\n} from '@abapify/adt-client';\nimport type { AdtAdapterConfig } from '@abapify/adt-client';\nimport { initializeAdk, isAdkInitialized } from '@abapify/adk';\nimport { FileLockStore } from '@abapify/adt-locks';\nimport {\n loadAuthSession,\n isExpired,\n refreshCredentials,\n type CookieCredentials,\n type BasicCredentials,\n type AuthSession,\n} from './auth';\nimport {\n createProgressReporter,\n type ProgressReporter,\n} from './progress-reporter';\nimport { setAdtSystem } from '../ui/components/link';\nimport { resolveAdtHeadersTimeoutMs } from './adt-http-options';\n\n// Re-export shared state from shared/adt-client.ts for backward compatibility\nexport {\n type CliContext,\n setCliContext,\n getCliContext,\n resetCliContext,\n silentLogger,\n consoleLogger,\n type CapturedResponse,\n getCaptured,\n setCaptured,\n resetCaptured,\n} from '../shared/adt-client';\n\nimport {\n getCliContext,\n silentLogger,\n consoleLogger,\n setCaptured,\n resetCaptured,\n} from '../shared/adt-client';\n\n// =============================================================================\n// Test DI hook (internal, used by tests/e2e harness)\n// =============================================================================\n\n/**\n * Stack of test overrides. Using a stack (instead of a single mutable slot)\n * means nested / concurrent harness instances don't clobber each other's\n * clients, and teardown is strict: each `__setTestAdtClient` call returns a\n * `release` function that removes *only that* override, regardless of order.\n *\n * Concurrency note: Vitest's default `threads` pool gives each worker its\n * own module graph, so in practice this state is already isolated per\n * worker. But a stack keeps us safe if:\n * - a suite uses `test.concurrent` (shared module, shared state)\n * - the pool config is changed to `forks: { singleFork: false }` or similar\n * - multiple harnesses are constructed within a single test\n * which is why we prefer a stack + explicit release handle here.\n */\nconst __testAdtClientOverrides: AdtClient[] = [];\n\n/**\n * @internal\n * Install a test AdtClient instance. When set, `getAdtClientV2()` will return\n * the most recently pushed client instead of loading credentials from disk and\n * constructing a real client. Intended solely for e2e harness usage.\n *\n * Returns a `release` function that removes **this specific** override from\n * the stack. Callers (harness teardown) MUST call `release()` in an\n * `afterEach` / `afterAll` / `finally` block.\n *\n * Backward compatibility: passing `null` pops the top of the stack (legacy\n * behaviour used by older harness code paths). New code should prefer the\n * returned release handle.\n */\nexport function __setTestAdtClient(client: AdtClient | null): () => void {\n if (client === null) {\n // Legacy clear semantics: pop the most recent override.\n __testAdtClientOverrides.pop();\n return () => {\n /* no-op: legacy clear has already happened */\n };\n }\n\n __testAdtClientOverrides.push(client);\n let released = false;\n return function release(): void {\n if (released) return;\n released = true;\n const idx = __testAdtClientOverrides.lastIndexOf(client);\n if (idx !== -1) __testAdtClientOverrides.splice(idx, 1);\n };\n}\n\n/**\n * @internal\n * Inspect the current test override (mostly for diagnostics / test cleanup).\n * Returns the top of the stack, or `null` if no override is active.\n */\nexport function __getTestAdtClient(): AdtClient | null {\n return __testAdtClientOverrides.length > 0\n ? __testAdtClientOverrides[__testAdtClientOverrides.length - 1]\n : null;\n}\n\nfunction __getActiveTestAdtClient(): AdtClient | undefined {\n return __testAdtClientOverrides[__testAdtClientOverrides.length - 1];\n}\n\n// =============================================================================\n// Client Options\n// =============================================================================\n\n/**\n * Options for creating ADT v2 client\n */\nexport interface AdtClientV2Options {\n /** Optional response plugins (added after built-in plugins) */\n plugins?: AdtAdapterConfig['plugins'];\n /** Optional logger for CLI messages (defaults to global CLI logger or silent) */\n logger?: Logger;\n /** Enable request/response logging (default: from CLI --verbose flag) */\n enableLogging?: boolean;\n /** Enable response file logging (default: from CLI --log-response-files flag) */\n logResponseFiles?: boolean;\n /** Output directory for response files (default: from CLI --log-output flag or './tmp/logs') */\n logOutput?: string;\n /** Write metadata alongside response files (default: false) */\n writeMetadata?: boolean;\n /** SAP System ID (SID) - e.g., 'TRL' (default: from CLI --sid flag) */\n sid?: string;\n /** Enable capture plugin to capture raw XML and parsed JSON (default: false) */\n capture?: boolean;\n /** Enable automatic SAML re-authentication when session expires (default: true for cookie auth) */\n autoReauth?: boolean;\n /** Pass through verbose flag (used to disable compact progress output) */\n verbose?: boolean | string;\n}\n\n/**\n * Typed error thrown by `getAdtClientV2Safe` when authentication cannot be\n * resolved. Intentionally NOT thrown by the legacy `getAdtClientV2`, which\n * prints a friendly message and calls `process.exit(1)` instead. Use this\n * error class from long-running processes (HTTP servers, MCP daemons) that\n * must never exit the process on auth failure.\n */\nexport class AdtAuthError extends Error {\n public readonly code:\n | 'NO_SESSION'\n | 'SESSION_EXPIRED_NO_PLUGIN'\n | 'REFRESH_FAILED'\n | 'UNSUPPORTED_AUTH_METHOD'\n | 'MAX_REFRESH_ATTEMPTS';\n public readonly systemId?: string;\n\n constructor(code: AdtAuthError['code'], message: string, systemId?: string) {\n super(message);\n this.name = 'AdtAuthError';\n this.code = code;\n this.systemId = systemId;\n }\n}\n\n// =============================================================================\n// Small helpers for the shared-between-variants logic (previously inline\n// process.exit paths). Split out per the Wave 1-C task so that\n// `getAdtClientV2Safe` can throw while `getAdtClientV2` keeps its\n// friendly CLI UX (print + exit).\n// =============================================================================\n\nfunction reportNoSessionAndExit(sid: string | undefined): never {\n const sidMsg = sid ? ` for SID ${sid}` : '';\n const loginFlag = sid ? ` --sid=${sid}` : '';\n console.error(`❌ Not authenticated${sidMsg}`);\n console.error(\n `💡 Run \"npx adt auth login${loginFlag}\" to authenticate first`,\n );\n process.exit(1);\n}\n\nfunction reportUnsupportedAuthAndExit(method: string): never {\n console.error(`❌ Unsupported auth method: ${method}`);\n process.exit(1);\n}\n\n/**\n * Try to auto-refresh expired session credentials\n *\n * @param session - The expired session\n * @param sid - Optional SID for error messages\n * @returns Updated session with fresh credentials\n */\nasync function tryAutoRefresh(\n session: AuthSession,\n sid: string | undefined,\n progress: ProgressReporter,\n): Promise<AuthSession> {\n // Check if plugin is available for refresh\n if (!session.auth.plugin) {\n console.error('❌ Session expired');\n console.error('💡 Run \"npx adt auth login\" to re-authenticate');\n process.exit(1);\n }\n\n progress.step(`🔄 Session expired for ${session.sid}, refreshing...`);\n\n try {\n const refreshedSession = await refreshCredentials(session, {\n log: progress.persist,\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n progress.clear(); // Silent on success - don't clutter output\n return refreshedSession;\n } catch (error) {\n progress.done('❌ Auto-refresh failed');\n console.error(\n '❌ Auto-refresh failed:',\n error instanceof Error ? error.message : String(error),\n );\n const sidArg = sid ? ` --sid=${sid}` : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n process.exit(1);\n }\n}\n\n/**\n * Safe variant of `tryAutoRefresh` that throws `AdtAuthError` instead of\n * exiting the process. Used by `getAdtClientV2Safe`.\n */\nasync function tryAutoRefreshSafe(\n session: AuthSession,\n sid: string | undefined,\n): Promise<AuthSession> {\n if (!session.auth.plugin) {\n const sidSuffix = sid ? ` for SID ${sid}` : '';\n throw new AdtAuthError(\n 'SESSION_EXPIRED_NO_PLUGIN',\n `Session expired${sidSuffix} and no auth plugin is configured to refresh it.`,\n sid,\n );\n }\n\n try {\n const refreshedSession = await refreshCredentials(session, {\n // no progress reporter in the safe path — callers own logging\n log: () => {\n /* silent */\n },\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n return refreshedSession;\n } catch (error) {\n const sidSuffix = sid ? ` for SID ${sid}` : '';\n const errMsg = error instanceof Error ? error.message : String(error);\n throw new AdtAuthError(\n 'REFRESH_FAILED',\n `Auto-refresh failed${sidSuffix}: ${errMsg}`,\n sid,\n );\n }\n}\n\n/**\n * Get authenticated ADT v2 client\n *\n * Loads auth session from CLI config and creates v2 client.\n * Automatically refreshes expired sessions when possible.\n * Exits with error if not authenticated.\n *\n * @param options - Optional configuration (plugins, logger, etc.)\n * @returns Authenticated ADT v2 client\n *\n * @example\n * // Simple usage\n * const client = await getAdtClientV2();\n *\n * @example\n * // With custom logger\n * const client = await getAdtClientV2({\n * logger: myLogger,\n * enableLogging: true // Enable HTTP request/response logging\n * });\n *\n * @example\n * // With plugins\n * const client = await getAdtClientV2({\n * plugins: [myPlugin]\n * });\n */\nexport async function getAdtClientV2(\n options?: AdtClientV2Options,\n): Promise<AdtClient> {\n // Test DI hook: if a test harness has injected a client, return the\n // top-of-stack override. Must short-circuit BEFORE touching disk-based\n // auth / CLI context.\n const testOverride = __getActiveTestAdtClient();\n if (testOverride) {\n return testOverride;\n }\n\n // Resolve the headers timeout before any auth/refresh work so an invalid\n // value fails fast instead of after a potentially network-bound refresh.\n const headersTimeoutMs = resolveAdtHeadersTimeoutMs();\n\n // Merge with global CLI context (explicit options take precedence)\n const ctx = getCliContext();\n const effectiveOptions = {\n sid: options?.sid ?? ctx.sid,\n logger: options?.logger ?? ctx.logger,\n logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,\n logOutput: options?.logOutput ?? ctx.logOutput ?? './tmp/logs',\n enableLogging: options?.enableLogging,\n writeMetadata: options?.writeMetadata ?? false,\n capture: options?.capture ?? false,\n plugins: options?.plugins ?? [],\n autoReauth: options?.autoReauth ?? true, // Enable auto-reauth by default\n verbose: options?.verbose ?? ctx.verbose,\n };\n\n // Priority: 1) user-provided logger, 2) global CLI logger, 3) console if enableLogging, 4) silent\n const logger =\n effectiveOptions.logger ??\n (effectiveOptions.enableLogging ? consoleLogger : silentLogger);\n const progress = createProgressReporter({\n compact: !effectiveOptions.verbose,\n logger,\n });\n let session = loadAuthSession(effectiveOptions.sid);\n\n if (!session) {\n reportNoSessionAndExit(effectiveOptions.sid);\n }\n\n // Set system name for ADT hyperlinks (e.g., adt://TRL/sap/bc/adt/...)\n setAdtSystem(session.sid);\n\n // Extract credentials based on auth method\n const baseUrl = session.host;\n const client = session.client;\n let username: string | undefined;\n let password: string | undefined;\n let cookieHeader: string | undefined;\n let authorizationHeader: string | undefined;\n\n if (session.auth.method === 'basic') {\n const creds = session.auth.credentials as BasicCredentials;\n username = creds.username;\n password = creds.password;\n } else if (session.auth.method === 'cookie') {\n // Check if session is expired - try auto-refresh first\n if (isExpired(session)) {\n session = await tryAutoRefresh(session, effectiveOptions.sid, progress);\n }\n\n const creds = session.auth.credentials as CookieCredentials;\n // Decode URL-encoded cookie values (e.g., %3d -> =)\n const rawCookies = decodeURIComponent(creds.cookies);\n\n const AUTH_PREFIX = 'Authorization: ';\n if (rawCookies.startsWith(AUTH_PREFIX)) {\n // Bearer token from OAuth (e.g., BTP service key auth) — pass as\n // Authorization header, not as a Cookie\n authorizationHeader = rawCookies.substring(AUTH_PREFIX.length);\n } else {\n cookieHeader = rawCookies;\n }\n } else {\n reportUnsupportedAuthAndExit(session.auth.method);\n }\n\n // Build plugin list: built-in plugins first, then user plugins\n const plugins: AdtAdapterConfig['plugins'] = [];\n\n // Add capture plugin if enabled (must be first to capture before other plugins)\n if (effectiveOptions.capture) {\n resetCaptured();\n plugins.push({\n name: 'capture',\n process: (context: ResponseContext) => {\n setCaptured({\n xml: context.rawText,\n json: context.parsedData,\n });\n return context.parsedData;\n },\n });\n }\n\n // Add file logging plugin if enabled\n if (effectiveOptions.logResponseFiles) {\n plugins.push(\n new FileLoggingPlugin({\n outputDir: effectiveOptions.logOutput,\n writeMetadata: effectiveOptions.writeMetadata,\n logger,\n }),\n );\n }\n\n // Add console logging plugin if enabled\n if (effectiveOptions.enableLogging) {\n plugins.push(\n new LoggingPlugin((msg, data) => {\n const dataSuffix = data ? ` ${JSON.stringify(data)}` : '';\n logger.info(`${msg}${dataSuffix}`);\n }),\n );\n }\n\n // Add user-provided plugins last\n plugins.push(...effectiveOptions.plugins);\n\n // Create onSessionExpired callback for automatic SAML re-authentication\n // Only applicable for cookie-based auth with a plugin that can refresh\n let onSessionExpired: (() => Promise<string>) | undefined;\n\n if (\n effectiveOptions.autoReauth &&\n session.auth.method === 'cookie' &&\n session.auth.plugin\n ) {\n // Capture current session for the callback closure\n let currentSession = session;\n let refreshAttempts = 0;\n const MAX_REFRESH_ATTEMPTS = 1;\n\n onSessionExpired = async (): Promise<string> => {\n refreshAttempts++;\n\n if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {\n const error = new Error(\n `Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded`,\n );\n console.error('❌ Auto-refresh failed: Too many attempts');\n const sidArg = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n throw error;\n }\n\n progress.step(\n `🔄 Session expired, refreshing credentials for ${currentSession.sid}... (attempt ${refreshAttempts}/${MAX_REFRESH_ATTEMPTS})`,\n );\n\n try {\n // Refresh credentials using the auth plugin (opens browser for SAML)\n const refreshedSession = await refreshCredentials(currentSession, {\n log: progress.persist,\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n currentSession = refreshedSession;\n\n // Extract new cookie from refreshed session\n const creds = currentSession.auth.credentials as CookieCredentials;\n const newCookie = decodeURIComponent(creds.cookies);\n\n progress.clear(); // Silent on success - don't clutter output\n // DON'T reset counter - if cookies don't work, we'll hit the limit\n return newCookie;\n } catch (error) {\n progress.done('❌ Auto-refresh failed');\n console.error(\n '❌ Auto-refresh failed:',\n error instanceof Error ? error.message : String(error),\n );\n const sidArg = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n console.error(\n `💡 Run \"npx adt auth login${sidArg}\" to re-authenticate manually`,\n );\n throw error;\n }\n };\n }\n\n const adtClient = createAdtClient({\n baseUrl,\n username,\n password,\n cookieHeader,\n authorizationHeader,\n client,\n logger,\n plugins,\n onSessionExpired,\n headersTimeoutMs,\n });\n\n // Initialize ADK global context if not already done\n // This allows ADK objects to be used without passing context explicitly\n if (!isAdkInitialized()) {\n initializeAdk(adtClient, { lockStore: new FileLockStore() });\n }\n\n return adtClient;\n}\n\n// =============================================================================\n// getAdtClientV2Safe — safe variant that throws AdtAuthError instead of\n// exiting the process. Required by long-running callers (adt-mcp HTTP\n// transport, any daemon). Keep this behaviourally identical to\n// `getAdtClientV2`, differing only in error handling.\n// =============================================================================\n\n/**\n * Same contract as {@link getAdtClientV2}, but on any authentication /\n * credential failure throws a typed {@link AdtAuthError} instead of\n * writing to stderr and calling `process.exit(1)`.\n *\n * Use this from long-running processes (HTTP servers, MCP daemons) where\n * `process.exit` would tear down unrelated connections.\n *\n * @throws {AdtAuthError} when the session is missing, expired without a\n * refresh plugin, refresh fails, or the configured auth method is\n * unsupported.\n */\nexport async function getAdtClientV2Safe(\n options?: AdtClientV2Options,\n): Promise<AdtClient> {\n // Test DI hook — identical to getAdtClientV2\n const testOverride = __getActiveTestAdtClient();\n if (testOverride) {\n return testOverride;\n }\n\n // Validate the headers timeout up front so an invalid value fails before\n // any expired-session refresh or authentication work can send a request.\n const adtHeadersTimeout = resolveAdtHeadersTimeoutMs();\n\n const ctx = getCliContext();\n const effectiveOptions = {\n sid: options?.sid ?? ctx.sid,\n logger: options?.logger ?? ctx.logger,\n logResponseFiles: options?.logResponseFiles ?? ctx.logResponseFiles,\n logOutput: options?.logOutput ?? ctx.logOutput ?? './tmp/logs',\n enableLogging: options?.enableLogging,\n writeMetadata: options?.writeMetadata ?? false,\n capture: options?.capture ?? false,\n plugins: options?.plugins ?? [],\n autoReauth: options?.autoReauth ?? true,\n verbose: options?.verbose ?? ctx.verbose,\n };\n\n const logger =\n effectiveOptions.logger ??\n (effectiveOptions.enableLogging ? consoleLogger : silentLogger);\n\n let session = loadAuthSession(effectiveOptions.sid);\n\n if (!session) {\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n const sidFlag = effectiveOptions.sid\n ? ` --sid=${effectiveOptions.sid}`\n : '';\n throw new AdtAuthError(\n 'NO_SESSION',\n `Not authenticated${sidSuffix}. Run \"adt auth login${sidFlag}\" first.`,\n effectiveOptions.sid,\n );\n }\n\n setAdtSystem(session.sid);\n\n const baseUrl = session.host;\n const client = session.client;\n let username: string | undefined;\n let password: string | undefined;\n let cookieHeader: string | undefined;\n let authorizationHeader: string | undefined;\n\n if (session.auth.method === 'basic') {\n const creds = session.auth.credentials as BasicCredentials;\n username = creds.username;\n password = creds.password;\n } else if (session.auth.method === 'cookie') {\n if (isExpired(session)) {\n session = await tryAutoRefreshSafe(session, effectiveOptions.sid);\n }\n\n const creds = session.auth.credentials as CookieCredentials;\n const rawCookies = decodeURIComponent(creds.cookies);\n\n const AUTH_PREFIX = 'Authorization: ';\n if (rawCookies.startsWith(AUTH_PREFIX)) {\n authorizationHeader = rawCookies.substring(AUTH_PREFIX.length);\n } else {\n cookieHeader = rawCookies;\n }\n } else {\n throw new AdtAuthError(\n 'UNSUPPORTED_AUTH_METHOD',\n `Unsupported auth method: ${session.auth.method}`,\n effectiveOptions.sid,\n );\n }\n\n // Plugin list — identical to getAdtClientV2\n const plugins: AdtAdapterConfig['plugins'] = [];\n\n if (effectiveOptions.capture) {\n resetCaptured();\n plugins.push({\n name: 'capture',\n process: (context: ResponseContext) => {\n setCaptured({\n xml: context.rawText,\n json: context.parsedData,\n });\n return context.parsedData;\n },\n });\n }\n\n if (effectiveOptions.logResponseFiles) {\n plugins.push(\n new FileLoggingPlugin({\n outputDir: effectiveOptions.logOutput,\n writeMetadata: effectiveOptions.writeMetadata,\n logger,\n }),\n );\n }\n\n if (effectiveOptions.enableLogging) {\n plugins.push(\n new LoggingPlugin((msg, data) => {\n const dataSuffix = data ? ` ${JSON.stringify(data)}` : '';\n logger.info(`${msg}${dataSuffix}`);\n }),\n );\n }\n\n plugins.push(...effectiveOptions.plugins);\n\n // onSessionExpired callback — throws AdtAuthError, no console.error\n let onSessionExpired: (() => Promise<string>) | undefined;\n if (\n effectiveOptions.autoReauth &&\n session.auth.method === 'cookie' &&\n session.auth.plugin\n ) {\n let currentSession = session;\n let refreshAttempts = 0;\n const MAX_REFRESH_ATTEMPTS = 1;\n\n onSessionExpired = async (): Promise<string> => {\n refreshAttempts++;\n\n if (refreshAttempts > MAX_REFRESH_ATTEMPTS) {\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n throw new AdtAuthError(\n 'MAX_REFRESH_ATTEMPTS',\n `Maximum refresh attempts (${MAX_REFRESH_ATTEMPTS}) exceeded${sidSuffix}.`,\n effectiveOptions.sid,\n );\n }\n\n try {\n const refreshedSession = await refreshCredentials(currentSession, {\n log: () => {\n /* silent — callers own logging */\n },\n });\n if (!refreshedSession) {\n throw new Error('Refresh returned null');\n }\n currentSession = refreshedSession;\n\n const creds = currentSession.auth.credentials as CookieCredentials;\n return decodeURIComponent(creds.cookies);\n } catch (error) {\n if (error instanceof AdtAuthError) throw error;\n const sidSuffix = effectiveOptions.sid\n ? ` for SID ${effectiveOptions.sid}`\n : '';\n const errMsg = error instanceof Error ? error.message : String(error);\n throw new AdtAuthError(\n 'REFRESH_FAILED',\n `Auto-refresh failed${sidSuffix}: ${errMsg}`,\n effectiveOptions.sid,\n );\n }\n };\n }\n\n const adtClient = createAdtClient({\n baseUrl,\n username,\n password,\n cookieHeader,\n authorizationHeader,\n client,\n logger,\n plugins,\n onSessionExpired,\n headersTimeoutMs: adtHeadersTimeout,\n });\n\n if (!isAdkInitialized()) {\n initializeAdk(adtClient, { lockStore: new FileLockStore() });\n }\n\n return adtClient;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAYA,MAAM,UAAU;AAChB,MAAM,aAAa;AAkCnB,SAAS,kBAAkB,IAA+B;CACxD,OAAO;EACL,KAAK,IAAI,OAAO;GACd,OAAO,IAAI,eAAe,IAAI,KAAK,KAAK;EAC1C;EACA,KAAK,IAAI,OAAO;GACd,OAAO,KAAK,KAAK,IAAI,KAAK,CAAC,CAAC,YAAY,MAAM;EAChD;EACA,MAAM,QAAQ,OAAO;GAEnB,OADa,OAAO,uBAAuB,IAAI,KACpC,CAAC,CAAC,KAAK,CAAC,KAA2B;EAChD;EACA,SAAS,QAAQ,OAAO;GACtB,MAAM,OAAO,OAAO,uBAAuB,IAAI,KAAK;GACpD,MAAM,SAAuB,CAAC;GAC9B,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;IACpC,MAAM,OAAO,KAAK,KAAK,CAAC;IACxB,IAAI,MAAM,OAAO,KAAK,IAAI;GAC5B;GACA,OAAO;EACT;CACF;AACF;AAEA,MAAM,OAAO,kBAAkB,OAAO;AACtC,MAAM,UAAU,kBAAkB,UAAU;AAE5C,SAAS,SAAS,MAAkB,OAAuB;CACzD,OAAO,QAAQ,KAAK,MAAM,KAAK,KAAK,KAAK,aAAa,KAAK,KAAK;AAClE;AAEA,SAAS,wBAAwB,MAAsC;CACrE,OAAO;EACL,MAAM,KAAK,KAAK,MAAM,MAAM;EAC5B,WAAW,KAAK,KAAK,MAAM,WAAW;EACtC,QAAQ,KAAK,KAAK,MAAM,QAAQ;EAChC,SAAS,KAAK,KAAK,MAAM,SAAS;EAClC,SAAS,KAAK,K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