(function() { var MAX_FILE_BYTES = 256 * 1024; var OPERATIONS_PER_PAGE = 100; var APPLY_REPLAY_STORAGE_KEY = 'crank_openapi_plan_apply_replay_v2'; var restoredApplyRequest = loadApplyReplay(); var state = { workspaceId: null, onImported: null, onboarding: false, returnContext: null, onSelectDraft: null, importContext: null, importIdentity: null, file: null, jobId: null, preview: null, existingOperations: [], operationsReady: false, decisions: Object.create(null), plan: null, securityChoices: [], securityStatus: 'unresolved', securityByOperation: Object.create(null), filterQuery: '', filterMethod: '', selectedOperationKeys: new Set(), operationGroups: [], pageIndex: 0, partialMode: false, planPageIndex: 0, resultPageIndex: 0, planVersion: 0, planRevalidationGeneration: 0, planRevalidationState: 'current', revision: 0, previewController: null, planController: null, applyController: null, applyInFlight: false, applyRequest: restoredApplyRequest, applyMetadata: restoredApplyRequest && restoredApplyRequest.operationMetadata || [], applyResult: null, applyOutcomeUnknown: !!restoredApplyRequest, applyRefreshFailed: false, restoreFocus: null, }; function validApplyReplay(request) { return request && typeof request.workspaceId === 'string' && request.workspaceId.length > 0 && request.workspaceId.length <= 128 && typeof request.planReference === 'string' && request.planReference.length > 0 && request.planReference.length <= 128 && typeof request.planDigest === 'string' && /^[a-f0-9]{64}$/.test(request.planDigest) && typeof request.idempotencyKey === 'string' && request.idempotencyKey.length > 0 && request.idempotencyKey.length <= 128; } function loadApplyReplay() { try { var request = JSON.parse(sessionStorage.getItem(APPLY_REPLAY_STORAGE_KEY) || 'null'); return validApplyReplay(request) ? request : null; } catch (_error) { return null; } } function persistApplyReplay(request) { if (!validApplyReplay(request)) return; try { sessionStorage.setItem(APPLY_REPLAY_STORAGE_KEY, JSON.stringify(request)); } catch (_error) {} } function clearApplyReplay() { try { sessionStorage.removeItem(APPLY_REPLAY_STORAGE_KEY); } catch (_error) {} } function qs(id) { return document.getElementById(id); } function tKey(key) { return window.t ? window.t(key) : key; } function tfKey(key, vars) { return window.tf ? window.tf(key, vars) : tKey(key); } function locale() { return localStorage.getItem('crank_lang') === 'ru' ? 'ru' : 'en'; } function isSameContext(revision, workspaceId, language) { return revision === state.revision && workspaceId === state.workspaceId && language === locale(); } function isCurrent(revision, workspaceId, language) { return isSameContext(revision, workspaceId, language) && !qs('openapi-import-modal').hidden; } function setStatus(message, isError, focus) { var node = qs('openapi-import-status'); if (!node) return; node.textContent = message || ''; node.classList.toggle('error', !!isError); if (focus && message) { node.focus(); } } function boundedFileName(file) { var name = String(file && file.name || ''); return name.length > 128 ? name.slice(0, 127) + '…' : name; } function formatSize(bytes) { var language = locale() === 'ru' ? 'ru-RU' : 'en-US'; return new Intl.NumberFormat(language).format(bytes) + ' B'; } function renderFileName() { var node = qs('openapi-import-file-name'); if (!node) return; node.textContent = state.file ? boundedFileName(state.file) + ' · ' + formatSize(state.file.size) : tKey('openapi.file.none'); } function selectedKeys() { return importOperations() .map(function(operation) { return operation.key; }) .filter(function(key) { return state.selectedOperationKeys.has(key); }); } function importOperations() { return (state.preview && state.preview.groups || []).flatMap(function(group) { return group.operations || []; }); } function operationConflicts(operationKey) { return (state.preview && state.preview.conflicts || []).filter(function(conflict) { return conflict && conflict.operation_key === operationKey; }); } function sourcePointer(location) { return location && typeof location.pointer === 'string' ? location.pointer : ''; } function hasTypedError(findings) { return (findings || []).some(function(finding) { return String(finding && finding.severity || '').toLowerCase() === 'error'; }); } function operationIsBlocked(operation) { return String(operation && operation.status || '').toLowerCase() === 'blocked' || hasTypedError(operation && operation.findings) || hasTypedError((state.preview && state.preview.findings || []).filter(function(finding) { return operation && finding && finding.operation_key === operation.key; })); } function operationReadiness(operation) { var status = String(operation && operation.status || '').toLowerCase(); var labelKey = { actionable: 'openapi.operation.readiness_actionable', blocked: 'openapi.operation.readiness_blocked', unresolved: 'openapi.operation.readiness_unresolved', }[status]; if (!labelKey) return ''; return '' + escapeHtml(tKey(labelKey)) + ''; } function documentIsBlocked() { var preview = state.preview || {}; return String(preview.status || '').toLowerCase() === 'blocked' || hasTypedError((preview.findings || []).filter(function(finding) { return !finding || !finding.operation_key; })); } function decisionFor(operationKey) { if (!state.decisions[operationKey]) { var conflicts = operationConflicts(operationKey); state.decisions[operationKey] = { action: conflicts.length ? 'rename' : 'create', targetOperationId: '', confirmedName: conflicts.length ? String(conflicts[0].proposed_name || '') : '', securityAlternativeIndex: null, authProfileId: null, }; } return state.decisions[operationKey]; } function matchingOperations(operation) { return state.existingOperations.filter(function(existing) { return existing.name === operation.suggested_name; }); } function renderDecisionControls(operation, row) { var previous = row.querySelector('.openapi-import-decision-controls'); if (previous) previous.remove(); var controls = document.createElement('div'); var actionLabel = document.createElement('label'); var actionSelect = document.createElement('select'); var candidateDecision = decisionFor(operation.key); var matches = matchingOperations(operation); var versionable = matches.filter(function(existing) { return existing.protocol === 'rest' && existing.status !== 'archived'; }); var actions = [ ['create', 'openapi.decision.create'], ['skip', 'openapi.decision.skip'], ['rename', 'openapi.decision.rename'], ['new_version', 'openapi.decision.new_version'], ]; controls.className = 'openapi-import-decision-controls'; actionLabel.textContent = tKey('openapi.decision.action_label'); actionLabel.htmlFor = 'openapi-import-decision-' + operation.key; actionSelect.id = actionLabel.htmlFor; actionSelect.dataset.openapiDecisionAction = operation.key; actions.forEach(function(spec) { var option = document.createElement('option'); option.value = spec[0]; option.textContent = tKey(spec[1]); if ((spec[0] === 'skip' && !matches.length) || (spec[0] === 'new_version' && !versionable.length)) { option.disabled = true; } actionSelect.appendChild(option); }); actionSelect.value = candidateDecision.action; actionSelect.addEventListener('change', function() { candidateDecision.action = actionSelect.value; if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') { var allowed = candidateDecision.action === 'new_version' ? versionable : matches; if (!allowed.some(function(existing) { return existing.id === candidateDecision.targetOperationId; })) { candidateDecision.targetOperationId = allowed.length === 1 ? allowed[0].id : ''; } } renderDecisionControls(operation, row); renderSecurityControls(operation, row); updateSecuritySummary(); }); actionLabel.appendChild(actionSelect); controls.appendChild(actionLabel); if (candidateDecision.action === 'skip' || candidateDecision.action === 'new_version') { var targetLabel = document.createElement('label'); var targetSelect = document.createElement('select'); var allowedTargets = candidateDecision.action === 'new_version' ? versionable : matches; var placeholder = document.createElement('option'); targetLabel.textContent = tKey('openapi.decision.target_label'); targetSelect.dataset.openapiDecisionTarget = operation.key; placeholder.value = ''; placeholder.textContent = tKey('openapi.decision.target_placeholder'); targetSelect.appendChild(placeholder); allowedTargets.forEach(function(existing) { var option = document.createElement('option'); option.value = existing.id; option.textContent = existing.name + ' · ' + existing.id; targetSelect.appendChild(option); }); targetSelect.value = candidateDecision.targetOperationId; targetSelect.addEventListener('change', function() { candidateDecision.targetOperationId = targetSelect.value; }); targetLabel.appendChild(targetSelect); controls.appendChild(targetLabel); } if (candidateDecision.action === 'rename') { var renameLabel = document.createElement('label'); var renameInput = document.createElement('input'); renameLabel.textContent = tKey('openapi.decision.confirmed_name_label'); renameInput.type = 'text'; renameInput.maxLength = 128; renameInput.value = candidateDecision.confirmedName; renameInput.placeholder = tKey('openapi.decision.confirmed_name_placeholder'); renameInput.dataset.openapiDecisionName = operation.key; if (operationConflicts(operation.key).length) renameInput.dataset.testid = 'openapi-import-rename-proposal'; renameInput.addEventListener('input', function() { candidateDecision.confirmedName = renameInput.value; }); renameLabel.appendChild(renameInput); controls.appendChild(renameLabel); } row.appendChild(controls); } function operationRows() { return Array.from(document.querySelectorAll('.openapi-import-operation')); } function visibleOperationRows() { return operationRows().filter(function(row) { return !row.hidden; }); } function updateCreateAvailability() { var noOnboardingSelection = state.onboarding && state.operationsReady && selectedKeys().length === 0; var blockedFullImport = state.onboarding && !state.partialMode && blockedOperationCount() > 0; qs('openapi-import-create').disabled = state.planController !== null || state.applyInFlight || noOnboardingSelection || blockedFullImport; } function updateSelection() { var node = qs('openapi-import-selection'); var selectedCount = selectedKeys().length; var totalCount = importOperations().length; var visibleCount = visibleOperationRows().length; if (node) { node.textContent = tfKey('openapi.selection', { selected: selectedCount, total: totalCount, visible: visibleCount, }); } document.querySelectorAll('.openapi-import-group').forEach(function(groupNode) { var rows = Array.from(groupNode.querySelectorAll('.openapi-import-operation')); var visibleInputs = rows .filter(function(row) { return !row.hidden; }) .map(function(row) { return row.querySelector('[data-openapi-operation]'); }) .filter(Boolean); var selectedVisible = visibleInputs.filter(function(input) { return input.checked; }).length; var selectedTotal = rows.reduce(function(count, row) { var input = row.querySelector('[data-openapi-operation]'); return count + (input && state.selectedOperationKeys.has(input.value) ? 1 : 0); }, 0); var checkbox = groupNode.querySelector('[data-openapi-group]'); var counter = groupNode.querySelector('[data-openapi-group-count]'); if (checkbox) { checkbox.indeterminate = selectedVisible > 0 && selectedVisible < visibleInputs.length; checkbox.checked = visibleInputs.length > 0 && selectedVisible === visibleInputs.length; } if (counter) { counter.textContent = tfKey('openapi.group.selection', { selected: selectedTotal, total: rows.length, visible: visibleInputs.length, }); } }); updateSecuritySummary(); updateCreateAvailability(); } function applyFilters() { state.pageIndex = 0; renderOperationPage(); updateSelection(); } function setVisibleSelection(checked) { visibleOperationRows().forEach(function(row) { var input = row.querySelector('[data-openapi-operation]'); if (!input) return; if (checked && input.disabled) return; input.checked = checked; if (checked) state.selectedOperationKeys.add(input.value); else state.selectedOperationKeys.delete(input.value); }); renderOperationPage(); updateSelection(); } function filteredOperationGroups() { var query = state.filterQuery.toLowerCase(); var method = state.filterMethod.toLowerCase(); return state.operationGroups.map(function(group) { return { group: group, operations: group.operations.filter(function(operation) { var matchesMethod = !method || String(operation.method).toLowerCase() === method; var searchable = [group.title, operation.key, operation.suggested_name, operation.suggested_display_name, operation.path, operation.method].join(' ').toLowerCase(); return matchesMethod && (!query || searchable.indexOf(query) >= 0); }), }; }).filter(function(group) { return group.operations.length > 0; }); } function createOperationRow(operation, groupTitle) { var row = document.createElement('div'); var selectionLabel = document.createElement('label'); row.className = 'openapi-import-operation'; selectionLabel.className = 'openapi-import-operation-selection'; row.dataset.openapiMethod = operation.method; row.dataset.openapiSearch = [groupTitle, operation.key, operation.suggested_name, operation.suggested_display_name, operation.path, operation.method].join(' '); selectionLabel.innerHTML = '' + '
' + escapeHtml(operation.suggested_display_name) + '
' + '
' + escapeHtml(operation.suggested_name) + ' · ' + escapeHtml(operation.path) + ' · ' + escapeHtml(tfKey('openapi.operation.fields', { input: operation.input_fields, output: operation.output_fields })) + '
' + escapeHtml(operation.method) + '' + operationReadiness(operation); row.appendChild(selectionLabel); var operationLocation = sourcePointer(operation.source_location); if (operationLocation) { var locationNode = document.createElement('div'); locationNode.className = 'openapi-import-source-location'; locationNode.dataset.testid = 'openapi-import-operation-location'; locationNode.textContent = operationLocation; row.appendChild(locationNode); } operationConflicts(operation.key).forEach(function(conflict) { var conflictNode = document.createElement('div'); var conflictType = document.createElement('strong'); conflictNode.className = 'openapi-import-conflict'; conflictNode.dataset.testid = 'openapi-import-conflict'; conflictType.textContent = String(conflict.conflict_type || ''); conflictNode.appendChild(conflictType); if (conflict.proposed_name) { var proposal = document.createElement('span'); proposal.className = 'openapi-import-conflict-proposal'; proposal.textContent = String(conflict.proposed_name); conflictNode.appendChild(proposal); } var conflictLocation = sourcePointer(conflict.source_location); if (conflictLocation) { var source = document.createElement('code'); source.className = 'openapi-import-source-location'; source.dataset.testid = 'openapi-import-conflict-location'; source.textContent = conflictLocation; conflictNode.appendChild(source); } row.appendChild(conflictNode); }); row.appendChild(renderOperationMappingPreview(operation)); var findingsPanel = renderFindingsPanel(operation.findings); if (findingsPanel) row.appendChild(findingsPanel); renderDecisionControls(operation, row); renderSecurityControls(operation, row); selectionLabel.querySelector('[data-openapi-operation]').addEventListener('change', function(event) { if (event.target.checked) state.selectedOperationKeys.add(operation.key); else state.selectedOperationKeys.delete(operation.key); updateSelection(); }); return row; } function renderOperationPage() { var groupsNode = qs('openapi-import-groups'); if (!groupsNode) return; var filtered = filteredOperationGroups(); var total = filtered.reduce(function(sum, group) { return sum + group.operations.length; }, 0); var pageCount = Math.max(1, Math.ceil(total / OPERATIONS_PER_PAGE)); state.pageIndex = Math.min(Math.max(0, state.pageIndex), pageCount - 1); var start = state.pageIndex * OPERATIONS_PER_PAGE; var end = start + OPERATIONS_PER_PAGE; var cursor = 0; var pageGroups = []; filtered.forEach(function(entry) { var groupStart = cursor; cursor += entry.operations.length; var from = Math.max(start, groupStart); var to = Math.min(end, cursor); if (from < to) pageGroups.push({ entry: entry, operations: entry.operations.slice(from - groupStart, to - groupStart) }); }); groupsNode.replaceChildren(); var docFindings = state.preview && state.preview.findings || []; if (docFindings.length) { var documentFindings = document.createElement('div'); documentFindings.className = 'openapi-import-document-findings'; var findingsPanel = renderFindingsPanel(docFindings); if (findingsPanel) documentFindings.appendChild(findingsPanel); groupsNode.appendChild(documentFindings); } pageGroups.forEach(function(pageGroup) { var group = pageGroup.entry.group; var groupNode = document.createElement('section'); var header = document.createElement('div'); var selectedCount = pageGroup.operations.reduce(function(count, operation) { return count + (state.selectedOperationKeys.has(operation.key) ? 1 : 0); }, 0); groupNode.className = 'openapi-import-group'; groupNode.dataset.selectedCount = String(selectedCount); header.className = 'openapi-import-group-header'; header.innerHTML = '' + escapeHtml(group.title) + ' · ' + pageGroup.entry.operations.length + '' + '' + ''; groupNode.appendChild(header); pageGroup.operations.forEach(function(operation) { groupNode.appendChild(createOperationRow(operation, group.title)); }); groupNode.querySelector('[data-openapi-group]').addEventListener('change', function(event) { pageGroup.operations.forEach(function(operation) { if (event.target.checked && operationIsBlocked(operation)) return; if (event.target.checked) state.selectedOperationKeys.add(operation.key); else state.selectedOperationKeys.delete(operation.key); }); renderOperationPage(); updateSelection(); }); groupsNode.appendChild(groupNode); }); var pager = qs('openapi-import-pagination'); if (pager) { pager.hidden = total <= OPERATIONS_PER_PAGE; qs('openapi-import-page-status').textContent = tfKey('openapi.pagination.status', { page: state.pageIndex + 1, pages: pageCount, total: total, }); qs('openapi-import-page-previous').disabled = state.pageIndex === 0; qs('openapi-import-page-next').disabled = state.pageIndex + 1 >= pageCount; } renderBlockersSummary(groupsNode); resetSecurityStatuses(); } function escapeHtml(value) { return String(value || '') .replace(/&/g, '&') .replace(//g, '>') .replace(/"/g, '"'); } function blockerCodes() { var codes = []; var seen = Object.create(null); importOperations().forEach(function(operation) { if (!operationIsBlocked(operation)) return; (operation.findings || []).forEach(function(finding) { if (String(finding && finding.severity || '').toLowerCase() !== 'error') return; var code = String(finding && finding.code || ''); if (code && !seen[code]) { seen[code] = true; codes.push(code); } }); }); return codes; } function blockedOperationCount() { return importOperations().filter(operationIsBlocked).length; } function renderBlockersSummary(container) { if (!container) return; var count = blockedOperationCount(); var node = document.createElement('div'); node.className = 'openapi-import-blockers-summary'; node.dataset.testid = 'openapi-import-blockers'; node.hidden = count === 0; if (count > 0) { var label = document.createElement('span'); label.className = 'openapi-import-blockers-count'; label.textContent = tfKey('openapi.blockers.summary', { count: count }); node.appendChild(label); blockerCodes().forEach(function(code) { var chip = document.createElement('code'); chip.className = 'openapi-import-blocker-code'; chip.dataset.testid = 'openapi-import-finding-code'; chip.textContent = code; node.appendChild(chip); }); } container.appendChild(node); } function renderFinding(finding) { var severity = String(finding && finding.severity || 'warning').toLowerCase(); var label = severity === 'info' ? 'i' : severity === 'error' ? '×' : '!'; var code = String(finding && finding.code || ''); var pointer = sourcePointer(finding && finding.source_location); return '' + '' + label + ' ' + (code ? '' + escapeHtml(code) + ' ' : '') + escapeHtml(findingMessage(finding)) + (pointer ? ' ' + escapeHtml(pointer) + '' : '') + ''; } function renderSkippedPanel(items) { var page = 0; var details = document.createElement('details'); var summary = document.createElement('summary'); var content = document.createElement('div'); var pageSize = OPERATIONS_PER_PAGE; details.className = 'openapi-import-result-skipped'; summary.textContent = tfKey('openapi.result.skipped_count', { count: items.length }); content.className = 'openapi-import-result-skipped-page'; function renderPage() { var list = document.createElement('ul'); items.slice(page * pageSize, (page + 1) * pageSize).forEach(function(item) { var entry = document.createElement('li'); entry.textContent = (item.name || item.operation_key || tKey('openapi.result.unnamed')) + ' — ' + findingMessage({ code: item.code || item.reason_code || item.reason }); list.appendChild(entry); }); content.replaceChildren(list); if (items.length > pageSize) { content.appendChild(createPageNavigation(page, items.length, 'openapi.pagination.result_label', function(nextPage) { page = nextPage; renderPage(); })); } } details.addEventListener('toggle', function() { if (details.open && !content.childElementCount) renderPage(); }); details.append(summary, content); return details; } function renderFindingsPanel(findings) { if (!findings || !findings.length) return null; var pageSize = 5; var page = 0; var details = document.createElement('details'); var summary = document.createElement('summary'); var content = document.createElement('div'); var pagination = document.createElement('div'); var previous = document.createElement('button'); var status = document.createElement('span'); var next = document.createElement('button'); details.className = 'openapi-import-findings'; summary.textContent = tfKey('openapi.findings.summary', { count: findings.length }); content.className = 'openapi-import-findings-page'; pagination.className = 'openapi-import-findings-pagination'; pagination.hidden = findings.length <= pageSize; previous.type = 'button'; previous.className = 'btn-secondary'; previous.textContent = tKey('openapi.pagination.previous'); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite'); status.setAttribute('aria-atomic', 'true'); next.type = 'button'; next.className = 'btn-secondary'; next.textContent = tKey('openapi.pagination.next'); function renderPage() { var pages = Math.max(1, Math.ceil(findings.length / pageSize)); content.innerHTML = findings.slice(page * pageSize, (page + 1) * pageSize).map(renderFinding).join(''); status.textContent = tfKey('openapi.pagination.status', { page: page + 1, pages: pages, total: findings.length }); previous.disabled = page === 0; next.disabled = page + 1 >= pages; } previous.addEventListener('click', function() { page = Math.max(0, page - 1); renderPage(); }); next.addEventListener('click', function() { page = Math.min(Math.ceil(findings.length / pageSize) - 1, page + 1); renderPage(); }); details.addEventListener('toggle', function() { if (details.open && !content.childElementCount) renderPage(); }); pagination.append(previous, status, next); details.append(summary, content, pagination); return details; } function createPageNavigation(page, total, labelKey, onPage) { var pageCount = Math.max(1, Math.ceil(total / OPERATIONS_PER_PAGE)); var navigation = document.createElement('nav'); var previous = document.createElement('button'); var status = document.createElement('span'); var next = document.createElement('button'); navigation.className = 'openapi-import-pagination'; navigation.setAttribute('aria-label', tKey(labelKey)); navigation.setAttribute('role', 'navigation'); previous.type = 'button'; previous.className = 'btn-secondary'; previous.textContent = tKey('openapi.pagination.previous'); status.setAttribute('role', 'status'); status.setAttribute('aria-live', 'polite'); status.setAttribute('aria-atomic', 'true'); status.textContent = tfKey('openapi.pagination.status', { page: page + 1, pages: pageCount, total: total, }); next.type = 'button'; next.className = 'btn-secondary'; next.textContent = tKey('openapi.pagination.next'); previous.disabled = page === 0; next.disabled = page + 1 >= pageCount; previous.addEventListener('click', function() { onPage(Math.max(0, page - 1)); }); next.addEventListener('click', function() { onPage(Math.min(pageCount - 1, page + 1)); }); navigation.append(previous, status, next); return navigation; } function findingMessage(finding) { var code = String(finding && finding.code || '').replace(/^.*\./, ''); var known = { missing_servers: 'openapi.finding.missing_servers', multiple_servers: 'openapi.finding.multiple_servers', unsupported_request_body: 'openapi.finding.unsupported_request_body', unsupported_security_scheme: 'openapi.finding.unsupported_security_scheme', external_reference_disabled: 'openapi.finding.external_reference_disabled', unsupported_security_and_requirement: 'openapi.finding.unsupported_security_and_requirement', auth_profile_required: 'openapi.error.auth_profile_required', operation_name_renamed: 'openapi.finding.operation_name_renamed', operation_name_conflict: 'openapi.finding.operation_name_conflict', weak_tool_description: 'openapi.finding.weak_tool_description', }; return tKey(known[code] || 'openapi.finding.generic'); } function outcomeMessage(outcome) { var key = 'openapi.plan.outcome.' + String(outcome || ''); return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key); } function appendMappingGroup(root, label, values) { if (!values || !values.length) return; var group = document.createElement('div'); group.className = 'openapi-import-mapping-group'; var title = document.createElement('span'); title.className = 'openapi-import-mapping-label'; title.textContent = label; group.appendChild(title); values.slice(0, 8).forEach(function(value) { var chip = document.createElement('code'); chip.className = 'openapi-import-mapping-chip'; chip.textContent = value; group.appendChild(chip); }); if (values.length > 8) { var more = document.createElement('span'); more.className = 'openapi-import-mapping-more'; more.textContent = '+' + (values.length - 8); group.appendChild(more); } root.appendChild(group); } function renderOperationMappingPreview(operation) { var details = document.createElement('div'); var request = { path: [], query: [], headers: [], body: [] }; var inputRules = operation && operation.draft && operation.draft.input_mapping && Array.isArray(operation.draft.input_mapping.rules) ? operation.draft.input_mapping.rules : []; var outputRules = operation && operation.draft && operation.draft.output_mapping && Array.isArray(operation.draft.output_mapping.rules) ? operation.draft.output_mapping.rules : []; details.className = 'openapi-import-mapping-preview'; inputRules.forEach(function(rule) { var target = String(rule.target || ''); if (target.indexOf('$.request.path.') === 0) { request.path.push(target.slice(15)); } else if (target.indexOf('$.request.query.') === 0) { request.query.push(target.slice(16)); } else if (target.indexOf('$.request.headers.') === 0) { request.headers.push(target.slice(18)); } else if (target.indexOf('$.request.body.') === 0) { request.body.push(target.slice(15)); } else if (target === '$.request.body') { request.body.push('body'); } }); appendMappingGroup(details, tKey('openapi.mapping.path'), request.path); appendMappingGroup(details, tKey('openapi.mapping.query'), request.query); appendMappingGroup(details, tKey('openapi.mapping.header'), request.headers); appendMappingGroup(details, tKey('openapi.mapping.body'), request.body); appendMappingGroup(details, tKey('openapi.mapping.response'), outputRules.map(function(rule) { var target = String(rule.target || '').replace('$.output.', '').replace('$.output', 'result'); var source = String(rule.source || '').replace('$.response.body.', '').replace('$.response.body', 'body'); return target + ' ← ' + source; })); return details; } function populateServers(preview) { var serverSelect = qs('openapi-import-server'); var servers = preview.source && preview.source.servers && preview.source.servers.length ? preview.source.servers : ['']; serverSelect.replaceChildren(); servers.forEach(function(server) { var option = document.createElement('option'); option.value = server; option.textContent = server || tKey('openapi.server.required'); serverSelect.appendChild(option); }); } function populateMethodFilter(preview) { var methodFilter = qs('openapi-import-method-filter'); var all = document.createElement('option'); var methods = Array.from(new Set((preview.groups || []).flatMap(function(group) { return (group.operations || []).map(function(operation) { return operation.method; }); }))).sort(); methodFilter.replaceChildren(); all.value = ''; all.textContent = tKey('openapi.method.all'); methodFilter.appendChild(all); methods.forEach(function(method) { var option = document.createElement('option'); option.value = method; option.textContent = method; methodFilter.appendChild(option); }); } var SECURITY_STATUS_KEYS = { no_auth: 'openapi.security.status_no_auth', required: 'openapi.security.status_required', unresolved: 'openapi.security.status_unresolved', unverified: 'openapi.security.status_unverified', resolved: 'openapi.security.status_resolved', blocked: 'openapi.security.status_blocked', }; var SECURITY_PLAN_ERROR_CODES = [ 'import_plan_auth_unavailable', 'import_plan_auth_incompatible', 'import_plan_security_alternative_required', ]; function securityStatusLabel(status) { return tKey(SECURITY_STATUS_KEYS[status] || SECURITY_STATUS_KEYS.unresolved); } function renderSecurityStatus() { var node = qs('openapi-import-security-status'); if (!node) return; node.textContent = securityStatusLabel(state.securityStatus); } function setSecurityStatus(status) { state.securityStatus = status; renderSecurityStatus(); } function securityOperationNode(operationKey) { // Compare dataset values against a constant selector: imported operation // keys are untrusted and must never be interpolated into a CSS selector. var nodes = document.querySelectorAll('[data-openapi-security-op-status]'); for (var i = 0; i < nodes.length; i += 1) { if (nodes[i].dataset.openapiSecurityOpStatus === operationKey) return nodes[i]; } return null; } function renderOperationSecurityStatus(operationKey) { var node = securityOperationNode(operationKey); if (!node) return; var status = state.securityByOperation[operationKey] || 'unresolved'; node.dataset.status = status; node.textContent = securityStatusLabel(status); } function setOperationSecurityStatus(operationKey, status) { state.securityByOperation[operationKey] = status; renderOperationSecurityStatus(operationKey); } // Summary only: the per-operation nodes carry the authority, this aggregate // id reports whether any selected operation still needs attention. function updateSecuritySummary() { var selected = new Set(selectedKeys()); var statuses = []; importOperations().forEach(function(operation) { if (!selected.has(operation.key)) return; statuses.push(state.securityByOperation[operation.key] || baselineSecurityStatus(operation)); }); var summary = 'unresolved'; if (statuses.indexOf('blocked') >= 0) summary = 'blocked'; else if (statuses.indexOf('required') >= 0) summary = 'required'; else if (statuses.indexOf('unverified') >= 0) summary = 'unverified'; else if (statuses.indexOf('resolved') >= 0) summary = 'resolved'; else if (statuses.length && statuses.every(function(status) { return status === 'no_auth'; })) summary = 'no_auth'; setSecurityStatus(summary); } function securityAlternativesFor(operation) { var requirements = operation && operation.security_requirements; return requirements && Array.isArray(requirements.alternatives) ? requirements.alternatives : []; } function alternativeFor(operation, index) { if (index === null || index === undefined) return null; return securityAlternativesFor(operation)[Number(index)] || null; } function isAnonymousAlternative(alternative) { if (!alternative || alternative.supported === false) return false; var schemes = Array.isArray(alternative.schemes) ? alternative.schemes : []; return schemes.length === 0; } function operationRequiresAuth(operation) { return securityAlternativesFor(operation).some(function(alternative) { return alternative && alternative.supported !== false && Array.isArray(alternative.schemes) && alternative.schemes.length > 0; }); } function securityProfilesFor(operation, alternativeIndex) { var profiles = []; (state.securityChoices || []).forEach(function(choice) { if (!choice || choice.operation_key !== operation.key) return; // Filter to the exact selected alternative. While no alternative is // chosen the safe union supports profile-first selection and lets the // API own compatibility validation. if (alternativeIndex !== null && alternativeIndex !== undefined && Number(choice.alternative_index) !== Number(alternativeIndex)) return; if (Array.isArray(choice.profiles)) profiles = profiles.concat(choice.profiles); }); // Keep a stable order across alternatives: first occurrence wins. var seen = {}; return profiles.filter(function(profile) { if (!profile || typeof profile.id !== 'string' || !profile.id || seen[profile.id]) return false; seen[profile.id] = true; return true; }); } // Local expectation only; resolved/blocked never originate here. function baselineSecurityStatus(operation) { var alternatives = securityAlternativesFor(operation); if (!alternatives.length) return 'no_auth'; var decision = decisionFor(operation.key); if (decision.action === 'skip') return 'unresolved'; if (!alternatives.some(function(alternative) { return alternative && alternative.supported !== false; })) { return 'blocked'; } if (!operationRequiresAuth(operation)) return 'no_auth'; var alternative = alternativeFor(operation, decision.securityAlternativeIndex); if (isAnonymousAlternative(alternative)) return 'unresolved'; if (decision.authProfileId) return 'unresolved'; return 'required'; } function resetSecurityStatuses() { importOperations().forEach(function(operation) { state.securityByOperation[operation.key] = baselineSecurityStatus(operation); }); document.querySelectorAll('[data-openapi-security-op-status]').forEach(function(node) { var key = node.dataset.openapiSecurityOpStatus; var status = state.securityByOperation[key] || 'unresolved'; node.dataset.status = status; node.textContent = securityStatusLabel(status); }); updateSecuritySummary(); } function operationRowFor(operation) { return Array.from(document.querySelectorAll('.openapi-import-operation')).find(function(row) { var input = row.querySelector('[data-openapi-operation]'); return input && input.value === operation.key; }) || null; } function invalidatePendingPlan() { // Even without a stored plan a prior blocked state must be cleared: the // edited selection is unverified until the next plan response arrives. if (state.plan) { state.planRevalidationGeneration += 1; state.plan = null; state.planRevalidationState = 'current'; qs('openapi-import-plan-confirmation').hidden = true; qs('openapi-import-plan-counts').replaceChildren(); qs('openapi-import-plan-candidates').replaceChildren(); qs('openapi-import-versioning-consequences').hidden = true; qs('openapi-import-plan-blocked-help').hidden = true; qs('openapi-import-plan-stale').hidden = true; qs('openapi-import-plan-revalidation-status').textContent = ''; } resetSecurityStatuses(); } function renderSecurityControls(operation, row) { var previous = row.querySelector('.openapi-import-security'); if (previous) previous.remove(); var decision = decisionFor(operation.key); var alternatives = securityAlternativesFor(operation); if (decision.action === 'skip') { // A skipped operation keeps the existing operation untouched: no // security binding may be attached, so clear it instead of trapping the // user in a local validation error. decision.authProfileId = null; decision.securityAlternativeIndex = null; setOperationSecurityStatus(operation.key, 'unresolved'); return; } var wrapper = document.createElement('div'); wrapper.className = 'openapi-import-security'; var statusNode = document.createElement('span'); statusNode.className = 'openapi-import-security-op-status'; statusNode.setAttribute('data-openapi-security-op-status', operation.key); statusNode.setAttribute('data-testid', 'openapi-security-op-status'); // Announce per-operation changes even when the aggregate text is unchanged. statusNode.setAttribute('role', 'status'); statusNode.setAttribute('aria-live', 'polite'); wrapper.appendChild(statusNode); if (alternatives.length) { var controls = document.createElement('div'); controls.className = 'openapi-import-security-controls'; // Only the alternative index and the typed profile id are stored locally. // The API remains the authority for OR/AND semantics and compatibility. var alternativeLabel = document.createElement('label'); var alternativeSelect = document.createElement('select'); alternativeLabel.textContent = tKey('openapi.security.alternative_label'); alternativeSelect.dataset.openapiSecurityAlternative = operation.key; var alternativePlaceholder = document.createElement('option'); alternativePlaceholder.value = ''; alternativePlaceholder.textContent = tKey('openapi.security.alternative_placeholder'); alternativeSelect.appendChild(alternativePlaceholder); var findingsNode = null; alternatives.forEach(function(alternative, index) { var option = document.createElement('option'); var schemes = alternative && Array.isArray(alternative.schemes) ? alternative.schemes : []; option.value = String(index); option.textContent = schemes.length ? schemes.join(' + ') : tKey('openapi.security.no_auth'); if (alternative && alternative.supported === false) { option.disabled = true; option.textContent += ' · ' + tKey('openapi.security.unsupported'); var finding = Array.isArray(alternative.findings) && alternative.findings[0]; // Surface the blocker as a safe, localized message next to the control. if (finding) { if (!findingsNode) { findingsNode = document.createElement('span'); findingsNode.className = 'openapi-import-security-findings'; } var findingSpan = document.createElement('span'); findingSpan.className = 'openapi-import-finding openapi-import-finding-warning'; findingSpan.textContent = findingMessage({ code: finding }); findingsNode.appendChild(findingSpan); } } alternativeSelect.appendChild(option); }); alternativeSelect.value = decision.securityAlternativeIndex === null ? '' : String(decision.securityAlternativeIndex); alternativeSelect.addEventListener('change', function() { // Switching the alternative invalidates the previous profile binding and // any server-confirmed plan: the API revalidates the current selection. decision.securityAlternativeIndex = alternativeSelect.value === '' ? null : Number(alternativeSelect.value); decision.authProfileId = null; invalidatePendingPlan(); renderSecurityControls(operation, row); }); alternativeLabel.appendChild(alternativeSelect); controls.appendChild(alternativeLabel); if (findingsNode) controls.appendChild(findingsNode); var selectedAlternative = alternativeFor(operation, decision.securityAlternativeIndex); var anonymous = isAnonymousAlternative(selectedAlternative); var profiles = securityProfilesFor(operation, decision.securityAlternativeIndex); // An anonymous alternative must offer no profile at all. if (!anonymous) { var profileLabel = document.createElement('label'); var profileSelect = document.createElement('select'); profileLabel.textContent = tKey('openapi.security.profile_label'); profileSelect.dataset.openapiSecurityProfile = operation.key; var profilePlaceholder = document.createElement('option'); profilePlaceholder.value = ''; profilePlaceholder.textContent = tKey('openapi.security.profile_placeholder'); profileSelect.appendChild(profilePlaceholder); profiles.forEach(function(profile) { // Safe metadata only: id, name, kind. Never credential material. var option = document.createElement('option'); option.value = profile.id; option.textContent = String(profile.name || profile.id); if (profile.kind) option.textContent += ' · ' + profile.kind; profileSelect.appendChild(option); }); var emptyProfiles = decision.securityAlternativeIndex !== null && selectedAlternative && selectedAlternative.supported !== false && !anonymous && profiles.length === 0; if (emptyProfiles) { profileSelect.disabled = true; var guidance = document.createElement('span'); guidance.className = 'openapi-import-security-guidance'; guidance.textContent = tKey('openapi.security.empty_profiles'); profileLabel.appendChild(guidance); } profileSelect.value = decision.authProfileId || ''; profileSelect.addEventListener('change', function() { decision.authProfileId = profileSelect.value || null; invalidatePendingPlan(); }); profileLabel.appendChild(profileSelect); controls.appendChild(profileLabel); } wrapper.appendChild(controls); } row.appendChild(wrapper); setOperationSecurityStatus(operation.key, baselineSecurityStatus(operation)); } function renderPreview(response) { var preview = response.preview; var count = (preview.groups || []).reduce(function(sum, group) { return sum + (group.operations || []).length; }, 0); var source = qs('openapi-import-source'); state.jobId = response.job_id; state.preview = preview; state.existingOperations = []; state.operationsReady = false; state.decisions = Object.create(null); state.securityChoices = Array.isArray(response.security_profile_choices) ? response.security_profile_choices : []; state.securityByOperation = Object.create(null); state.operationGroups = preview.groups || []; state.selectedOperationKeys = new Set(importOperations().map(function(operation) { return operation.key; })); state.pageIndex = 0; state.partialMode = false; qs('openapi-import-partial-mode').checked = false; importOperations().forEach(function(operation) { decisionFor(operation.key); }); state.filterQuery = ''; state.filterMethod = ''; qs('openapi-import-preview-panel').hidden = false; qs('openapi-import-result').hidden = true; qs('openapi-import-result').replaceChildren(); source.textContent = tfKey('openapi.source.summary', { name: boundedFileName(state.file), size: formatSize(state.file.size), count: count, }); qs('openapi-import-search').value = ''; populateServers(preview); populateMethodFilter(preview); renderOperationPage(); updateSelection(); } function validateFile(file) { if (!file) return 'openapi.error.file_required'; var name = String(file.name || '').toLowerCase(); var yaml = /\.(yaml|yml)$/.test(name); var json = /\.json$/.test(name); if (!yaml && !json) return 'openapi.error.file_type'; if (!file.size) return 'openapi.error.file_empty'; if (file.size > MAX_FILE_BYTES) return 'openapi.error.file_large'; var type = String(file.type || '').toLowerCase(); if (!type || type === 'application/octet-stream') return null; var allowed = yaml ? ['application/yaml', 'application/x-yaml', 'text/yaml', 'text/x-yaml'] : ['application/json', 'application/openapi+json']; return allowed.indexOf(type) >= 0 ? null : 'openapi.error.file_type'; } function abort(controller) { if (controller) controller.abort(); } function clearPreview() { state.planRevalidationGeneration += 1; state.planVersion = 0; state.planRevalidationState = 'current'; state.jobId = null; state.preview = null; state.existingOperations = []; state.operationsReady = false; state.decisions = Object.create(null); state.securityChoices = []; state.securityStatus = 'unresolved'; state.securityByOperation = Object.create(null); state.operationGroups = []; state.selectedOperationKeys = new Set(); state.pageIndex = 0; state.partialMode = false; qs('openapi-import-partial-mode').checked = false; state.plan = null; state.applyRequest = null; state.applyMetadata = []; state.applyResult = null; state.applyOutcomeUnknown = false; state.applyRefreshFailed = false; state.filterQuery = ''; state.filterMethod = ''; qs('openapi-import-preview-panel').hidden = true; qs('openapi-import-plan-confirmation').hidden = true; qs('openapi-import-plan-counts').replaceChildren(); qs('openapi-import-plan-candidates').replaceChildren(); qs('openapi-import-plan-pagination').hidden = true; qs('openapi-import-versioning-consequences').hidden = true; qs('openapi-import-plan-blocked-help').hidden = true; qs('openapi-import-plan-stale').hidden = true; qs('openapi-import-plan-revalidation-status').textContent = ''; qs('openapi-import-groups').replaceChildren(); qs('openapi-import-pagination').hidden = true; qs('openapi-import-page-previous').disabled = true; qs('openapi-import-page-next').disabled = true; qs('openapi-import-select-visible').disabled = true; qs('openapi-import-clear-visible').disabled = true; renderSecurityStatus(); qs('openapi-import-result').hidden = true; qs('openapi-import-result').replaceChildren(); updateSelection(); } function clearServerSelection() { qs('openapi-import-server-custom').value = ''; qs('openapi-import-server').replaceChildren(); } function invalidate(options) { state.revision += 1; abort(state.previewController); abort(state.planController); abort(state.applyController); state.previewController = null; state.planController = null; state.applyController = null; state.applyInFlight = false; qs('openapi-import-preview').disabled = false; qs('openapi-import-create').disabled = false; qs('openapi-import-plan-apply').disabled = false; qs('openapi-import-plan-back').disabled = false; qs('openapi-import-file-select').disabled = false; qs('openapi-import-reset').disabled = false; qs('openapi-import-cancel').hidden = true; clearPreview(); if (options && options.clearFile) { state.file = null; qs('openapi-import-file').value = ''; renderFileName(); } } function showRetry(show) { qs('openapi-import-retry').hidden = !show; } function lockApplyInputs(locked) { qs('openapi-import-create').disabled = locked; qs('openapi-import-preview').disabled = locked; qs('openapi-import-file-select').disabled = locked; qs('openapi-import-reset').disabled = locked; qs('openapi-import-plan-apply').disabled = locked; qs('openapi-import-plan-back').disabled = locked; qs('openapi-import-server').disabled = locked; qs('openapi-import-server-custom').disabled = locked; qs('openapi-import-search').disabled = locked; qs('openapi-import-method-filter').disabled = locked; qs('openapi-import-select-visible').disabled = locked || !state.partialMode; qs('openapi-import-clear-visible').disabled = locked || !state.partialMode; qs('openapi-import-partial-mode').disabled = locked || documentIsBlocked(); qs('openapi-import-page-previous').disabled = locked || state.pageIndex === 0; qs('openapi-import-page-next').disabled = locked || state.pageIndex + 1 >= Math.ceil(filteredOperationGroups().reduce(function(sum, group) { return sum + group.operations.length; }, 0) / OPERATIONS_PER_PAGE); document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) { var row = input.closest('.openapi-import-operation'); var operation = row && importOperations().find(function(candidate) { return candidate.key === input.value; }); input.disabled = locked || !state.partialMode || documentIsBlocked() || (input.matches('[data-openapi-operation]') && operationIsBlocked(operation)); }); document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) { input.disabled = locked; }); document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) { input.disabled = locked; }); } function lockPlanEditing(locked) { qs('openapi-import-create').disabled = locked; qs('openapi-import-preview').disabled = locked; qs('openapi-import-file-select').disabled = locked; qs('openapi-import-reset').disabled = locked; qs('openapi-import-server').disabled = locked; qs('openapi-import-server-custom').disabled = locked; qs('openapi-import-search').disabled = locked; qs('openapi-import-method-filter').disabled = locked; qs('openapi-import-select-visible').disabled = locked || !state.partialMode; qs('openapi-import-clear-visible').disabled = locked || !state.partialMode; qs('openapi-import-partial-mode').disabled = locked || documentIsBlocked(); qs('openapi-import-page-previous').disabled = locked || state.pageIndex === 0; qs('openapi-import-page-next').disabled = locked || state.pageIndex + 1 >= Math.ceil(filteredOperationGroups().reduce(function(sum, group) { return sum + group.operations.length; }, 0) / OPERATIONS_PER_PAGE); document.querySelectorAll('[data-openapi-operation], [data-openapi-group]').forEach(function(input) { var row = input.closest('.openapi-import-operation'); var operation = row && importOperations().find(function(candidate) { return candidate.key === input.value; }); input.disabled = locked || !state.partialMode || documentIsBlocked() || (input.matches('[data-openapi-operation]') && operationIsBlocked(operation)); }); document.querySelectorAll('.openapi-import-decision-controls select, .openapi-import-decision-controls input').forEach(function(input) { input.disabled = locked; }); document.querySelectorAll('.openapi-import-security-controls select, .openapi-import-security-controls input').forEach(function(input) { input.disabled = locked; }); } function markApplyOutcomeUnknown(options) { if (!state.applyRequest) return false; abort(state.applyController); state.applyController = null; state.applyInFlight = false; state.applyOutcomeUnknown = true; persistApplyReplay(state.applyRequest); // Until the same plan is replayed, starting another import could hide an // already committed server outcome and lead to duplicate drafts. lockApplyInputs(true); qs('openapi-import-cancel').hidden = true; if (!options || options.render !== false) { showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); } return true; } function cancelCurrent() { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown(); return; } if (state.planController) { abort(state.planController); state.planController = null; state.revision += 1; lockPlanEditing(false); qs('openapi-import-cancel').hidden = true; showRetry(false); setStatus(tKey('openapi.status.cancelled')); return; } if (!state.previewController) return; invalidate(); showRetry(!!state.file); setStatus(tKey('openapi.status.cancelled')); } function errorStatus(error, fallback) { var known = { 'openapi_upload.missing_file': 'openapi.error.file_required', 'openapi_upload.invalid_media_type': 'openapi.error.file_type', 'openapi_upload.empty_file': 'openapi.error.file_empty', 'openapi_upload.file_too_large': 'openapi.error.file_large', 'openapi_upload.no_methods': 'openapi.error.no_methods', 'openapi_upload.malformed_multipart': 'openapi.error.malformed_multipart', 'openapi_upload.invalid_utf8': 'openapi.error.invalid_utf8', 'openapi_upload.invalid_document': 'openapi.error.invalid_document', 'openapi_upload.parser_unavailable': 'openapi.error.parser_unavailable', 'openapi_upload.storage_unavailable': 'openapi.error.storage_unavailable', 'openapi_upload.source_integrity': 'openapi.error.source_integrity', 'openapi_upload.source_unavailable': 'openapi.error.source_unavailable', 'import_plan_auth_unavailable': 'openapi.error.auth_unavailable', 'import_plan_auth_incompatible': 'openapi.error.auth_incompatible', 'import_plan_security_alternative_required': 'openapi.error.security_alternative_required', }; var message = tKey(known[error && error.code] || fallback); var identifiers = []; if (error && error.requestId) { identifiers.push(tfKey('openapi.correlation.request_id', { id: error.requestId })); } if (error && error.traceId) { identifiers.push(tfKey('openapi.correlation.trace_id', { id: error.traceId })); } return identifiers.length ? message + ' ' + identifiers.join(' · ') : message; } async function preview() { var localError = validateFile(state.file); if (localError) { setStatus(tKey(localError), true, true); showRetry(false); return; } if (!state.workspaceId) { setStatus(tKey('openapi.error.workspace'), true, true); return; } invalidate(); var revision = state.revision; var workspaceId = state.workspaceId; var language = locale(); var controller = new AbortController(); state.previewController = controller; qs('openapi-import-preview').disabled = true; qs('openapi-import-cancel').hidden = false; showRetry(false); setStatus(tKey('openapi.status.uploading')); try { var response = await window.CrankApi.previewOpenApiImport(workspaceId, state.file, { signal: controller.signal }); if (!isCurrent(revision, workspaceId, language)) return; setStatus(tKey('openapi.status.parsing')); await new Promise(function(resolve) { window.requestAnimationFrame(resolve); }); if (!isCurrent(revision, workspaceId, language)) return; renderPreview(response); qs('openapi-import-create').disabled = true; setStatus(tKey('openapi.status.loading_operations')); var operationResponse = await window.CrankApi.listOperations(workspaceId); if (!isCurrent(revision, workspaceId, language)) return; if (!operationResponse || !Array.isArray(operationResponse.items)) { throw new Error('Backend returned an invalid operations list response'); } state.existingOperations = operationResponse.items; state.operationsReady = true; importOperations().forEach(function(operation) { var row = operationRowFor(operation); if (row) { renderDecisionControls(operation, row); renderSecurityControls(operation, row); } }); updateCreateAvailability(); setStatus(tKey('openapi.status.preview_ready')); } catch (error) { if (!isCurrent(revision, workspaceId, language)) return; if (error && error.name === 'AbortError') { setStatus(tKey('openapi.status.cancelled')); return; } clearPreview(); showRetry(true); setStatus(errorStatus(error, 'openapi.error.preview'), true, true); } finally { if (isCurrent(revision, workspaceId, language)) { state.previewController = null; qs('openapi-import-preview').disabled = false; qs('openapi-import-cancel').hidden = true; } } } function previewOperationForCreated(created) { var groups = state.preview && state.preview.groups || []; for (var groupIndex = 0; groupIndex < groups.length; groupIndex += 1) { var operations = groups[groupIndex].operations || []; for (var operationIndex = 0; operationIndex < operations.length; operationIndex += 1) { if (created.operation_key && operations[operationIndex].key === created.operation_key) { return operations[operationIndex]; } } } // Older servers did not return operation_key. Keep result rendering useful // during a rolling upgrade, but use the unambiguous key whenever it exists. for (var fallbackGroupIndex = 0; fallbackGroupIndex < groups.length; fallbackGroupIndex += 1) { var fallbackOperations = groups[fallbackGroupIndex].operations || []; for (var fallbackOperationIndex = 0; fallbackOperationIndex < fallbackOperations.length; fallbackOperationIndex += 1) { if (fallbackOperations[fallbackOperationIndex].suggested_name === created.name) { return fallbackOperations[fallbackOperationIndex]; } } } for (var metadataIndex = 0; metadataIndex < state.applyMetadata.length; metadataIndex += 1) { if (created.operation_key && state.applyMetadata[metadataIndex].key === created.operation_key) { return state.applyMetadata[metadataIndex]; } } return null; } function wizardHref(operationId) { return ((window.CrankRoutes && window.CrankRoutes.wizard) || '/wizard/') + '?mode=edit&operationId=' + encodeURIComponent(operationId); } function appendFindingNodes(root, findings) { if (!findings || !findings.length) { var empty = document.createElement('span'); empty.className = 'openapi-import-result-ok'; empty.textContent = tKey('openapi.result.no_findings'); root.appendChild(empty); return; } root.appendChild(renderFindingsPanel(findings)); } function renderResult(response) { var node = qs('openapi-import-result'); var title = document.createElement('strong'); node.replaceChildren(); title.textContent = tKey('openapi.result.title'); node.appendChild(title); if (response.created && response.created.length) { var primary = document.createElement('div'); var table = document.createElement('div'); primary.className = 'openapi-import-primary-result'; primary.innerHTML = '' + escapeHtml(tKey('openapi.result.open_first')) + ''; node.appendChild(primary); table.className = 'openapi-import-result-table'; table.setAttribute('role', 'table'); table.innerHTML = '
' + '
' + escapeHtml(tKey('openapi.result.draft')) + '
' + '
' + escapeHtml(tKey('openapi.result.findings')) + '
' + '
' + escapeHtml(tKey('openapi.result.action')) + '
' + '
'; var created = Array.isArray(response.created) ? response.created : []; var resultPageCount = Math.max(1, Math.ceil(created.length / OPERATIONS_PER_PAGE)); state.resultPageIndex = Math.min(Math.max(0, state.resultPageIndex), resultPageCount - 1); created.slice(state.resultPageIndex * OPERATIONS_PER_PAGE, (state.resultPageIndex + 1) * OPERATIONS_PER_PAGE).forEach(function(operation) { var previewOperation = previewOperationForCreated(operation); var row = document.createElement('div'); var nameCell = document.createElement('div'); var name = document.createElement('div'); var meta = document.createElement('div'); var findingsCell = document.createElement('div'); var actionCell = document.createElement('div'); var action = document.createElement('a'); row.className = 'openapi-import-result-row'; row.setAttribute('role', 'row'); nameCell.setAttribute('role', 'cell'); name.className = 'openapi-import-result-name'; name.textContent = operation.name; meta.className = 'openapi-import-result-meta'; meta.textContent = previewOperation ? previewOperation.method + ' ' + previewOperation.path + ' · v' + operation.version : 'v' + operation.version; nameCell.append(name, meta); findingsCell.className = 'openapi-import-result-findings'; findingsCell.setAttribute('role', 'cell'); appendFindingNodes(findingsCell, previewOperation && previewOperation.findings); actionCell.setAttribute('role', 'cell'); action.className = 'btn-secondary openapi-import-result-action'; action.href = wizardHref(operation.operation_id); action.textContent = previewOperation && previewOperation.findings && previewOperation.findings.length ? tKey('openapi.result.fix') : tKey('openapi.result.open'); actionCell.appendChild(action); row.append(nameCell, findingsCell, actionCell); table.appendChild(row); }); node.appendChild(table); if (created.length > OPERATIONS_PER_PAGE) { node.appendChild(createPageNavigation(state.resultPageIndex, created.length, 'openapi.pagination.result_label', function(page) { state.resultPageIndex = page; renderResult(response); })); } } if (response.skipped && response.skipped.length) { node.appendChild(renderSkippedPanel(response.skipped)); } if (response.findings && response.findings.length) { var findingsPanel = renderFindingsPanel(response.findings); findingsPanel.classList.add('openapi-import-result-findings'); node.appendChild(findingsPanel); } node.hidden = false; } function createdStatus(response) { if (response && response.counts) { return tfKey('openapi.plan.summary', { applied: (Number(response.counts.created) || 0) + (Number(response.counts.versioned) || 0) + (Number(response.counts.renamed) || 0), skipped: Number(response.counts.skipped) || 0, excluded: Number(response.counts.excluded) || 0, rejected: Number(response.counts.rejected) || 0, }); } return tfKey('openapi.status.created', { created: (response.created || []).length, skipped: (response.skipped || []).length, }); } function planActionLabel(candidate) { if (candidate.state === 'excluded') return tKey('openapi.plan.action.excluded'); if (candidate.state === 'blocked') return tKey('openapi.plan.action.blocked'); var action = String(candidate.action || 'create'); var key = 'openapi.plan.action.' + action; return tKey(key) === key ? tKey('openapi.plan.action.create') : tKey(key); } function updatePlanRevalidationUi(plan, hasBlocked) { var statusNode = qs('openapi-import-plan-revalidation-status'); var staleNode = qs('openapi-import-plan-stale'); var reopenButton = qs('openapi-import-plan-reopen'); var statusKey = 'openapi.plan.revalidation_' + state.planRevalidationState; statusNode.textContent = tKey(statusKey); var unsafe = state.planRevalidationState === 'stale' || state.planRevalidationState === 'error' || state.planRevalidationState === 'pending' || !!plan.revalidation_required || state.applyOutcomeUnknown; staleNode.hidden = !unsafe || state.planRevalidationState === 'pending' || state.applyOutcomeUnknown; staleNode.textContent = unsafe && !staleNode.hidden ? tKey('openapi.plan.revalidation_guidance') : ''; reopenButton.disabled = state.applyInFlight || state.applyOutcomeUnknown; reopenButton.setAttribute('aria-busy', state.planRevalidationState === 'pending' ? 'true' : 'false'); qs('openapi-import-plan-apply').disabled = hasBlocked || unsafe; } function renderImportPlan(plan, pageOnly) { var countsNode = qs('openapi-import-plan-counts'); var candidatesNode = qs('openapi-import-plan-candidates'); var versioningNode = qs('openapi-import-versioning-consequences'); var counts = plan.counts || {}; var hasBlocked = (Number(counts.blocked) || 0) > 0; var operationsByKey = Object.create(null); importOperations().forEach(function(operation) { operationsByKey[operation.key] = operation; }); if (!pageOnly) { // The plan API is the sole authority for each operation's binding outcome. (Array.isArray(plan.candidates) ? plan.candidates : []).forEach(function(candidate) { if (!candidate || !candidate.key) return; var operation = operationsByKey[candidate.key]; var alternativeIndex = candidate.security_alternative_index; var anonymous = alternativeIndex !== null && alternativeIndex !== undefined && isAnonymousAlternative(alternativeFor(operation, alternativeIndex)); var status; if (candidate.state === 'blocked') { status = 'blocked'; } else if (candidate.state === 'actionable') { // Only a genuine auth binding confirmed by the API is resolved; a // no-auth/anonymous or unbound candidate must never read as resolved. if (candidate.auth_profile_id) status = 'resolved'; else if (operation && !operationRequiresAuth(operation)) status = 'no_auth'; else if (anonymous) status = 'no_auth'; else status = 'unresolved'; } else { // Excluded/skipped candidates keep the operation untouched. status = 'unresolved'; } state.securityByOperation[candidate.key] = status; }); document.querySelectorAll('[data-openapi-security-op-status]').forEach(function(node) { var status = state.securityByOperation[node.dataset.openapiSecurityOpStatus] || 'unresolved'; node.dataset.status = status; node.textContent = securityStatusLabel(status); }); updateSecuritySummary(); } var countSpecs = [ ['selected', 'openapi.plan.selected'], ['excluded', 'openapi.plan.excluded'], ['actionable', 'openapi.plan.actionable'], ['blocked', 'openapi.plan.blocked'], ]; var planCandidates = Array.isArray(plan.candidates) ? plan.candidates : []; var planPageCount = Math.max(1, Math.ceil(planCandidates.length / OPERATIONS_PER_PAGE)); state.planPageIndex = Math.min(Math.max(0, state.planPageIndex), planPageCount - 1); state.planCandidates = planCandidates; countsNode.replaceChildren(); candidatesNode.replaceChildren(); var planPagination = qs('openapi-import-plan-pagination'); planPagination.hidden = planCandidates.length <= OPERATIONS_PER_PAGE; qs('openapi-import-plan-page-status').textContent = tfKey('openapi.pagination.status', { page: state.planPageIndex + 1, pages: planPageCount, total: planCandidates.length, }); qs('openapi-import-plan-page-previous').disabled = state.planPageIndex === 0; qs('openapi-import-plan-page-next').disabled = state.planPageIndex + 1 >= planPageCount; countSpecs.forEach(function(spec) { var item = document.createElement('span'); item.className = 'openapi-import-plan-count'; item.textContent = tfKey(spec[1], { count: Number(counts[spec[0]]) || 0 }); countsNode.appendChild(item); }); var hasNewVersion = planCandidates.some(function(candidate) { return candidate.action === 'new_version' && candidate.state !== 'blocked' && candidate.state !== 'excluded'; }); qs('openapi-import-plan-version').textContent = tfKey('openapi.plan.version', { version: state.planVersion, reference: plan.plan_reference, digest: plan.plan_digest, }); planCandidates.slice(state.planPageIndex * OPERATIONS_PER_PAGE, (state.planPageIndex + 1) * OPERATIONS_PER_PAGE).forEach(function(candidate) { var item = document.createElement('article'); var title = document.createElement('strong'); var key = document.createElement('code'); var action = document.createElement('p'); item.className = 'openapi-import-plan-candidate'; item.dataset.state = String(candidate.state || 'blocked'); title.textContent = String(candidate.name || candidate.key || tKey('openapi.result.unnamed')); key.textContent = String(candidate.key || ''); action.textContent = planActionLabel(candidate); item.append(title, key, action); if (candidate.target_operation_id) { var target = document.createElement('p'); target.textContent = tKey('openapi.plan.exact_target') + ': ' + candidate.target_operation_id; item.appendChild(target); } if (candidate.confirmed_name) { var confirmedName = document.createElement('p'); confirmedName.textContent = tKey('openapi.plan.confirmed_name') + ': ' + candidate.confirmed_name; item.appendChild(confirmedName); } if (candidate.reason) { var reason = document.createElement('p'); reason.className = 'openapi-import-plan-reason'; if (candidate.state === 'excluded') reason.dataset.testid = 'openapi-import-excluded-reason'; reason.textContent = findingMessage({ code: candidate.reason }); if (candidate.state === 'excluded') reason.textContent += ' (' + candidate.reason + ')'; item.appendChild(reason); } candidatesNode.appendChild(item); }); versioningNode.textContent = tKey('openapi.plan.versioning_new'); versioningNode.hidden = !hasNewVersion; qs('openapi-import-plan-confirmation').hidden = false; qs('openapi-import-plan-blocked-help').hidden = !hasBlocked; qs('openapi-import-result').hidden = true; updatePlanRevalidationUi(plan, hasBlocked); qs('openapi-import-plan-back').textContent = tKey(hasBlocked ? 'openapi.plan.back_fix' : 'openapi.plan.back'); if (!pageOnly) lockPlanEditing(true); } async function revalidateCurrentPlan() { if (!state.plan || state.applyInFlight || state.applyOutcomeUnknown) return; var planReference = state.plan.plan_reference; var generation = ++state.planRevalidationGeneration; state.planRevalidationState = 'pending'; updatePlanRevalidationUi(state.plan, (Number(state.plan.counts && state.plan.counts.blocked) || 0) > 0); try { var response = await window.CrankApi.revalidateOpenApiImportPlan( state.workspaceId, planReference, {} ); if (generation !== state.planRevalidationGeneration || !state.plan || state.plan.plan_reference !== planReference) return; if (!response || response.plan_reference !== planReference || !/^[a-f0-9]{64}$/.test(String(response.plan_digest || '')) || response.plan_digest !== state.plan.plan_digest || !response.counts || !Array.isArray(response.candidates) || typeof response.revalidation_required !== 'boolean') { throw new Error('Backend returned an invalid ImportPlan revalidation response'); } state.plan = Object.assign({}, state.plan, response); if (response.revalidation_status === 'stale' || response.revalidation_required) { state.planRevalidationState = 'stale'; } else if (response.revalidation_status === 'current' && !response.revalidation_required) { state.planRevalidationState = 'current'; } else { state.planRevalidationState = 'error'; } renderImportPlan(state.plan); } catch (_error) { if (generation !== state.planRevalidationGeneration || !state.plan || state.plan.plan_reference !== planReference) return; state.planRevalidationState = 'error'; updatePlanRevalidationUi(state.plan, (Number(state.plan.counts && state.plan.counts.blocked) || 0) > 0); } } function reportOutcomeLabel(outcome) { var value = String(outcome || 'rejected'); var key = 'openapi.plan.outcome.' + value; return tKey(key) === key ? tKey('openapi.plan.outcome.rejected') : tKey(key); } function renderImportPlanReport(report) { var node = qs('openapi-import-result'); var title = document.createElement('strong'); node.replaceChildren(); title.textContent = tKey('openapi.plan.result_title'); node.appendChild(title); var counts = report.counts || {}; var applied = (Number(counts.created) || 0) + (Number(counts.versioned) || 0) + (Number(counts.renamed) || 0); var summary = document.createElement('p'); summary.className = 'openapi-import-plan-summary'; summary.textContent = tfKey('openapi.plan.summary', { applied: applied, skipped: Number(counts.skipped) || 0, excluded: Number(counts.excluded) || 0, rejected: Number(counts.rejected) || 0, }); node.appendChild(summary); var outcomes = Array.isArray(report.outcomes) ? report.outcomes : []; if (outcomes.length) { var list = document.createElement('div'); list.className = 'openapi-import-plan-outcomes'; var pageCount = Math.max(1, Math.ceil(outcomes.length / OPERATIONS_PER_PAGE)); state.resultPageIndex = Math.min(Math.max(0, state.resultPageIndex), pageCount - 1); outcomes.slice(state.resultPageIndex * OPERATIONS_PER_PAGE, (state.resultPageIndex + 1) * OPERATIONS_PER_PAGE).forEach(function(outcome) { var item = document.createElement('article'); var heading = document.createElement('strong'); var key = document.createElement('code'); var detail = document.createElement('p'); var outcomeStatus = outcome.status || outcome.outcome || 'rejected'; item.className = 'openapi-import-plan-outcome'; item.dataset.outcome = String(outcomeStatus); heading.textContent = String(outcome.name || outcome.key || tKey('openapi.result.unnamed')); key.textContent = String(outcome.key || ''); detail.textContent = reportOutcomeLabel(outcomeStatus); if (Number.isInteger(outcome.version)) { detail.textContent += ' · v' + outcome.version; } item.append(heading, key, detail); if (outcome.reason) { var reason = document.createElement('p'); reason.className = 'openapi-import-plan-reason'; reason.textContent = findingMessage({ code: outcome.reason }); item.appendChild(reason); } list.appendChild(item); }); node.appendChild(list); if (outcomes.length > OPERATIONS_PER_PAGE) { node.appendChild(createPageNavigation(state.resultPageIndex, outcomes.length, 'openapi.pagination.result_label', function(page) { state.resultPageIndex = page; renderImportPlanReport(report); })); } } if (state.onboarding) renderOnboardingDraftChoice(node, report); node.hidden = false; qs('openapi-import-plan-confirmation').hidden = true; } function renderOnboardingDraftChoice(node, report) { var previous = node.querySelector('[data-testid="onboarding-import-draft-choice"]'); if (previous) previous.remove(); var outcomes = Array.isArray(report.outcomes) ? report.outcomes : []; var context = state.importContext; var choices = context && Array.isArray(context.choices) ? context.choices : []; if (!choices.length) { choices = outcomes.map(function(outcome) { return { key: outcome.key, name: outcome.name, operation_id: outcome.operation_id, version: outcome.version, outcome: outcome.status || outcome.outcome, selectable: false, reason: tKey('onboarding.import.registration_pending'), }; }); } if (!choices.length) return; var chooser = document.createElement('div'); chooser.className = 'onboarding-import-draft-choice'; chooser.dataset.testid = 'onboarding-import-draft-choice'; var heading = document.createElement('strong'); heading.className = 'onboarding-import-draft-choice-title'; heading.textContent = tKey('onboarding.import.choose_draft'); chooser.appendChild(heading); var list = document.createElement('div'); list.className = 'onboarding-import-draft-choice-list'; choices.forEach(function(outcome) { var wrapper = document.createElement('div'); wrapper.className = 'onboarding-import-draft-option-row'; var label = document.createElement('span'); label.textContent = [ outcome.name || outcome.key || tKey('openapi.result.unnamed'), outcomeMessage(outcome.outcome), outcome.version ? 'v' + outcome.version : '', outcome.reason ? findingMessage({ code: outcome.reason }) : '', ] .filter(Boolean).join(' · '); wrapper.appendChild(label); var alreadySelected = context && context.selected_operation_id === outcome.operation_id && Number(context.selected_operation_version) === Number(outcome.version); if (alreadySelected) { var selected = document.createElement('span'); selected.className = 'onboarding-import-draft-selected'; selected.textContent = tKey('onboarding.import.selected'); wrapper.appendChild(selected); } else if (outcome.selectable === true && !(context && context.selected_operation_id && !context.drift)) { var choice = document.createElement('button'); choice.type = 'button'; choice.className = 'btn-secondary onboarding-import-draft-option'; choice.textContent = tKey('onboarding.import.continue'); choice.addEventListener('click', function() { chooseDraft(outcome); }); wrapper.appendChild(choice); } list.appendChild(wrapper); }); if (context && context.drift) { var drift = document.createElement('p'); drift.className = 'onboarding-import-drift'; drift.setAttribute('role', 'alert'); drift.textContent = tKey('onboarding.import.drift'); chooser.appendChild(drift); } chooser.appendChild(list); node.appendChild(chooser); } async function chooseDraft(outcome) { var operationId = outcome && outcome.operation_id; var version = outcome && Number.isInteger(outcome.version) ? outcome.version : null; if (!operationId || !Number.isInteger(version) || version < 1 || !state.importContext) return; var revision = state.revision; var workspaceId = state.workspaceId; var language = locale(); if (!isCurrent(revision, workspaceId, language)) return; try { var response = typeof state.onSelectDraft === 'function' ? await state.onSelectDraft(operationId, version, { applicationIdempotencyKey: state.importContext.application_idempotency_key, planDigest: state.importContext.plan_digest, }) : null; if (!isCurrent(revision, workspaceId, language)) return; var current = response && response.onboarding ? response.onboarding : response; if (!current || !current.import_context || current.import_context.selected_operation_id !== operationId || Number(current.import_context.selected_operation_version) !== version) { throw new Error(tKey('onboarding.import.selection_failed')); } state.importContext = current.import_context; renderImportPlanReport(current.import_context.report || state.applyResult); var target = ((window.CrankRoutes && window.CrankRoutes.wizard) || '/wizard/') + '?mode=edit&operationId=' + encodeURIComponent(operationId) + '&operationVersion=' + encodeURIComponent(version) + '&onboarding=1' + (state.returnContext ? '&return=' + encodeURIComponent(state.returnContext) : ''); window.location.href = target; } catch (error) { if (!isCurrent(revision, workspaceId, language)) return; if (error && error.status === 409 && window.CrankOnboarding && typeof window.CrankOnboarding.refresh === 'function') { var refreshed = await window.CrankOnboarding.refresh(); if (!isCurrent(revision, workspaceId, language)) return; if (refreshed && refreshed.import_context) { state.importContext = refreshed.import_context; renderImportPlanReport(refreshed.import_context.report || state.applyResult); } } setStatus(error && error.status === 409 ? tKey('onboarding.import.conflict_reload') : tKey('onboarding.import.selection_failed'), true, true); } } function recoveryCode(payload) { var value = payload && payload.error && typeof payload.error === 'object' ? payload.error : payload; var context = value && value.context && typeof value.context === 'object' ? value.context : value; return String((context && context.recovery) || (payload && payload.recovery) || ''); } function reportFromPayload(payload) { if (!payload || typeof payload !== 'object') return null; var errorContext = payload.error && payload.error.context; var report = payload.report || payload.apply_report || (errorContext && (errorContext.report || errorContext.apply_report || errorContext)) || payload; return report && Array.isArray(report.outcomes) ? report : null; } async function notifyImported(revision, workspaceId, language, request) { if (typeof state.onImported !== 'function') return; if (!state.onboarding) { try { await state.onImported(); } catch (_refreshError) { if (isCurrent(revision, workspaceId, language) && state.applyResult) { state.applyRefreshFailed = true; setStatus(createdStatus(state.applyResult) + ' ' + tKey('openapi.status.refresh_failed'), false, true); } } return; } if (!request || !state.applyResult || state.applyResult.status !== 'applied') return; try { var identity = { applicationIdempotencyKey: state.applyResult.idempotency_key, planDigest: state.applyResult.plan_digest, }; if (identity.applicationIdempotencyKey !== request.idempotencyKey || identity.planDigest !== request.planDigest) { throw new Error(tKey('onboarding.import.registration_failed')); } state.importIdentity = identity; var current = await state.onImported(identity); if (!isCurrent(revision, workspaceId, language)) return; if (current && current.import_context) { state.importContext = current.import_context; renderImportPlanReport(current.import_context.report || state.applyResult); } } catch (_error) { if (isCurrent(revision, workspaceId, language) && state.applyResult) { state.applyRefreshFailed = true; var status = qs('openapi-import-status'); setStatus(createdStatus(state.applyResult) + ' ' + tKey('onboarding.import.registration_failed'), true, true); if (state.importIdentity && status) { var retry = document.createElement('button'); retry.type = 'button'; retry.className = 'btn-secondary onboarding-import-registration-retry'; retry.textContent = tKey('onboarding.import.retry_registration'); retry.addEventListener('click', async function() { var retryRevision = state.revision; var retryWorkspaceId = state.workspaceId; var retryLanguage = locale(); if (!isCurrent(retryRevision, retryWorkspaceId, retryLanguage)) return; retry.disabled = true; try { var current = await state.onImported(state.importIdentity); if (!isCurrent(retryRevision, retryWorkspaceId, retryLanguage)) return; if (!current || !current.import_context) throw new Error(tKey('onboarding.import.registration_failed')); state.importContext = current.import_context; renderImportPlanReport(current.import_context.report || state.applyResult); state.applyRefreshFailed = false; setStatus(tKey('openapi.status.applied')); } catch (_retryError) { if (!isCurrent(retryRevision, retryWorkspaceId, retryLanguage)) return; retry.disabled = false; setStatus(tKey('onboarding.import.registration_failed'), true, true); status.appendChild(retry); } }); status.appendChild(retry); } } } } async function submitApply(request) { if (state.applyInFlight) return; // Claim the attempt — including the controller used by the cancel path — // before the first await. A second click cannot start a parallel replay // with a different idempotency key, and Escape/close or a workspace or // language change during the session wait aborts this attempt instead of // letting it install itself and POST afterwards. var controller = new AbortController(); var revision = state.revision; var workspaceId = request.workspaceId; var language = locale(); state.applyController = controller; state.applyInFlight = true; state.applyOutcomeUnknown = false; state.applyRefreshFailed = false; lockApplyInputs(true); qs('openapi-import-cancel').hidden = false; showRetry(false); setStatus(tKey('openapi.status.applying')); // A replay can start right after a reload, before the shell has restored the // session and its CSRF token; sending the mutation without that token would // be rejected as forbidden. Wait for the already-required authenticated // session instead of firing an unauthenticated POST. if (window.CrankAuth && typeof window.CrankAuth.getCsrfToken === 'function' && !window.CrankAuth.getCsrfToken() && typeof window.CrankAuth.fetchSession === 'function') { try { await window.CrankAuth.fetchSession(true); } catch (_error) { // A missing session stays a real 401/403 from the API, never a silent // local success. } // A cancelled or superseded attempt owns no authority any more: it must // neither re-install itself over the cancel/unknown state nor send its // POST after the wait. if (state.applyController !== controller) return; } try { var response = await window.CrankApi.applyOpenApiImportPlan( workspaceId, request.planReference, { plan_digest: request.planDigest, idempotency_key: request.idempotencyKey, }, { signal: controller.signal } ); // Abort is advisory: a superseded request can still deliver a response. // Only the controller installed by this attempt may mutate UI authority. if (state.applyController !== controller) return; state.applyOutcomeUnknown = false; clearApplyReplay(); state.applyController = null; state.applyInFlight = false; lockApplyInputs(false); qs('openapi-import-cancel').hidden = true; showRetry(false); if (!isSameContext(revision, workspaceId, language)) { // The original workspace job is now resolved. Do not render its result // into another workspace/language context. state.applyResult = null; state.applyRequest = null; return; } state.applyResult = response; state.resultPageIndex = 0; state.applyRequest = null; state.plan = null; if (isCurrent(revision, workspaceId, language)) { if (Array.isArray(response.outcomes)) renderImportPlanReport(response); else renderResult(response); if (response.recovery === 'repreview_required') { setStatus(tKey('openapi.plan.repreview'), true, true); showRetry(true); } else if (response.status === 'rejected' || response.recovery === 'confirm_skip_rename_or_new_version') { setStatus(tKey('openapi.plan.resolve_conflict'), true, true); showRetry(true); } else { setStatus(tKey('openapi.status.applied')); } } await notifyImported(revision, workspaceId, language, request); } catch (error) { // A cancelled attempt may settle after an idempotent retry has already // installed a new controller. It must not overwrite the newer state. if (state.applyController !== controller) return; if (error && error.name === 'AbortError') { state.applyOutcomeUnknown = true; persistApplyReplay(state.applyRequest); lockApplyInputs(true); showRetry(true); if (!qs('openapi-import-modal').hidden) { setStatus(tKey('openapi.plan.retry_unknown'), true, true); } return; } if (Number.isInteger(error && error.status) && error.status >= 400 && error.status < 500 && error.status !== 408) { state.applyOutcomeUnknown = false; state.applyRequest = null; clearApplyReplay(); showRetry(true); var report = reportFromPayload(error.payload); if (report && isCurrent(revision, workspaceId, language)) { state.applyResult = report; state.resultPageIndex = 0; renderImportPlanReport(report); } var recovery = recoveryCode(error.payload); state.plan = null; qs('openapi-import-plan-confirmation').hidden = true; lockPlanEditing(false); // A rejected/repreview Apply voids the prior resolved security review. resetSecurityStatuses(); if (!qs('openapi-import-modal').hidden) { if (recovery === 'repreview_required') { setStatus(tKey('openapi.plan.repreview'), true, true); } else if (recovery === 'confirm_skip_rename_or_new_version') { setStatus(tKey('openapi.plan.resolve_conflict'), true, true); } else { setStatus(errorStatus(error, 'openapi.error.apply'), true, true); } } return; } // A browser/network failure is not proof that the server rolled the // transaction back. Replaying this exact plan is idempotent server-side. state.applyOutcomeUnknown = true; persistApplyReplay(state.applyRequest); lockApplyInputs(true); showRetry(true); if (!qs('openapi-import-modal').hidden) { setStatus(errorStatus(error, 'openapi.error.apply') + ' ' + tKey('openapi.plan.retry_unknown'), true, true); } } finally { if (state.applyController === controller) { state.applyController = null; state.applyInFlight = false; lockApplyInputs(state.applyOutcomeUnknown); qs('openapi-import-cancel').hidden = true; } } } async function createImportPlan() { if (state.applyInFlight || state.planController) return; var keys = selectedKeys(); if (!keys.length) { setStatus(tKey('openapi.error.selection'), true, true); return; } if (keys.length > 2000 || importOperations().length - keys.length > 2000) { setStatus(tKey('openapi.error.plan_too_large'), true, true); return; } if (!state.jobId || !state.preview) { setStatus(tKey('openapi.error.preview_required'), true, true); return; } var serverUrl = (qs('openapi-import-server-custom').value || qs('openapi-import-server').value || '').trim(); if (!serverUrl) { setStatus(tKey('openapi.error.server'), true, true); return; } if (!state.workspaceId) { setStatus(tKey('openapi.error.workspace'), true, true); return; } if (!state.operationsReady) { setStatus(tKey('openapi.error.operations_unavailable'), true, true); return; } var selectedSet = new Set(keys); var decisions = []; var invalidDecision = null; importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key)) return; var decision = decisionFor(operation.key); // Skip decisions keep the existing operation untouched: no security // binding may be attached to them. if (decision.action === 'skip' && (decision.authProfileId || decision.securityAlternativeIndex !== null)) { invalidDecision = 'openapi.error.security_with_skip'; } }); importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key) || invalidDecision) return; var decision = decisionFor(operation.key); var output = { operation_key: operation.key, action: decision.action }; if (decision.action === 'skip' || decision.action === 'new_version') { var allowedTargets = matchingOperations(operation).filter(function(existing) { return decision.action !== 'new_version' || (existing.protocol === 'rest' && existing.status !== 'archived'); }); if (!allowedTargets.some(function(existing) { return existing.id === decision.targetOperationId; })) { invalidDecision = 'openapi.error.decision_target'; return; } output.target_operation_id = decision.targetOperationId; } else if (decision.action === 'rename') { if (!decision.confirmedName || !decision.confirmedName.trim()) { invalidDecision = 'openapi.error.confirmed_name'; return; } output.confirmed_name = decision.confirmedName; } else if (decision.action !== 'create') { invalidDecision = 'openapi.error.decision_action'; return; } // Security binding is a typed reference only: alternative index and, // when chosen, the profile id. Resolution stays server-side. if (decision.action !== 'skip') { if (decision.authProfileId) output.auth_profile_id = decision.authProfileId; if (decision.securityAlternativeIndex !== null) { output.security_alternative_index = decision.securityAlternativeIndex; } } if (decision.action !== 'create' || decision.authProfileId || decision.securityAlternativeIndex !== null) { decisions.push(output); } }); if (invalidDecision) { setStatus(tKey(invalidDecision), true, true); return; } var selectionMode = state.partialMode ? 'partial' : 'full'; var payload = { selection_mode: selectionMode, selected_operation_keys: keys, server_url: serverUrl, decisions: decisions, }; var revision = state.revision; var workspaceId = state.workspaceId; var language = locale(); var controller = new AbortController(); state.planRevalidationGeneration += 1; state.planRevalidationState = 'current'; state.planController = controller; state.plan = null; lockPlanEditing(true); qs('openapi-import-cancel').hidden = false; qs('openapi-import-plan-confirmation').hidden = true; showRetry(false); setStatus(tKey('openapi.status.planning')); try { var plan = await window.CrankApi.createOpenApiImportPlan( workspaceId, state.jobId, payload, { signal: controller.signal } ); if (state.planController !== controller) return; if (!isCurrent(revision, workspaceId, language)) return; if (!plan || typeof plan.plan_reference !== 'string' || !/^[a-f0-9]{64}$/.test(String(plan.plan_digest || '')) || !plan.counts || !Array.isArray(plan.candidates)) { throw new Error('Backend returned an invalid ImportPlan response'); } state.plan = plan; state.planVersion += 1; state.planPageIndex = 0; state.planRevalidationState = plan.revalidation_status === 'stale' || plan.revalidation_required ? 'stale' : 'current'; renderImportPlan(plan); setStatus(tKey('openapi.status.plan_ready')); } catch (error) { if (state.planController !== controller) return; if (error && error.name === 'AbortError') { setStatus(tKey('openapi.status.cancelled')); return; } setStatus(errorStatus(error, 'openapi.error.plan'), true, true); showRetry(true); // A typed API rejection of a security binding is authoritative blocked; // a transport/network failure only means the selection is unverified. var securityRejection = Number.isInteger(error && error.status) && error.status >= 400 && error.status < 500 && SECURITY_PLAN_ERROR_CODES.indexOf(String(error.code)) >= 0; importOperations().forEach(function(operation) { if (!selectedSet.has(operation.key) || !securityAlternativesFor(operation).length) return; setOperationSecurityStatus(operation.key, securityRejection ? 'blocked' : 'unverified'); }); updateSecuritySummary(); } finally { if (state.planController === controller) { state.planController = null; lockPlanEditing(!!state.plan); qs('openapi-import-cancel').hidden = true; } } } function newIdempotencyKey() { if (window.crypto && typeof window.crypto.randomUUID === 'function') { return 'openapi:' + window.crypto.randomUUID(); } return 'openapi:' + Date.now().toString(36) + ':' + Math.random().toString(36).slice(2); } async function applyImportPlan() { if (state.applyInFlight || !state.plan || state.applyOutcomeUnknown) return; if (state.planRevalidationState !== 'current' || state.plan.revalidation_required) return; var request = { workspaceId: state.workspaceId, planReference: state.plan.plan_reference, planDigest: state.plan.plan_digest, idempotencyKey: newIdempotencyKey(), }; if (!validApplyReplay(request)) { setStatus(tKey('openapi.error.apply'), true, true); return; } state.applyRequest = request; persistApplyReplay(request); await submitApply(request); } function backToImportSelection() { if (state.applyInFlight || state.applyOutcomeUnknown) return; state.planRevalidationGeneration += 1; state.plan = null; state.planRevalidationState = 'current'; // Returning to editing voids the previous review: revalidation is done by // the next plan request. resetSecurityStatuses(); qs('openapi-import-plan-confirmation').hidden = true; qs('openapi-import-plan-counts').replaceChildren(); qs('openapi-import-plan-candidates').replaceChildren(); qs('openapi-import-versioning-consequences').hidden = true; qs('openapi-import-plan-blocked-help').hidden = true; qs('openapi-import-plan-stale').hidden = true; qs('openapi-import-plan-revalidation-status').textContent = ''; qs('openapi-import-plan-back').textContent = tKey('openapi.plan.back'); lockPlanEditing(false); setStatus(tKey('openapi.status.preview_ready')); } function retryCurrent() { if (state.applyOutcomeUnknown && state.applyRequest) { return submitApply(state.applyRequest); } return preview(); } function reset() { state.importContext = null; state.importIdentity = null; invalidate({ clearFile: true }); showRetry(false); setStatus(''); qs('openapi-import-server-custom').value = ''; } function open(options) { var changedWorkspace = state.workspaceId !== options.workspaceId; if (state.workspaceId && state.workspaceId !== options.workspaceId && !(state.applyOutcomeUnknown && state.applyRequest)) { invalidate({ clearFile: true }); } if (changedWorkspace) state.importIdentity = null; state.workspaceId = options.workspaceId; state.onImported = options.onImported; state.onboarding = options.onboarding === true; if (Object.prototype.hasOwnProperty.call(options, 'importContext')) { state.importContext = options.importContext || null; } else if (changedWorkspace) { state.importContext = null; } state.returnContext = typeof options.returnContext === 'string' ? options.returnContext : null; state.onSelectDraft = typeof options.onSelectDraft === 'function' ? options.onSelectDraft : null; state.restoreFocus = document.activeElement; qs('openapi-import-modal').hidden = false; renderFileName(); if (state.importContext && state.importContext.report) { renderImportPlanReport(state.importContext.report); setStatus(tKey('onboarding.import.report_title')); } else if (state.applyResult) { if (state.importContext && state.importContext.report) { renderImportPlanReport(state.importContext.report); } else if (Array.isArray(state.applyResult.outcomes)) { renderImportPlanReport(state.applyResult); } else { renderResult(state.applyResult); } if (state.applyResult.recovery === 'repreview_required') { showRetry(true); setStatus(tKey('openapi.plan.repreview'), true, true); } else if (state.applyResult.status === 'rejected' || state.applyResult.recovery === 'confirm_skip_rename_or_new_version') { showRetry(true); setStatus(tKey('openapi.plan.resolve_conflict'), true, true); } else { setStatus(createdStatus(state.applyResult) + (state.applyRefreshFailed ? ' ' + tKey('openapi.status.refresh_failed') : '')); } } else if (state.applyOutcomeUnknown && state.applyRequest) { lockApplyInputs(true); showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); qs('openapi-import-retry').focus(); return; } qs('openapi-import-file-select').focus(); } function close() { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown({ render: false }); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } return; } if (state.applyOutcomeUnknown && state.applyRequest) { persistApplyReplay(state.applyRequest); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } return; } invalidate({ clearFile: true }); showRetry(false); qs('openapi-import-modal').hidden = true; if (state.restoreFocus && typeof state.restoreFocus.focus === 'function') { state.restoreFocus.focus(); } } function selectFile(file) { state.importContext = null; state.importIdentity = null; clearServerSelection(); invalidate(); state.file = file || null; showRetry(false); var localError = validateFile(state.file); renderFileName(); if (localError) { setStatus(tKey(localError), true, true); } else if (state.file) { setStatus(tKey('openapi.status.file_ready')); } } document.addEventListener('DOMContentLoaded', function() { if (!qs('openapi-import-modal')) return; renderFileName(); // Dedicated screen-reader output for the API-authoritative binding state. var groupsNode = qs('openapi-import-groups'); if (!qs('openapi-import-security-status') && groupsNode && groupsNode.parentNode) { var securityStatusNode = document.createElement('div'); securityStatusNode.id = 'openapi-import-security-status'; securityStatusNode.className = 'openapi-import-security-status'; securityStatusNode.setAttribute('data-testid', 'openapi-security-status'); securityStatusNode.setAttribute('role', 'status'); securityStatusNode.setAttribute('aria-live', 'polite'); groupsNode.parentNode.insertBefore(securityStatusNode, groupsNode); } qs('openapi-import-file-select').addEventListener('click', function(event) { event.preventDefault(); qs('openapi-import-file').click(); }); qs('openapi-import-file').addEventListener('change', function(event) { selectFile(event.target.files && event.target.files[0]); }); qs('openapi-import-preview').addEventListener('click', preview); qs('openapi-import-retry').addEventListener('click', retryCurrent); qs('openapi-import-create').addEventListener('click', createImportPlan); qs('openapi-import-plan-apply').addEventListener('click', applyImportPlan); qs('openapi-import-plan-back').addEventListener('click', backToImportSelection); qs('openapi-import-cancel').addEventListener('click', cancelCurrent); qs('openapi-import-reset').addEventListener('click', reset); qs('openapi-import-search').addEventListener('input', function(event) { state.filterQuery = event.target.value.trim(); applyFilters(); }); qs('openapi-import-method-filter').addEventListener('change', function(event) { state.filterMethod = event.target.value; applyFilters(); }); qs('openapi-import-select-visible').addEventListener('click', function() { setVisibleSelection(true); }); qs('openapi-import-clear-visible').addEventListener('click', function() { setVisibleSelection(false); }); qs('openapi-import-partial-mode').addEventListener('change', function(event) { state.partialMode = event.target.checked && !documentIsBlocked(); event.target.checked = state.partialMode; if (!state.partialMode) state.selectedOperationKeys = new Set(importOperations().map(function(operation) { return operation.key; })); else importOperations().forEach(function(operation) { if (operationIsBlocked(operation)) state.selectedOperationKeys.delete(operation.key); }); renderOperationPage(); qs('openapi-import-select-visible').disabled = !state.partialMode; qs('openapi-import-clear-visible').disabled = !state.partialMode; lockPlanEditing(false); updateSelection(); }); qs('openapi-import-page-previous').addEventListener('click', function() { if (state.pageIndex <= 0) return; state.pageIndex -= 1; renderOperationPage(); updateSelection(); }); qs('openapi-import-page-next').addEventListener('click', function() { state.pageIndex += 1; renderOperationPage(); updateSelection(); }); qs('openapi-import-plan-page-previous').addEventListener('click', function() { if (state.planPageIndex <= 0 || !state.plan) return; state.planPageIndex -= 1; renderImportPlan(state.plan, true); }); qs('openapi-import-plan-page-next').addEventListener('click', function() { if (!state.plan || state.planPageIndex + 1 >= Math.ceil((state.plan.candidates || []).length / OPERATIONS_PER_PAGE)) return; state.planPageIndex += 1; renderImportPlan(state.plan, true); }); qs('openapi-import-plan-reopen').addEventListener('click', revalidateCurrentPlan); document.querySelectorAll('[data-openapi-close]').forEach(function(node) { node.addEventListener('click', close); }); document.addEventListener('keydown', function(event) { var modal = qs('openapi-import-modal'); if (event.key === 'Escape' && !qs('openapi-import-modal').hidden) { event.preventDefault(); close(); } if (event.key !== 'Tab' || modal.hidden) return; var focusable = Array.from(modal.querySelectorAll('button:not([disabled]):not([hidden]), input:not([disabled]), select:not([disabled]), a[href]')) .filter(function(node) { return node.tabIndex >= 0 && !node.closest('[hidden]'); }); if (!focusable.length) return; var first = focusable[0]; var last = focusable[focusable.length - 1]; if (event.shiftKey && (document.activeElement === first || !modal.contains(document.activeElement))) { event.preventDefault(); last.focus(); } else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); } }); function invalidateForContext(options) { if (!qs('openapi-import-modal').hidden) { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown(); return; } if (state.applyOutcomeUnknown && state.applyRequest) { showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); return; } invalidate(options); renderFileName(); showRetry(!options || !options.clearFile ? !!state.file : false); setStatus(tKey('openapi.status.context_changed')); } } function handleLanguageChange() { // While an Apply owns the locked controls, re-rendering would re-enable // them. Route straight to the context-change path, which marks the apply // outcome unknown and keeps the controls locked. if (state.applyInFlight || state.applyController || (state.applyOutcomeUnknown && state.applyRequest)) { renderSecurityStatus(); invalidateForContext(); return; } importOperations().forEach(function(operation) { var row = operationRowFor(operation); if (row) { renderDecisionControls(operation, row); renderSecurityControls(operation, row); } }); if (state.preview) renderOperationPage(); if (!qs('openapi-import-modal').hidden && state.plan) { renderImportPlan(state.plan); setStatus(tKey('openapi.status.plan_ready')); return; } updateSecuritySummary(); invalidateForContext(); } window.addEventListener('crank:langchange', handleLanguageChange); window.addEventListener('crank:workspacechange', function(event) { if (!qs('openapi-import-modal').hidden) { state.workspaceId = event.detail && event.detail.id || null; invalidateForContext({ clearFile: true }); } }); window.addEventListener('storage', function(event) { if (event.key === 'crank_lang') handleLanguageChange(); }); window.addEventListener('pagehide', function() { if (state.applyInFlight || state.applyController) { markApplyOutcomeUnknown({ render: false }); state.file = null; qs('openapi-import-file').value = ''; renderFileName(); } else if (state.applyOutcomeUnknown && state.applyRequest) { persistApplyReplay(state.applyRequest); } else { invalidate({ clearFile: true }); } clearServerSelection(); showRetry(false); setStatus(''); }); window.addEventListener('pageshow', function(event) { if (!event.persisted || qs('openapi-import-modal').hidden) return; if (state.applyOutcomeUnknown && state.applyRequest) { lockApplyInputs(true); showRetry(true); setStatus(tKey('openapi.plan.retry_unknown'), true, true); } else { invalidateForContext({ clearFile: true }); } }); }); window.CrankOpenApiImport = { open: open, close: close, reset: reset, describeFinding: function(code) { return findingMessage({ code: code }); }, }; }());