/** * XML parser for SAP ADT responses. * * SAP ADT returns XML with multiple namespace conventions: * - adtcore: (http://www.sap.com/adt/core) — object references, search results * - asx: (http://www.sap.com/abapxml) — table contents, package structure * - atom: (http://www.w3.org/2005/Atom) — feed entries * * We use fast-xml-parser v5 with removeNSPrefix to strip namespaces, * since we know the expected structure and don't need namespace dispatch. * * Key design choice: parse to plain objects, then map to our types. * This decouples the XML format from our internal types, making it * easier to handle SAP's inconsistent XML across different endpoints. */ import { XMLParser } from 'fast-xml-parser'; import { AdtApiError } from './errors.js'; import type { AdtSearchResult, AttributeStructure, AuthorizationFieldInfo, BspAppInfo, BspFileNode, ClassMetadata, ClassStructure, DataElementInfo, DomainInfo, EnhancementImplementationInfo, FeatureToggleInfo, FunctionGroupStructure, FunctionModuleProperties, InactiveObject, LineRange, MessageClassInfo, MethodStructure, ServerDrivenObjectMetadata, TransactionInfo, } from './types.js'; import { decodeXmlEntities } from './xml-entities.js'; /** * Escape the five predefined XML entities (`& < > " '`) for safe interpolation into XML. * * This is the ONE XML escaper for the codebase — safe for both attribute values and element text * (escaping `"`/`'` in text content is valid and harmless). Do NOT add a local copy in another * module; import this. (HTML/XSS contexts are different — `escapeHtml` in oauth.ts/http.ts emits * `'`, not the XML `'`, and must stay separate.) */ export function escapeXmlAttr(s: string): string { return s.replace(/[&<>"']/g, (char) => XML_ESCAPE_MAP[char]!); } const XML_ESCAPE_MAP: Record = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''', }; // These elements can appear 0-N times; force arrays even for a single item. const ARRAY_TAGS = new Set([ 'objectReference', 'entry', 'link', 'objectStructure', 'field', 'functionModule', 'COLUMN', 'columns', 'DATA', 'data', 'SEU_ADT_REPOSITORY_OBJ_NODE', 'component', 'objectStructureElement', 'task', 'objectType', 'proposal', 'referencedObject', 'textSearchResult', 'textSearchObject', 'textLine', 'testClass', 'testMethod', 'alert', 'finding', 'msg', 'request', 'hitListEntry', 'chapter', 'traceStatement', 'statement', 'dbAccess', 'access', 'successor', 'messages', 'workspace', 'collection', 'accept', 'orglvlinfo', 'badiImplementation', ]); /** Common ADT conventions; data-preview cells additionally retain their exact text. */ const parserOptions = { ignoreAttributes: false, attributeNamePrefix: '@_', removeNSPrefix: true, // Strip adtcore:, asx:, etc. isArray: (name: string) => ARRAY_TAGS.has(name), parseAttributeValue: false, // Keep attributes as strings parseTagValue: false, // Keep tag values as strings (prevents "001" → 1) // Use the native entity boundary: unlike value processors, it skips literal CDATA. // Decode only predefined/numeric references, with no recursive DOCTYPE expansion or ST22 cap. entityDecoder: { decode: decodeXmlEntities, addInputEntities: () => {}, setExternalEntities: () => {}, setXmlVersion: () => {}, reset: () => {}, }, }; const parser = new XMLParser(parserOptions); const whitespacePreservingParser = new XMLParser({ ...parserOptions, trimValues: false }); /** * Parse raw XML string to a JS object. Every attribute and text value is entity-DECODED * (`R&D` → `R&D`): never decode a parsed value again, and `escapeXmlAttr` it on the way back. * Set preserveWhitespace to retain leading/trailing text whitespace, e.g. in quick-fix deltas. */ export function parseXml(xml: string, preserveWhitespace = false): Record { return (preserveWhitespace ? whitespacePreservingParser : parser).parse(xml) as Record; } /** * Parse ADT search results XML. * * Expected format: * * * */ export function parseSearchResults(xml: string): AdtSearchResult[] { const parsed = parseXml(xml); const refs = getNestedArray(parsed, 'objectReferences', 'objectReference'); return refs.map((ref: Record) => ({ objectType: String(ref['@_type'] ?? ''), objectName: canonicalSearchName(String(ref['@_name'] ?? ''), String(ref['@_uri'] ?? '')), description: String(ref['@_description'] ?? ''), packageName: String(ref['@_packageName'] ?? ''), uri: String(ref['@_uri'] ?? ''), })); } /** Legacy quickSearch decorates names with localized type labels; require URI identity proof. */ function canonicalSearchName(displayName: string, uri: string): string { const name = /^([^\s()]+) \([^()]+\)$/.exec(displayName)?.[1]; if (!name) return displayName; const segment = /^\/sap\/bc\/adt\/(?:[^/?#]+\/)*([^/?#]+)$/i.exec(uri)?.[1]; try { return segment && decodeURIComponent(segment).toUpperCase() === name.toUpperCase() ? name : displayName; } catch { return displayName; } } /** * Parse ADT package contents (nodestructure response). * * Expected format: * * * PROG/P * ZTEST * ... * * */ export function parsePackageContents( xml: string, ): Array<{ type: string; name: string; description: string; uri: string }> { const parsed = parseXml(xml); // After namespace stripping, asx:abap → abap, asx:values → values // fast-xml-parser structure depends on XML depth — use recursive finder as fallback let nodes = getDeepArray(parsed, ['abap', 'values', 'DATA', 'TREE_CONTENT', 'SEU_ADT_REPOSITORY_OBJ_NODE']); if (nodes.length === 0) { nodes = findDeepNodes(parsed, 'SEU_ADT_REPOSITORY_OBJ_NODE'); } return nodes.map((node: Record) => ({ type: String(node.OBJECT_TYPE ?? ''), name: String(node.OBJECT_NAME ?? ''), description: String(node.DESCRIPTION ?? ''), uri: String(node.OBJECT_URI ?? ''), })); } /** * Parse direct sub-packages from an ADT `repository/nodestructure` response * for `parent_type=DEVC/K`. * * SAP returns one `` per node under * ``. The response also includes: * - `DEVC/KI` rows for package-interface nodes, * which are NOT subpackages — these must be filtered out. * - Placeholder rows with `` (empty) representing the queried * package itself or expandable categories — also filtered out. * * Returns uppercased, deduplicated DEVCLASS names in document order. An * empty body (HTTP 200 with no payload — SAP's response for an unknown * `parent_name`) returns `[]`. Truly malformed XML propagates as a parse * exception from `fast-xml-parser`, which the caller surfaces as * `AdtApiError`. We never silently return `[]` for a malformed envelope — * the resolver relies on this to fail closed. */ export function parseSubpackageNodestructure(xml: string): string[] { // Empty body = "no children" (e.g. unknown parent on SAP returns 200 with empty payload). if (!xml || xml.trim().length === 0) return []; const parsed = parseXml(xml); let nodes = getDeepArray(parsed, ['abap', 'values', 'DATA', 'TREE_CONTENT', 'SEU_ADT_REPOSITORY_OBJ_NODE']); if (nodes.length === 0) { nodes = findDeepNodes(parsed, 'SEU_ADT_REPOSITORY_OBJ_NODE'); } const seen = new Set(); const out: string[] = []; for (const node of nodes) { const type = String(node.OBJECT_TYPE ?? ''); // DEVC/K only — drop DEVC/KI (package interfaces) and any unexpected types. if (type !== 'DEVC/K') continue; const name = String(node.OBJECT_NAME ?? '') .trim() .toUpperCase(); if (!name) continue; if (seen.has(name)) continue; seen.add(name); out.push(name); } return out; } /** * Parse table contents (datapreview response). * * SAP ADT returns two possible formats for data preview: * * Format 1 (older/asx): COLUMNS/COLUMN/METADATA + DATASET/DATA * Format 2 (newer/dataPreview namespace): columns/metadata + dataSet/data * * After namespace stripping, both converge but with different casing. * We try both patterns with fallback. */ function parseTableContentsObject(parsed: Record): { columns: string[]; rows: Record[]; } { // Try old format first: abap > values > COLUMNS > COLUMN let columns = getDeepArray(parsed, ['abap', 'values', 'COLUMNS', 'COLUMN']); if (columns.length === 0) { columns = findDeepNodes(parsed, 'COLUMN'); } // New format: dataPreview:columns → "columns" after NS strip // Each "columns" element contains "metadata" and "dataSet" if (columns.length === 0) { columns = findDeepNodes(parsed, 'columns'); } const colNames: string[] = []; const colData: string[][] = []; for (const col of columns) { // Old format: METADATA/@_name, DATASET/DATA // New format: metadata/@_name, dataSet/data const metadata = (col.METADATA ?? col.metadata) as Record | undefined; const name = String(metadata?.['@_name'] ?? ''); if (!name) continue; // skip non-column entries like totalRows, name, etc. colNames.push(name); const dataset = (col.DATASET ?? col.dataSet) as Record | undefined; const rawData = dataset?.DATA ?? dataset?.data; const data = Array.isArray(rawData) ? rawData.map(String) : rawData != null ? [String(rawData)] : []; colData.push(data as string[]); } // Pivot column-oriented to row-oriented const rowCount = colData.length > 0 ? colData[0]?.length : 0; const rows: Record[] = []; for (let i = 0; i < rowCount; i++) { const row: Record = {}; for (let j = 0; j < colNames.length; j++) { row[colNames[j]!] = colData[j]?.[i] ?? ''; } rows.push(row); } return { columns: colNames, rows }; } /** Metrics ADT returns alongside a datapreview result (already in the body, normally discarded). */ export interface DataPreviewMeta { /** Raw SAP count: may count input rows or be zero when SAP's separate count query fails. */ totalRows?: number; /** SAP timing in milliseconds; excludes network overhead and may exclude the separate count query. */ queryExecutionTimeMs?: number; /** The OpenSQL echo returned by SAP, without client-side whitespace normalization. */ executedQueryString?: string; } export interface DataPreviewResult extends DataPreviewMeta { columns: string[]; rows: Record[]; } function parseDataPreviewMetaObject(parsed: Record): DataPreviewMeta { const td = (parsed.tableData ?? parsed) as Record; const meta: DataPreviewMeta = {}; // Guard blank values too: an empty would otherwise coerce via Number('') to a spurious 0. const totalRowsText = td.totalRows != null ? String(td.totalRows).trim() : ''; const totalRows = Number(totalRowsText); if (totalRowsText !== '' && Number.isFinite(totalRows)) meta.totalRows = totalRows; const execMsText = td.queryExecutionTime != null ? String(td.queryExecutionTime).trim() : ''; const execMs = Number(execMsText); if (execMsText !== '' && Number.isFinite(execMs)) { meta.queryExecutionTimeMs = execMs; } const executed = td.executedQueryString; if (typeof executed === 'string' && executed.trim()) { meta.executedQueryString = executed; } return meta; } /** Parse data-preview rows and metrics from one shared fast-xml-parser object tree. */ export function parseDataPreviewResult(xml: string): DataPreviewResult { if (!xml || xml.trim().length === 0) return { columns: [], rows: [] }; const parsed = whitespacePreservingParser.parse(xml) as Record; return { ...parseTableContentsObject(parsed), ...parseDataPreviewMetaObject(parsed) }; } export function parseTableContents(xml: string): { columns: string[]; rows: Record[] } { if (!xml || xml.trim().length === 0) return { columns: [], rows: [] }; return parseTableContentsObject(whitespacePreservingParser.parse(xml) as Record); } /** * Parse the scalar metrics from a datapreview response — `totalRows`, `queryExecutionTime`, * `executedQueryString`. All optional: absent fields are omitted. Reads the same body * `parseTableContents` does; these are SAP diagnostics, not verified result totals or full request timings. */ export function parseDataPreviewMeta(xml: string): DataPreviewMeta { if (!xml || xml.trim().length === 0) return {}; return parseDataPreviewMetaObject(whitespacePreservingParser.parse(xml) as Record); } /** * Parse installed components response. * * SAP returns an Atom feed for /sap/bc/adt/system/components: * * * SAP_BASIS * 753;SAPKB75308;0008;SAP Basis Component * * * * The title field is semicolon-separated: release;sp_name;sp_level;description */ export function parseInstalledComponents( xml: string, ): Array<{ name: string; release: string; spName: string; spLevel: string; description: string }> { const parsed = parseXml(xml); // After removeNSPrefix: atom:feed → feed, atom:entry → entry const entries = getNestedArray(parsed, 'feed', 'entry'); return entries.map((entry: Record) => { const name = String(entry.id ?? ''); const title = String(entry.title ?? ''); // Title format: "release;sp_name;sp_level;description" const parts = title.split(';'); return { name, release: parts[0]?.trim() ?? '', spName: parts[1]?.trim() ?? '', spLevel: parts[2]?.trim() ?? '', description: parts[3]?.trim() ?? title, }; }); } /** * Parse ABAP syntax-configurations response (/sap/bc/adt/abapsource/syntax/configurations). * * * * * X * Standard ABAP * * * * ... * * * Feature detection uses the Standard ABAP entry (version="X") as a fallback * release signal when installed components do not expose SAP_BASIS. */ export function parseSyntaxConfigurations(xml: string): Array<{ version: string; description: string; etag: string }> { const parsed = parseXml(xml); const configs = getNestedArray(parsed, 'syntaxConfigurations', 'syntaxConfiguration'); return configs.map((cfg: Record) => { const language = (cfg.language ?? {}) as Record; const linkRaw = language.link; // `link` is forced to array by the parser config; take the first element. const link = (Array.isArray(linkRaw) ? linkRaw[0] : (linkRaw ?? {})) as Record; return { version: String(language.version ?? ''), description: String(language.description ?? ''), etag: String(link['@_etag'] ?? ''), }; }); } /** * Parse a function group's structure from the ADT **objectstructure** response * (`/sap/bc/adt/functions/groups//objectstructure`). * * The plain `/functions/groups/` resource returns only group metadata + * atom links — NO function-module list — which is why the old parser (reading a * ``/`functionModule` shape that ADT never emits) always returned empty. * The objectstructure response is a tree of `` nodes, each * tagged with `adtcore:type`: the root is `FUGR/F` (the group), `FUGR/FF` children * are function modules, `FUGR/I` children are includes, `FUGR/PX` is the main * program. Verified live on a4h (see tests/fixtures/xml/function-group.xml). */ export function parseFunctionGroup(xml: string): FunctionGroupStructure { const parsed = parseXml(xml); // parseXml wraps elements in arrays, so the root arrives as // a one-element array; its children are nested under the same (array) key. const root = toRecordArray(parsed.objectStructureElement)[0] ?? {}; const functions: string[] = []; const includes: string[] = []; for (const child of toRecordArray(root.objectStructureElement)) { const type = String(child['@_type'] ?? ''); const childName = String(child['@_name'] ?? ''); if (!childName) continue; if (type === 'FUGR/FF') functions.push(childName); else if (type === 'FUGR/I') includes.push(childName); } return { name: String(root['@_name'] ?? ''), functions, includes }; } /** * Parse a function group's structure from the GENERIC repository objectstructure * response (`/sap/bc/adt/repository/objectstructure?objectname=X&objecttype=FUGR/F`). * * This is the pre-7.52 fallback: `/functions/groups//objectstructure` 404s on * NW 7.50 under every Accept, while the generic resource works there. The payload is a * different shape — a FLAT list of `` elements with unprefixed * lowercase attributes — so it needs its own parser rather than a tweak to * `parseFunctionGroup`. Folder nodes carry an `objecttype` but no `objectname`, and real * groups also emit FUGR/PD|PM|PO|PT|PU|PZ (dynpros, PBO/PAI modules, text elements) plus * PROG/* nodes, so everything that is not FUGR/FF or FUGR/I is ignored. * * The group name is NOT in the response — callers pass it through. * Verified live on npl 7.50 (see tests/fixtures/xml/function-group-projectexplorer.xml). */ export function parseFunctionGroupNodes(xml: string, groupName: string): FunctionGroupStructure { const parsed = parseXml(xml); const root = toRecordArray(parsed.objectstructure)[0] ?? {}; const functions: string[] = []; const includes: string[] = []; for (const node of toRecordArray(root.node)) { // Folders are grouping headers ("Includes", "Function Modules") — they carry an // objecttype but never an objectname, so the name check alone would not skip them. if (String(node['@_isfolder'] ?? '') === 'true') continue; const type = String(node['@_objecttype'] ?? ''); const nodeName = String(node['@_objectname'] ?? ''); if (!nodeName) continue; if (type === 'FUGR/FF') functions.push(nodeName); else if (type === 'FUGR/I') includes.push(nodeName); } return { name: groupName, functions, includes }; } /** * Attributes ARC-1 writes on a function module. SAP's fmodule resource rejects a * hand-built partial envelope (`400 ExceptionInvalidData` / "Unexpected Case in Branch"), * so the only working write is GET → mutate this document → PUT it back verbatim. * Live-verified on npl 7.50 + a4h 758 — see * docs/research/2026-07-29-nw750-fixture-create-surface.md §8.1. */ export function parseFunctionModuleProperties(xml: string): FunctionModuleProperties { // Scope to the root element first so an attribute elsewhere in the document can't match, // and accept either quote style — SAP is not consistent across releases. const root = /]*>/i.exec(xml)?.[0]; const pick = (attr: string): string | undefined => { if (!root) return undefined; const m = new RegExp(`\\bfmodule:${attr}\\s*=\\s*(?:"([^"]*)"|'([^']*)')`, 'i').exec(root); return m?.[1] ?? m?.[2]; }; const props: FunctionModuleProperties = {}; const processingType = pick('processingType'); if (processingType) props.processingType = processingType; const updateTaskKind = pick('updateTaskKind'); if (updateTaskKind) props.updateTaskKind = updateTaskKind; const releaseState = pick('releaseState'); if (releaseState) props.releaseState = releaseState; return props; } /** * Parse ADT system discovery XML into structured info. * * The discovery response is an Atom service document that lists available * ADT workspaces/collections. We extract collection titles and hrefs * to determine what capabilities the SAP system has. * * The authenticated username is passed in from the client config since * the discovery XML doesn't directly contain "you are logged in as X". */ export function parseSystemInfo( xml: string, username: string, ): { user: string; collections: Array<{ title: string; href: string }> } { const parsed = parseXml(xml); // Atom service document: service > workspace > collection const collections: Array<{ title: string; href: string }> = []; // After namespace stripping: app:service → service, app:workspace → workspace, app:collection → collection const service = (parsed.service ?? parsed.service ?? {}) as Record; const workspaces = Array.isArray(service.workspace) ? service.workspace : service.workspace ? [service.workspace] : []; for (const ws of workspaces as Array>) { const cols = Array.isArray(ws.collection) ? ws.collection : ws.collection ? [ws.collection] : []; for (const col of cols as Array>) { const title = String(col.title ?? col['@_title'] ?? ''); const href = String(col['@_href'] ?? ''); if (title || href) { collections.push({ title, href }); } } } return { user: username ?? '', collections }; } /** * Parse ADT discovery service document into endpoint -> accepted MIME types. * * The service document is AtomPub: * service > workspace[] > collection[] > accept[] */ export function parseDiscoveryDocument(xml: string): Map { if (!xml?.trim()) return new Map(); try { return parseDiscoveryObject(parseXml(xml)); } catch { return new Map(); } } /** Map an already-parsed discovery document without parsing its XML a second time. */ export function parseDiscoveryObject(parsed: Record): Map { try { const service = (parsed.service ?? {}) as Record; const workspaces = Array.isArray(service.workspace) ? service.workspace : service.workspace ? [service.workspace] : []; const discoveryMap = new Map(); for (const ws of workspaces as Array>) { const collections = Array.isArray(ws.collection) ? ws.collection : ws.collection ? [ws.collection] : []; for (const collection of collections as Array>) { const href = String(collection['@_href'] ?? ''); const normalizedPath = normalizeDiscoveryPath(href); if (!normalizedPath) continue; const acceptsRaw = Array.isArray(collection.accept) ? collection.accept : collection.accept != null ? [collection.accept] : []; const accepts = acceptsRaw.map((value) => String(value)).filter((value) => value.length > 0); // A listed collection still exists when this user has no advertised POST media types. // Retain its presence; an empty duplicate must not erase an earlier usable definition. if (accepts.length > 0 || !discoveryMap.has(normalizedPath)) { discoveryMap.set(normalizedPath, accepts); } } } return discoveryMap; } catch { return new Map(); } } function normalizeDiscoveryPath(href: string): string | undefined { if (!href) return undefined; let path = href.trim(); if (!path) return undefined; // Absolute URL -> extract pathname. if (/^https?:\/\//i.test(path)) { try { path = new URL(path).pathname; } catch { return undefined; } } // Normalize leading slash. if (!path.startsWith('/')) { path = `/${path}`; } // Keep only ADT paths. const adtPrefix = '/sap/bc/adt/'; if (!path.startsWith(adtPrefix)) { const idx = path.indexOf(adtPrefix); if (idx < 0) return undefined; path = path.slice(idx); } // Remove trailing slash for stable map keys. if (path.length > adtPrefix.length && path.endsWith('/')) { path = path.slice(0, -1); } return path; } /** * Parse domain metadata XML from /sap/bc/adt/ddic/domains/{name}. * * Domains don't have /source/main — they return structured XML with * type information, output characteristics, value table, and fixed values. * * Expected root: with nested . */ export function parseDomainMetadata(xml: string): DomainInfo { const parsed = parseXml(xml); // After NS strip: doma:domain → domain const domain = (parsed.domain ?? {}) as Record; const content = (domain.content ?? {}) as Record; const typeInfo = (content.typeInformation ?? {}) as Record; const outputInfo = (content.outputInformation ?? {}) as Record; const valueInfo = (content.valueInformation ?? {}) as Record; const pkgRef = (domain.packageRef ?? {}) as Record; // Parse fixed values if present const fixedValues: Array<{ low: string; high: string; description: string }> = []; const fvContainer = valueInfo.fixValues ?? valueInfo.fixedValues; if (fvContainer && typeof fvContainer === 'object') { const fvNodes = findDeepNodes(fvContainer as Record, 'fixValue'); for (const fv of fvNodes) { fixedValues.push({ low: String(fv.low ?? fv['@_low'] ?? ''), high: String(fv.high ?? fv['@_high'] ?? ''), description: String(fv.text ?? fv.description ?? fv['@_text'] ?? fv['@_description'] ?? ''), }); } } // Parse value table reference const valueTableRef = (valueInfo.valueTableRef ?? {}) as Record; return { name: String(domain['@_name'] ?? ''), description: String(domain['@_description'] ?? ''), dataType: String(typeInfo.datatype ?? ''), length: String(typeInfo.length ?? ''), decimals: String(typeInfo.decimals ?? ''), outputLength: String(outputInfo.length ?? ''), conversionExit: String(outputInfo.conversionExit ?? ''), signExists: String(outputInfo.signExists ?? '') === 'true', lowercase: String(outputInfo.lowercase ?? '') === 'true', valueTable: String(valueTableRef['@_name'] ?? ''), fixedValues, package: String(pkgRef['@_name'] ?? ''), }; } /** * Parse data element metadata XML from /sap/bc/adt/ddic/dataelements/{name}. * * Data elements don't have /source/main — they return structured XML with * domain/type reference, field labels, search help, and other metadata. * * Expected root: with nested . */ export function parseDataElementMetadata(xml: string): DataElementInfo { const parsed = parseXml(xml); // After NS strip: blue:wbobj → wbobj const wbobj = (parsed.wbobj ?? {}) as Record; const pkgRef = (wbobj.packageRef ?? {}) as Record; // Find the dataElement node — after NS strip: dtel:dataElement → dataElement const dtelNodes = findDeepNodes(parsed, 'dataElement'); const dtel = dtelNodes[0] ?? {}; const flag = (value: unknown) => String(value ?? '').toLowerCase() === 'true'; return { name: String(wbobj['@_name'] ?? ''), description: String(wbobj['@_description'] ?? ''), typeKind: String(dtel.typeKind ?? ''), typeName: String(dtel.typeName ?? ''), dataType: String(dtel.dataType ?? ''), length: String(dtel.dataTypeLength ?? ''), decimals: String(dtel.dataTypeDecimals ?? ''), shortLabel: String(dtel.shortFieldLabel ?? ''), shortLength: String(dtel.shortFieldLength ?? ''), mediumLabel: String(dtel.mediumFieldLabel ?? ''), mediumLength: String(dtel.mediumFieldLength ?? ''), longLabel: String(dtel.longFieldLabel ?? ''), longLength: String(dtel.longFieldLength ?? ''), headingLabel: String(dtel.headingFieldLabel ?? ''), headingLength: String(dtel.headingFieldLength ?? ''), searchHelp: String(dtel.searchHelp ?? ''), searchHelpParameter: String(dtel.searchHelpParameter ?? ''), setGetParameter: String(dtel.setGetParameter ?? ''), defaultComponentName: String(dtel.defaultComponentName ?? ''), deactivateInputHistory: flag(dtel.deactivateInputHistory), changeDocument: flag(dtel.changeDocument), leftToRightDirection: flag(dtel.leftToRightDirection), deactivateBIDIFiltering: flag(dtel.deactivateBIDIFiltering), package: String(pkgRef['@_name'] ?? ''), }; } /** * Parse authorization field metadata from /sap/bc/adt/aps/iam/auth/{name}. * * Expected root: with IAM field metadata and org-level entries. */ export function parseAuthorizationField(xml: string): AuthorizationFieldInfo { const parsed = parseXml(xml); // After NS strip: auth:auth → auth (root). Fall back to findDeepNodes for robustness. const auth = (parsed.auth ?? findDeepNodes(parsed, 'auth')[0] ?? {}) as Record; const content = (auth.content ?? {}) as Record; const pkgRef = (auth.packageRef ?? {}) as Record; // Real SAP responses wrap fields under ; older shapes put them at root. Support both. const field = (key: string): unknown => content[key] ?? auth[key]; const orgLevelInfo = toStringArray(content.orglvlinfo ?? auth.orglvlinfo); return { name: String(field('fieldName') ?? auth['@_name'] ?? ''), description: String(auth['@_description'] ?? ''), roleName: String(field('rollName') ?? ''), checkTable: String(field('checkTable') ?? ''), domainName: String(field('domname') ?? ''), outputLength: String(field('outputlen') ?? ''), conversionExit: String(field('convexit') ?? ''), exitFunctionModule: String(field('exitFB') ?? ''), package: String(pkgRef['@_name'] ?? ''), orgLevelInfo, masterLanguage: String(auth['@_masterLanguage'] ?? ''), }; } /** * Parse feature toggle states JSON from /sap/bc/adt/sfw/featuretoggles/{name}/states. */ export function parseFeatureToggleStates(json: string, name: string): FeatureToggleInfo { let parsed: Record; try { parsed = JSON.parse(json) as Record; } catch (err) { const reason = err instanceof Error ? err.message : 'Invalid JSON'; throw new AdtApiError( `ADT_JSON_PARSE: Failed to parse feature toggle states for "${name}": ${reason}`, 500, `/sap/bc/adt/sfw/featuretoggles/${encodeURIComponent(name)}/states`, json, ); } // SAP wraps the payload in a STATES object with upper-case keys. const wrap = (parsed.STATES ?? parsed) as Record; const normalizeState = (raw: unknown): 'on' | 'off' | 'unknown' => { const s = String(raw ?? '').toLowerCase(); return s === 'on' ? 'on' : s === 'off' ? 'off' : 'unknown'; }; const clientStatesRaw = Array.isArray(wrap.CLIENT_STATES) ? wrap.CLIENT_STATES : []; const states = clientStatesRaw.map((entry) => { const row = (entry ?? {}) as Record; const description = String(row.DESCRIPTION ?? ''); return { client: String(row.CLIENT ?? ''), state: normalizeState(row.STATE), ...(description ? { description } : {}), }; }); const userStatesRaw = Array.isArray(wrap.USER_STATES) ? wrap.USER_STATES : []; const userStates = userStatesRaw.map((entry) => { const row = (entry ?? {}) as Record; return { client: String(row.CLIENT ?? ''), user: String(row.USER ?? ''), state: normalizeState(row.STATE), }; }); return { name: String(wrap.NAME ?? name), clientState: String(wrap.CLIENT_STATE ?? ''), userState: String(wrap.USER_STATE ?? ''), states, userStates, }; } /** Parse BAdI metadata (XHB v4 or legacy XH v1), rooted at enho:objectData. */ export function parseEnhancementImplementation(xml: string): EnhancementImplementationInfo { const parsed = parseXml(xml); const objectData = (parsed.objectData ?? findDeepNodes(parsed, 'objectData')[0] ?? {}) as Record; const pkgRef = (objectData.packageRef ?? {}) as Record; const contentCommon = (objectData.contentCommon ?? {}) as Record; const contentSpecific = (objectData.contentSpecific ?? {}) as Record; // Real responses wrap impls: contentSpecific > badiTechnology > badiImplementations > badiImplementation[] // badiTechnology may be an empty element (text value) on implementations with no BAdIs. const badiTech = contentSpecific.badiTechnology; const badiTechRec = badiTech && typeof badiTech === 'object' ? (badiTech as Record) : ({} as Record); const badiImplContainer = (badiTechRec.badiImplementations ?? contentSpecific.badiImplementations ?? {}) as Record< string, unknown >; const badiImplNodes = toRecordArray(badiImplContainer.badiImplementation); const technology = String( contentCommon['@_toolType'] ?? (typeof badiTech === 'string' || typeof badiTech === 'number' ? badiTech : ''), ); return { name: String(objectData['@_name'] ?? ''), description: String(objectData['@_description'] ?? ''), package: String(pkgRef['@_name'] ?? ''), technology, switchSupported: String(contentCommon['@_switchSupported'] ?? '') === 'true', badiImplementations: badiImplNodes.map((node) => { const implementingClass = (node.implementingClass ?? {}) as Record; const badiDefinition = (node.badiDefinition ?? {}) as Record; const enhancementSpot = (node.enhancementSpot ?? {}) as Record; return { name: String(node['@_name'] ?? ''), shortText: String(node['@_shortText'] ?? ''), implementingClass: String(implementingClass['@_name'] ?? ''), badiDefinition: String(badiDefinition['@_name'] ?? ''), enhancementSpot: String(enhancementSpot['@_name'] ?? ''), active: String(node['@_active'] ?? node['@_isActive'] ?? '') === 'true', default: String(node['@_default'] ?? node['@_isDefault'] ?? '') === 'true', }; }), }; } /** * Parse transaction metadata XML from /sap/bc/adt/vit/wb/object_type/trant/object_name/{name}. * * Returns basic transaction info: code, description, package. * The program name is not in this endpoint — use SQL (TSTC) for full details. * * Expected root: . */ export function parseTransactionMetadata(xml: string): TransactionInfo { const parsed = parseXml(xml); // After NS strip: adtcore:mainObject → mainObject const obj = (parsed.mainObject ?? {}) as Record; const pkgRef = (obj.packageRef ?? {}) as Record; return { code: String(obj['@_name'] ?? ''), description: String(obj['@_description'] ?? ''), program: '', // Not available from this endpoint — populated via SQL in handler package: String(pkgRef['@_name'] ?? ''), }; } /** * Parse service binding metadata XML into a human-readable summary. * * SRVB objects don't have editable source — they're structured XML with binding configuration. * We extract the key fields into a JSON summary: * - name, description, OData version (V2/V4), binding type (UI/Web API) * - service definition reference, publish status, contract * Compact JSON — returned verbatim to the LLM as SAPRead(type="SRVB").source.*/ export function parseServiceBinding(xml: string): string { const parsed = parseXml(xml); const sb = (parsed.serviceBinding ?? {}) as Record; // Extract binding info const binding = (sb.binding ?? {}) as Record; const services = sb.services as Record | undefined; const content = (services?.content ?? {}) as Record; const srvDef = (content?.serviceDefinition ?? {}) as Record; const pkg = (sb.packageRef ?? {}) as Record; const result = { name: String(sb['@_name'] ?? ''), description: String(sb['@_description'] ?? ''), type: String(sb['@_type'] ?? ''), odataVersion: String(binding['@_version'] ?? ''), bindingType: String(binding['@_type'] ?? ''), bindingCategory: binding['@_category'] === '0' ? 'UI' : binding['@_category'] === '1' ? 'Web API' : String(binding['@_category'] ?? ''), published: sb['@_published'] === 'true', bindingCreated: sb['@_bindingCreated'] === 'true', contract: String(sb['@_contract'] ?? ''), releaseSupported: sb['@_releaseSupported'] === 'true', serviceDefinition: String(srvDef['@_name'] ?? ''), serviceName: String(services?.['@_name'] ?? ''), serviceVersion: String(content?.['@_version'] ?? ''), releaseState: String(content?.['@_releaseState'] ?? ''), package: String(pkg['@_name'] ?? ''), implementation: String((binding.implementation as Record)?.['@_name'] ?? ''), language: String(sb['@_language'] ?? ''), changedAt: String(sb['@_changedAt'] ?? ''), changedBy: String(sb['@_changedBy'] ?? ''), }; return JSON.stringify(result); } /** * Parse message class metadata XML from /sap/bc/adt/messageclass/{name}. * * Message classes are metadata-only (no /source/main). The XML contains * the message class attributes and individual messages as mc:messages elements. * * Expected root: (after NS strip: messageClass). */ export function parseMessageClass(xml: string): MessageClassInfo { const parsed = parseXml(xml); const mc = (parsed.messageClass ?? {}) as Record; const pkgRef = (mc.packageRef ?? {}) as Record; const msgNodes = Array.isArray(mc.messages) ? (mc.messages as Array>) : []; const messages = msgNodes.map((m) => ({ number: String(m['@_msgno'] ?? ''), shortText: String(m['@_msgtext'] ?? ''), })); return { name: String(mc['@_name'] ?? ''), description: String(mc['@_description'] ?? ''), messages, package: String(pkgRef['@_name'] ?? ''), }; } // ─── BSP / UI5 Filestore Parsers ──────────────────────────────────── /** * Parse BSP app list from /sap/bc/adt/filestore/ui5-bsp/objects. * * Returns an Atom feed where each entry has: * - → app name * - → description */ export function parseBspAppList(xml: string): BspAppInfo[] { const parsed = parseXml(xml); const entries = getNestedArray(parsed, 'feed', 'entry'); return entries.map((entry: Record) => { const summary = entry.summary; // desc → fast-xml-parser returns {#text, @_type} when attributes present const description = typeof summary === 'string' ? summary : String((summary as Record)?.['#text'] ?? ''); return { name: String(entry.title ?? ''), description, }; }); } /** * Parse BSP folder listing from /sap/bc/adt/filestore/ui5-bsp/objects/{app}/content. * * Each entry has: * - → type * - → full path like "APPNAME/Component.js" * - → etag for files * * We extract the relative path by stripping the appName prefix, * and the file/folder name from the last path segment. */ export function parseBspFolderListing(xml: string, appName: string): BspFileNode[] { const parsed = parseXml(xml); const entries = getNestedArray(parsed, 'feed', 'entry'); return entries.map((entry: Record) => { const title = String(entry.title ?? ''); const category = entry.category as Record | undefined; const term = String(category?.['@_term'] ?? 'file'); const nodeType = term === 'folder' ? 'folder' : 'file'; const content = entry.content as Record | undefined; const etag = content?.['@_etag']; // Path relative to app root const path = title.startsWith(appName) ? title.substring(appName.length) : `/${title}`; // Name is the last segment const name = title.split('/').pop() || title; return { name, path, type: nodeType, ...(etag != null ? { etag: String(etag) } : {}), }; }); } // ─── Helpers ──────────────────────────────────────────────────────── /** Safely get a nested array from parsed XML. * Absent, empty (`` → `''` on 7.50) and single-node containers all collapse to an array. */ export function getNestedArray( obj: Record, parent: string, child: string, ): Array> { const parentObj = obj[parent] as Record | undefined; if (!parentObj) return []; const arr = parentObj[child]; if (Array.isArray(arr)) return arr as Array>; if (arr && typeof arr === 'object') return [arr as Record]; return []; } /** Recursively find an array by key name, anywhere in the object tree */ export function findDeepNodes(obj: unknown, key: string): Array> { if (!obj || typeof obj !== 'object') return []; if (Array.isArray(obj)) { for (const item of obj) { const found = findDeepNodes(item, key); if (found.length > 0) return found; } return []; } const record = obj as Record; if (key in record) { const val = record[key]; if (Array.isArray(val)) return val as Array>; if (val && typeof val === 'object') return [val as Record]; } for (const val of Object.values(record)) { const found = findDeepNodes(val, key); if (found.length > 0) return found; } return []; } /** A parsed `nameditem:namedItem`: identifier (`name`), human text (`description`), optional structured `data`. */ export interface NamedItem { name: string; description: string; data: string; } /** * Parse a `nameditem:namedItemList` value-help response. Shared by transport layers/targets and * the ATC variant listing — any ADT endpoint that returns the generic named-item feed. */ export function parseNamedItems(xml: string): NamedItem[] { const parsed = parseXml(xml); // The parser wraps some leaf elements (e.g. `data`) in single-element arrays; unwrap. const str = (v: unknown): string => { const x = Array.isArray(v) ? v[0] : v; return typeof x === 'string' ? x : typeof x === 'number' ? String(x) : ''; }; // Some items carry markup (e.g. "gCTS generated

Target: DEV

") — strip tags, collapse whitespace. const clean = (v: unknown): string => str(v) .replace(/<[^>]*>/g, ' ') .replace(/\s+/g, ' ') .trim(); return findDeepNodes(parsed, 'namedItem').map((item) => { const rec = item as Record; // `name` is an identifier passed back verbatim (only trim); `description`/`data` get cleaned. return { name: str(rec.name).trim(), description: clean(rec.description), data: clean(rec.data) }; }); } /** * Read the system default ATC check variant from an `` response — the * `` entry. This is the system's CONFIGURED ATC * variant; SAP does NOT apply it on an empty `checkVariant` (that runs `DEFAULT`), so `runAtcCheck` * sends it explicitly. Returns undefined when the property is absent. */ export function parseAtcSystemCheckVariant(xml: string): string | undefined { const parsed = parseXml(xml); for (const prop of findDeepNodes(parsed, 'property')) { if (prop['@_name'] === 'systemCheckVariant') { const value = prop['@_value']; return typeof value === 'string' && value ? value : undefined; } } return undefined; } /** * Map ADT class category numeric codes to human-readable AFF enum strings. * * Category codes from SAP ADT `class:category` attribute: * "00" = general, "40" = exit class, "01" = exception, etc. */ const CLASS_CATEGORY_MAP: Record = { '00': 'generalObjectType', '01': 'exceptionClass', '02': 'persistentClass', '03': 'behaviorClass', '04': 'businessClass', '05': 'factoryForPersistentClass', '06': 'statusClassForPersistClass', '11': 'rfcProxyClass', '12': 'communicationConnectionClass', '14': 'areaClassSharedObjects', '30': 'bspApplicationClass', '31': 'basisClassBspElementHdlr', '32': 'webDynproRuntimeObject', '33': 'entityEventHandler', '40': 'exitClass', '41': 'testclassAbapUnit', }; /** * Parse class metadata XML from /sap/bc/adt/oo/classes/{name}. * * Classes without /source/main return structured XML with description, * language version, category, fixPointArithmetic, and package info. * * Expected root: (after NS strip: abapClass). */ export function parseClassMetadata(xml: string): ClassMetadata { const parsed = parseXml(xml); const cls = (parsed.abapClass ?? {}) as Record; const pkgRef = (cls.packageRef ?? {}) as Record; const rawCategory = String(cls['@_category'] ?? ''); // is present on behavior pool classes (category=behaviorPool). // It binds the class back to its root CDS entity (the BDEF/DDLS name); used by // SAPWrite(action="generate_behavior_implementation") to auto-discover the BDEF // without a second metadata round-trip. Absent on regular classes. const rootEntityRefRaw = cls.rootEntityRef as Record | undefined; const rootEntityRefName = String(rootEntityRefRaw?.['@_name'] ?? ''); const rootEntityRef = rootEntityRefName ? { name: rootEntityRefName, type: String(rootEntityRefRaw?.['@_type'] ?? ''), uri: String(rootEntityRefRaw?.['@_uri'] ?? ''), } : undefined; return { name: String(cls['@_name'] ?? ''), description: String(cls['@_description'] ?? ''), language: String(cls['@_language'] ?? ''), ...(cls['@_abapLanguageVersion'] != null ? { abapLanguageVersion: String(cls['@_abapLanguageVersion']) } : {}), category: CLASS_CATEGORY_MAP[rawCategory] ?? rawCategory, fixPointArithmetic: String(cls['@_fixPointArithmetic'] ?? 'false') === 'true', package: String(pkgRef['@_name'] ?? ''), ...(rootEntityRef ? { rootEntityRef } : {}), }; } /** * Parse the metadata of a server-driven (AFF generic) object — the contract shared by DESD, EVTB, * DTSC, COTA, DSFD (root ``) and DTDC (root ``). `removeNSPrefix` * strips the prefix, so the root is keyed by its local name (`rootLocalName`: `blueSource` / * `dtdcSource`). The attribute shape is identical across formats. Optional fields omitted when empty. */ export function parseServerDrivenMetadata(xml: string, rootLocalName: string): ServerDrivenObjectMetadata { const root = (parseXml(xml)[rootLocalName] ?? {}) as Record; const pkgRef = (root.packageRef ?? {}) as Record; const str = (k: string): string => { const v = root[k]; return v == null ? '' : String(v); }; const meta: ServerDrivenObjectMetadata = { name: str('@_name'), type: str('@_type') }; const opt = (key: keyof ServerDrivenObjectMetadata, attr: string): void => { const v = str(attr); if (v) (meta as unknown as Record)[key] = v; }; opt('description', '@_description'); opt('masterLanguage', '@_masterLanguage'); opt('abapLanguageVersion', '@_abapLanguageVersion'); opt('responsible', '@_responsible'); opt('version', '@_version'); opt('changedBy', '@_changedBy'); opt('changedAt', '@_changedAt'); opt('createdBy', '@_createdBy'); opt('createdAt', '@_createdAt'); const pkg = pkgRef['@_name'] == null ? '' : String(pkgRef['@_name']); if (pkg) meta.package = pkg; return meta; } /** Safely traverse a deep path and return an array at the end */ function getDeepArray(obj: Record, path: string[]): Array> { let current: unknown = obj; for (const key of path.slice(0, -1)) { if (current && typeof current === 'object' && !Array.isArray(current)) { current = (current as Record)[key]; } else { return []; } } const lastKey = path[path.length - 1]!; if (current && typeof current === 'object' && !Array.isArray(current)) { const arr = (current as Record)[lastKey]; if (Array.isArray(arr)) return arr as Array>; if (arr && typeof arr === 'object') return [arr as Record]; } return []; } export function toRecordArray(value: unknown): Array> { if (Array.isArray(value)) { return value.filter((item): item is Record => Boolean(item) && typeof item === 'object'); } if (value && typeof value === 'object') { return [value as Record]; } return []; } function toStringArray(value: unknown): string[] { if (Array.isArray(value)) return value.map((entry) => String(entry ?? '')); if (value === undefined || value === null) return []; return [String(value)]; } /** Parse inactive objects response from /sap/bc/adt/activation/inactiveobjects. * Supports three response shapes (all live-verified): * - Rich `` (vendor MIME on every supported release, includes user/transport/deleted metadata): * * * * * * ... * - Flat with `application/xml` Accept (NW 7.50 + legacy): * ... * - Flat root-level (very old): * ... * Detection: rich shape if any has a nested ; otherwise flat. */ export function parseInactiveObjects(xml: string): InactiveObject[] { if (!xml.trim()) return []; const parsed = parseXml(xml); const entries = findDeepNodes(parsed, 'entry'); const hasRichObjects = entries.some((entry) => toRecordArray((entry as Record).object).some((object) => { const refs = toRecordArray(object.ref); return refs.length > 0; }), ); if (hasRichObjects) { const results: InactiveObject[] = []; for (const entry of entries) { const entryRecord = entry as Record; for (const object of toRecordArray(entryRecord.object)) { const ref = toRecordArray(object.ref)[0]; if (!ref) continue; const transportRef = toRecordArray(toRecordArray(entryRecord.transport)[0]?.ref)[0]; results.push({ name: String(ref['@_name'] ?? ''), type: String(ref['@_type'] ?? ''), uri: String(ref['@_uri'] ?? ''), ...(ref['@_description'] ? { description: String(ref['@_description']) } : {}), ...(object['@_user'] ? { user: String(object['@_user']) } : {}), ...(object['@_deleted'] !== undefined ? { deleted: String(object['@_deleted']).toLowerCase() === 'true' } : {}), ...(transportRef?.['@_name'] ? { transport: String(transportRef['@_name']) } : {}), ...(transportRef?.['@_parentUri'] ? { parentTransport: String(transportRef['@_parentUri']) } : {}), }); } } return results; } // Flat objectReference shape (legacy + NW 7.50 with generic Accept). Each inactive object // is usually in its own entry, but very old responses put objectReference nodes directly // under the root. Use entries when present, else search the full doc. const flatResults: InactiveObject[] = []; const flatContainers = entries.length > 0 ? entries : [parsed]; for (const container of flatContainers) { for (const ref of findDeepNodes(container, 'objectReference')) { flatResults.push({ name: String(ref['@_name'] ?? ''), type: String(ref['@_type'] ?? ''), uri: String(ref['@_uri'] ?? ''), ...(ref['@_description'] ? { description: String(ref['@_description']) } : {}), }); } } return flatResults; } export { parseRevisionFeed } from './revision-feed.js'; // ─── parseClassStructure (issue #303) ───────────────────────────────────── /** * Parse a `#start=L,C;end=L,C` fragment from an `` href into a `LineRange`. * * Returns `null` if the fragment doesn't match — callers treat `null` as "this * element doesn't carry a range" (e.g. the `CLAS/OCX` text-elements ref has no * `#start=…` in its `definitionIdentifier` href, just a deep-link URL). */ function parseLineRange(href: string): LineRange | null { const m = href.match(/#start=(\d+),(\d+);end=(\d+),(\d+)/); if (!m) return null; return { sr: +m[1], sc: +m[2], er: +m[3], ec: +m[4] }; } /** * Parse `/sap/bc/adt/oo/classes/{name}/objectstructure` XML into a `ClassStructure`. * * Wire shape varies across SAP releases: * * **Kernel 7.58+ (S/4HANA 2023):** every method is ONE `` * with `adtcore:type="CLAS/OM"`, carrying both `definitionBlock` and * `implementationBlock` atom:link children. * * **Kernel 7.50 (NW 7.50 SP02 / NPL):** methods are SPLIT into two elements with * the same `adtcore:name` — `CLAS/OO` (carries `definitionBlock` + identifiers) * and `CLAS/OM` (carries `implementationBlock` + identifiers). This parser groups * by name and merges, so callers see one `MethodStructure` per method on either * release. ABSTRACT methods have a `CLAS/OO` entry only (no `implementationBlock`). * * Live evidence: fixtures `tests/fixtures/xml/objectstructure-clas-a4h-758.xml` * (single-element shape) and `objectstructure-clas-npl-750.xml` (split shape). * * Scoped regexes preserve the `adtcore:type` prefix used to merge OO/OM entries; * the shared XML parser's `removeNSPrefix` setting would strip it. */ export function parseClassStructure(xml: string, className?: string): ClassStructure { if (!xml.trim()) { throw new AdtApiError('parseClassStructure: empty XML response', 0, ''); } // Top-level class name (preferred from xml attribute; fall back to caller-provided). const rootMatch = xml.match(/]*\badtcore:name="([^"]+)"/); const resolvedClassName = rootMatch?.[1] ?? className ?? ''; // The XML is a single root `` (the class itself, // type CLAS/OC) that WRAPS the per-method/attribute children of the same element // name. A naive non-greedy regex eats the first child's close tag as the root's // close tag, so we strip the outer wrapper before scanning for children. // // Inner-content extraction: find the first `>` of the root (end of root open tag) // and the last `` (the root close tag). const rootOpenEnd = xml.indexOf('>', xml.indexOf(''); const inner = rootOpenEnd >= 0 && rootCloseStart > rootOpenEnd ? xml.slice(rootOpenEnd + 1, rootCloseStart) : xml; // Class-level blocks live in the root element's OWN atom:link children, which // precede the first nested . Scope the search to that // prefix so a method's definitionBlock can never be mistaken for the class // block, regardless of how SAP orders elements across releases. const firstChildIdx = inner.indexOf('= 0 ? inner.slice(0, firstChildIdx) : inner; const classDefMatch = classScope.match( /rel="http:\/\/www\.sap\.com\/adt\/relations\/source\/definitionBlock"[^>]*href="([^"]+)"/, ); const classImplMatch = classScope.match( /rel="http:\/\/www\.sap\.com\/adt\/relations\/source\/implementationBlock"[^>]*href="([^"]+)"/, ); if (!classDefMatch) { throw new AdtApiError( 'parseClassStructure: response missing class-level definitionBlock atom:link', 0, xml.slice(0, 256), ); } const classDef = parseLineRange(classDefMatch[1]); if (!classDef) { throw new AdtApiError( `parseClassStructure: class definitionBlock href has no #start fragment: ${classDefMatch[1]}`, 0, '', ); } const classImpl = classImplMatch ? (parseLineRange(classImplMatch[1]) ?? undefined) : undefined; // Children themselves do NOT nest objectStructureElement — they only contain // self-closing elements. So a non-greedy match on the children // is safe inside `inner`. const elemRe = /]*adtcore:type="CLAS\/[A-Z]+"[^>]*)>([\s\S]*?)<\/abapsource:objectStructureElement>/g; // 7.50 split shape: per-name accumulators. type PartialMethod = { name: string; redefinition?: boolean; visibility?: 'public' | 'protected' | 'private'; level?: 'instance' | 'static'; abstract: boolean; constructor: boolean; definition?: LineRange; implementation?: LineRange; definitionIdentifier?: LineRange; implementationIdentifier?: LineRange; }; const methodsByName = new Map(); const attributes: AttributeStructure[] = []; for (const match of inner.matchAll(elemRe)) { const attrs = match[1]; const elemInner = match[2]; const type = attrs.match(/adtcore:type="(CLAS\/[A-Z]+)"/)?.[1]; if (!type) continue; const name = attrs.match(/adtcore:name="([^"]*)"/)?.[1] ?? ''; if (!name) continue; const visibility = attrs.match(/visibility="([^"]+)"/)?.[1] as 'public' | 'protected' | 'private' | undefined; const level = attrs.match(/level="([^"]+)"/)?.[1] as 'instance' | 'static' | undefined; const isAbstract = /\babstract="true"/.test(attrs); const isConstructor = /\bconstructor="true"/.test(attrs); const isConstant = /\bconstant="true"/.test(attrs); const isReadOnly = /\breadOnly="true"/.test(attrs); const defBlock = elemInner.match(/rel="[^"]*\/definitionBlock"[^>]*href="([^"]+)"/)?.[1]; const implBlock = elemInner.match(/rel="[^"]*\/implementationBlock"[^>]*href="([^"]+)"/)?.[1]; const defIdent = elemInner.match(/rel="[^"]*\/definitionIdentifier"[^>]*href="([^"]+)"/)?.[1]; const implIdent = elemInner.match(/rel="[^"]*\/implementationIdentifier"[^>]*href="([^"]+)"/)?.[1]; // Methods: CLAS/OM (7.58+ unified or 7.50 impl-side), CLAS/OO (7.50 def-side). if (type === 'CLAS/OM' || type === 'CLAS/OO') { const upper = name.toUpperCase(); let entry = methodsByName.get(upper); if (!entry) { entry = { name: upper, abstract: false, constructor: false }; methodsByName.set(upper, entry); } // visibility/level/abstract/constructor: prefer the CLAS/OO (def-side) values // when both are present (the def side carries the canonical metadata). On // 7.58+ the single CLAS/OM element carries everything. if (visibility && (!entry.visibility || type === 'CLAS/OO')) entry.visibility = visibility; if (level && (!entry.level || type === 'CLAS/OO')) entry.level = level; if (/\bredefinition="true"/.test(attrs)) entry.redefinition = true; if (isAbstract) entry.abstract = true; if (isConstructor) entry.constructor = true; if (defBlock) { const r = parseLineRange(defBlock); if (r) entry.definition = r; } if (implBlock) { const r = parseLineRange(implBlock); if (r) entry.implementation = r; } if (defIdent) { const r = parseLineRange(defIdent); if (r) entry.definitionIdentifier = r; } if (implIdent) { const r = parseLineRange(implIdent); if (r) entry.implementationIdentifier = r; } continue; } // Attributes: CLAS/OA. if (type === 'CLAS/OA' && defBlock) { const def = parseLineRange(defBlock); if (!def) continue; attributes.push({ name: name.toUpperCase(), visibility: visibility ?? 'public', level: level ?? 'instance', constant: isConstant, readOnly: isReadOnly, definition: def, }); } // Other CLAS/O* types (CLAS/OE events, CLAS/OT types, CLAS/OF friends, // CLAS/OK constants/literals, CLAS/OCX text-elements) are intentionally // dropped — class-section surgery (issue #303) only targets methods. // Attribute-management is a future follow-up; events/types deeper still. } // Build the final methods array: skip entries that have no definition range // (defensive — every real method emitted by SAP carries at least a CLAS/OO // with definitionBlock, but parser robustness matters when the wire format // drifts). const methods: MethodStructure[] = []; for (const m of methodsByName.values()) { if (!m.definition) continue; methods.push({ name: m.name, ...(m.redefinition ? { redefinition: true } : {}), visibility: m.visibility ?? 'public', level: m.level ?? 'instance', abstract: m.abstract, constructor: m.constructor, definition: m.definition, ...(m.implementation ? { implementation: m.implementation } : {}), ...(m.definitionIdentifier ? { definitionIdentifier: m.definitionIdentifier } : {}), ...(m.implementationIdentifier ? { implementationIdentifier: m.implementationIdentifier } : {}), }); } return { className: resolvedClassName, classDefinitionBlock: classDef, ...(classImpl ? { classImplementationBlock: classImpl } : {}), methods, attributes, }; }