Files
crank/apps/ui/js/resources.js
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

2416 lines
98 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* Story 3.6/3.7 — Resources: drafts, inert preview, exact publication, binding, archive.
*
* Страница показывает Draft инертно (D-6): метаданные — текстом, содержимое только
* для kind=text/json и через `textContent`. Для kind=binary bytes не загружаются
* вообще; скачивание идёт отдельной ссылкой на attachment-эндпоинт, поэтому
* markup никогда не исполняется в origin Crank.
*
* Один снимок ответа (P3): metadata, digest, size, version, инертный текст и ссылка
* скачивания относятся к одному выбранному Draft, а форма редактирования отправляет
* precondition (`expected_updated_at`) той же загрузки, а не сохранённое ранее значение.
*
* Story 3.7: lifecycle-действия (publish/archive) идут через реальный API с точным
* precondition и обязательным подтверждением; точная Published Version читается
* отдельным `GET .../versions/{integer}` (не latest-alias), а binding отправляется в
* существующий `POST .../agents/{id}/bindings`, сохраняя Operation bindings,
* tool_selection_policy и прочие Resource bindings из зафиксированного снимка Agent.
*
* Мутации отправляются синхронно из обработчика (multipart собирается без ожиданий),
* чтобы переход страницы не оборвал принятый запрос.
*/
function initResourcesPage() {
var PREVIEW = '[data-testid="resources-preview"]';
var PREVIEW_TEXT = '[data-testid="resource-preview-text"]';
var PREVIEW_ERROR = '[data-testid="resource-preview-error"]';
var META_URI = '[data-testid="resource-meta-uri"]';
var META_NAME = '[data-testid="resource-meta-name"]';
var META_KIND = '[data-testid="resource-meta-kind"]';
var META_MIME = '[data-testid="resource-meta-mime"]';
var META_SIZE = '[data-testid="resource-meta-size"]';
var META_DIGEST = '[data-testid="resource-meta-digest"]';
var META_VERSION = '[data-testid="resource-meta-version"]';
var META_DESCRIPTION = '[data-testid="resource-meta-description"]';
var META_SENSITIVITY = '[data-testid="resource-meta-sensitivity"]';
// Story 3.7 lifecycle contract.
var STATUS = '[data-testid="resource-status"]';
var FINDINGS_LIST = '[data-testid="resource-preview-findings-list"]';
var FINDINGS_EMPTY = '[data-testid="resource-preview-findings-empty"]';
var root = document.querySelector(PREVIEW);
if (!root) {
return;
}
var createForm = document.getElementById('resource-create-form');
var editForm = document.getElementById('resource-edit-form');
var listElement = document.getElementById('resource-list');
var listStatus = document.getElementById('resources-list-status');
var statusElement = document.getElementById('resources-status');
var downloadElement = document.getElementById('resource-download');
var createStatus = document.getElementById('resource-create-status');
var editStatus = document.getElementById('resource-edit-status');
var lifecycleCard = document.getElementById('resource-lifecycle-card');
var publishButton = document.getElementById('resource-publish');
var archiveButton = document.getElementById('resource-archive');
var publishStatus = document.getElementById('resource-publish-status');
var archiveStatus = document.getElementById('resource-archive-status');
var archivedHint = document.getElementById('resource-archived-hint');
var confirmHost = document.getElementById('resource-confirm-host');
var staleHost = document.getElementById('resource-stale-host');
var publishedHost = document.getElementById('resource-published-host');
var bindForm = document.getElementById('resource-bind');
var bindAgent = document.getElementById('resource-bind-agent');
var bindVersion = document.getElementById('resource-bind-version');
var bindAgentVersion = document.getElementById('resource-bind-agent-version');
var bindSubmit = document.getElementById('resource-bind-submit');
var bindStatus = document.getElementById('resource-bind-status');
var bindStale = document.getElementById('resource-bind-stale');
var bindReload = document.getElementById('resource-bind-reload');
var findingsTitle = document.getElementById('resource-findings-title');
// Story 3.10: REST-backed Resource template (source selection/mapping/publish).
var sourceMode = document.getElementById('resource-source-mode');
var staticContent = document.getElementById('resource-static-content');
var sourcePanel = document.getElementById('resource-source-panel');
var sourceLoading = document.getElementById('resource-source-loading');
var sourceEmpty = document.getElementById('resource-source-empty');
var sourceOperation = document.getElementById('resource-source-operation');
var sourceVersion = document.getElementById('resource-source-version');
var sourceUriTemplate = document.getElementById('resource-source-uri-template');
var sourceBind = document.getElementById('resource-source-bind');
var sourcePreview = document.getElementById('resource-source-preview');
var sourceStatus = document.getElementById('resource-source-status');
var sourceParamsHost = document.getElementById('resource-source-params');
var draftParamsHost = document.getElementById('resource-draft-params');
var sourceFacts = document.getElementById('resource-source-facts');
var sourcePinned = document.getElementById('resource-source-pinned');
var sourceSafety = document.getElementById('resource-source-safety');
var sourceSensitivity = document.getElementById('resource-source-sensitivity');
var sourceAccess = document.getElementById('resource-source-access');
var sourceFindings = document.getElementById('resource-source-findings');
var templates = {
publishConfirm: document.getElementById('resource-publish-confirm-template'),
archiveConfirm: document.getElementById('resource-archive-confirm-template'),
stale: document.getElementById('resource-stale-template'),
published: document.getElementById('resource-published-template'),
importConfirm: document.getElementById('resource-import-confirm-template'),
};
// Story 3.9 portability contract.
var exportLink = document.getElementById('resource-export');
var exportStatus = document.getElementById('resource-export-status');
var importFile = document.getElementById('resource-import-file');
var importSubmit = document.getElementById('resource-import-submit');
var importStatus = document.getElementById('resource-import-status');
var importError = document.getElementById('resource-import-error');
var importConfirmHost = document.getElementById('resource-import-confirm-host');
var portabilityStaleHost = document.getElementById('resource-portability-stale-host');
var state = {
workspaceId: '',
resourceId: '',
updatedAt: '',
version: null,
digest: '',
loadToken: 0,
/// Поколение принятых мутаций выбранного Resource: поздний preview-ответ прежнего
/// поколения не откатывает metadata/CAS уже изменённого Resource.
mutationToken: 0,
status: '',
latestPublishedVersion: null,
/// Текущий выбор успешно загружен: только его снимок владеет lifecycle/CAS/версией.
selectedLoaded: false,
/// Точная Published Version этого выбора реально прочитана (не только указатель).
publishedReady: false,
/// Coherent content snapshot текущего выбора реально прочитан: только тогда
/// редактор содержит bytes Resource и может отправить metadata-only правку.
contentReady: false,
agents: null,
bind: null,
/// Story 3.10: source открытого template Draft и его server-authoritative findings.
source: null,
sourceFindings: [],
pinnedInputFields: Object.create(null),
/// Зафиксированная в create-форме версия операции (source ещё не создан).
binding: null,
bindingToken: 0,
};
var actionBusy = false;
var bindBusy = false;
var resourceTestToken = 0;
/// Новый выбор увеличивает поколение загрузки. Любой ответ прежнего поколения
/// (карточка, предпросмотр, ошибка или reload после правки) уже не применяется к
/// экрану и не меняет цель редактирования (F2). Тот же токен защищает lifecycle,
/// Published snapshot и binding от ответов прежнего выбора.
///
/// D1: lifecycle/CAS/точная версия прежнего Resource не переживают смену выбора —
/// иначе новый (или неудачно загруженный) Resource можно было бы отправить в
/// publish/archive/bind с чужим precondition/версией.
function beginSelection(id) {
state.resourceId = id;
state.loadToken += 1;
invalidateSelectionState();
resetTransientSections();
clearHost(confirmHost);
clearHost(staleHost);
clearHost(publishedHost);
clearPortabilityTransient();
setStatus(publishStatus, '');
setStatus(archiveStatus, '');
return state.loadToken;
}
function invalidateSelectionState() {
state.updatedAt = '';
state.version = null;
state.digest = '';
state.status = '';
state.latestPublishedVersion = null;
state.selectedLoaded = false;
state.publishedReady = false;
state.contentReady = false;
// Story 3.10: source/findings прежнего выбора не переживают смену выбора.
state.source = null;
state.sourceFindings = [];
renderResourceTest(null);
if (sourceFacts) {
sourceFacts.hidden = true;
}
if (draftParamsHost) {
clearHost(draftParamsHost);
}
if (sourceFindings) {
clearHost(sourceFindings);
}
if (lifecycleCard) {
lifecycleCard.hidden = true;
}
if (archivedHint) {
archivedHint.hidden = true;
}
setText(document.querySelector(STATUS), '');
renderFindings(null);
renderBind();
refreshActionButtons();
}
function isCurrentSelection(token, id) {
return token === state.loadToken && id === state.resourceId;
}
function resetTransientSections() {
state.bind = null;
clearHost(publishedHost);
if (bindAgent) {
bindAgent.value = '';
}
hideBindStale();
setText(bindAgentVersion, '');
setStatus(bindStatus, '');
refreshBindButton();
}
function hideBindStale() {
if (bindStale) {
bindStale.hidden = true;
bindStale.textContent = '';
}
if (bindReload) {
bindReload.hidden = true;
}
}
/// Пока текущий выбор не загружен, редактировать нельзя: иначе форма отправила бы
/// metadata прежнего Draft вместе с его precondition.
function setEditEnabled(enabled) {
if (!editForm) {
return;
}
Array.prototype.forEach.call(
editForm.querySelectorAll('input, select, textarea, button'),
function(control) {
control.disabled = !enabled;
},
);
}
/// E1: успешная публикация не включает редактор до прихода preview — иначе
/// textarea пуста и metadata-only правка отправила бы пустой content. Редактор
/// открывается только из coherent снимка текущего неархивного выбора.
function refreshEditor() {
setEditEnabled(state.contentReady && state.selectedLoaded && state.status !== 'archived');
}
/// Заменяемый файл никогда не переносится на другой Draft (F3): он выбирается заново
/// уже для текущего черновика.
function clearReplacementFile() {
var fileInput = byId('resource-edit-file');
if (fileInput) {
fileInput.value = '';
}
}
/// Прежний выбор не оставляет за собой доступного действия (R1, TL run113 BH2):
/// пока новый черновик не загружен и после отказа его загрузки ссылка скачивания
/// прежнего черновика недоступна. Восстановление происходит только в `applySnapshot`
/// на успешном снимке текущего выбора.
function clearDownload() {
if (downloadElement) {
downloadElement.removeAttribute('href');
downloadElement.hidden = true;
}
// Story 3.9: экспорт принадлежит загруженному выбору, прежний выбор его не оставляет.
if (exportLink) {
exportLink.removeAttribute('href');
exportLink.hidden = true;
}
setStatus(exportStatus, '');
}
function tKey(key, fallback) {
if (typeof t === 'function') {
var value = t(key);
if (value && value !== key) {
return value;
}
}
return fallback;
}
function setText(element, value) {
if (element) {
element.textContent = value == null ? '' : String(value);
}
}
function byId(id) {
return document.getElementById(id);
}
function setStatus(element, message) {
setText(element, message || '');
}
function clearHost(host) {
if (host) {
host.textContent = '';
}
}
function workspaceId() {
var workspace = window.getCurrentWorkspace ? window.getCurrentWorkspace() : null;
return workspace && workspace.id ? workspace.id : '';
}
function resourceIdFromUrl() {
return new URLSearchParams(window.location.search).get('resource_id') || '';
}
function apiPath(suffix) {
return '/api/admin/workspaces/' + encodeURIComponent(state.workspaceId) + '/resources' + suffix;
}
function agentsPath(suffix) {
return '/api/admin/workspaces/' + encodeURIComponent(state.workspaceId) + '/agents' + suffix;
}
function cachedCsrf() {
return window.CrankAuth && typeof window.CrankAuth.getCsrfToken === 'function'
? (window.CrankAuth.getCsrfToken() || '')
: '';
}
async function csrfToken() {
var token = cachedCsrf();
if (!token && window.CrankApi && typeof window.CrankApi.refreshSessionCsrf === 'function') {
var refreshed = await window.CrankApi.refreshSessionCsrf();
token = refreshed && refreshed.csrf_token ? refreshed.csrf_token : '';
}
return token || '';
}
async function readJson(responsePromise) {
var response = await responsePromise;
var text = await response.text();
var payload = null;
if (text) {
try {
payload = JSON.parse(text);
} catch (_error) {
payload = null;
}
}
return { status: response.status, text: text, payload: payload };
}
function errorMessage(payload, fallback) {
if (payload && payload.error && payload.error.message) {
return String(payload.error.message);
}
return fallback;
}
function errorCode(payload) {
return payload && payload.error && typeof payload.error.code === 'string'
? payload.error.code
: '';
}
/// Multipart без ожиданий: текст кодируется UTF-8, файл добавляется как Blob.
function draftRequest(method, url, metadata, content, mimeType, token) {
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }), 'metadata.json');
if (content && content.file) {
form.append('content', content.file, content.file.name || 'upload.bin');
} else if (content) {
form.append('content', new Blob([new TextEncoder().encode(content.text || '')], { type: mimeType || 'application/octet-stream' }), 'draft.txt');
}
var headers = { 'Accept': 'application/json' };
if (token) {
headers['X-CSRF-Token'] = token;
}
return fetch(url, {
method: method,
credentials: 'same-origin',
headers: headers,
body: form,
});
}
/// Отправка с гарантией: если CSRF не закеширован, он берётся и запрос уходит следом.
function sendDraft(method, url, metadata, content, mimeType) {
var token = cachedCsrf();
if (token) {
return readJson(draftRequest(method, url, metadata, content, mimeType, token));
}
return csrfToken().then(function(fresh) {
return readJson(draftRequest(method, url, metadata, content, mimeType, fresh));
});
}
/// JSON-мутация lifecycle с точным precondition; ответ читается тем же способом.
async function sendJson(method, url, body, extraHeaders) {
var token = await csrfToken();
var headers = { 'Accept': 'application/json', 'Content-Type': 'application/json' };
if (token) {
headers['X-CSRF-Token'] = token;
}
if (extraHeaders) {
Object.keys(extraHeaders).forEach(function(key) {
headers[key] = extraHeaders[key];
});
}
return readJson(fetch(url, {
method: method,
credentials: 'same-origin',
headers: headers,
body: body == null ? undefined : JSON.stringify(body),
}));
}
// -------------------------------------------------------------------------
// Список черновиков: выбор отражается в URL, поэтому reload восстанавливает
// тот же Draft.
// -------------------------------------------------------------------------
function renderList(items) {
if (!listElement) {
return;
}
listElement.textContent = '';
items.forEach(function(item) {
var row = document.createElement('li');
row.className = 'resource-list-item';
row.setAttribute('data-testid', 'resource-list-item');
row.setAttribute('data-resource-id', item.resource.resource_id || '');
if (item.resource.resource_id === state.resourceId) {
row.classList.add('selected');
}
var name = document.createElement('span');
name.className = 'resource-list-name';
name.textContent = item.resource.name || '';
var meta = document.createElement('span');
meta.className = 'resource-list-meta';
meta.textContent = [item.resource.kind, item.version.mime_type, item.version.size_bytes + ' B'].join(' · ');
row.appendChild(name);
row.appendChild(meta);
row.addEventListener('click', function() {
selectResource(item.resource.resource_id || '');
});
listElement.appendChild(row);
});
setStatus(
listStatus,
items.length === 0
? tKey('resources.list.empty', 'No drafts yet.')
: tKey('resources.list.hint', 'Select a draft to preview or edit it.'),
);
}
async function loadList() {
var response = await fetch(apiPath(''), { credentials: 'same-origin' });
if (!response.ok) {
setStatus(listStatus, tKey('resources.list.error', 'The drafts could not be loaded.'));
return;
}
var payload = await response.json();
renderList(Array.isArray(payload.items) ? payload.items : []);
}
function markSelected(id) {
Array.prototype.forEach.call(document.querySelectorAll('.resource-list-item'), function(row) {
row.classList.toggle('selected', row.getAttribute('data-resource-id') === id);
});
}
function selectResource(id) {
if (!id) {
return;
}
var url = new URL(window.location.href);
url.searchParams.set('resource_id', id);
window.history.replaceState(null, '', url.pathname + url.search);
var token = beginSelection(id);
markSelected(id);
setEditEnabled(false);
loadResource(id, token).catch(function() {
if (isCurrentSelection(token, id)) {
setStatus(statusElement, tKey('resources.error', 'The Resource could not be loaded.'));
}
});
}
// -------------------------------------------------------------------------
// Карточка и инертный предпросмотр выбранного Draft
// -------------------------------------------------------------------------
function showPreviewError(message) {
clearPreviewError();
var node = document.createElement('div');
node.className = 'resource-preview-error';
node.setAttribute('data-testid', 'resource-preview-error');
// Безопасный отказ: код/сообщение API, без байтов содержимого и без разметки.
node.textContent = message;
root.appendChild(node);
}
function clearPreviewError() {
var existing = document.querySelector(PREVIEW_ERROR);
if (existing) {
existing.remove();
}
}
/// Findings preview (AC01): только стабильные коды/поля, никогда bytes содержимого.
/// `findings === null` — снимок ещё не проверен (не утверждаем «нарушений нет»).
function renderFindings(findings) {
var list = document.querySelector(FINDINGS_LIST);
var empty = document.querySelector(FINDINGS_EMPTY);
if (!list || !empty) {
return;
}
list.textContent = '';
if (!Array.isArray(findings)) {
empty.textContent = '';
return;
}
var items = findings;
if (items.length === 0) {
empty.textContent = tKey('resources.findings.empty', 'No findings.');
return;
}
empty.textContent = '';
items.forEach(function(finding) {
var row = document.createElement('li');
row.className = 'resource-finding';
row.setAttribute('data-testid', 'resource-preview-finding');
var code = finding && finding.code ? String(finding.code) : 'finding';
var field = finding && finding.field ? String(finding.field) : '';
row.textContent = field ? field + ': ' + code : code;
list.appendChild(row);
});
}
/// Экран целиком строится из **одного** ответа API (F1): metadata, digest, size,
/// version, описание, precondition и текст относятся к одному снимку Draft.
/// `text` — ровно bytes этого снимка для text/json; `null` для binary (bytes не
/// загружаются вообще).
///
/// D1: снимок всегда применяется целиком (включая lifecycle/`latest_published_version`),
/// потому что CAS/metadata/статус в нём относятся к одной версии. Поздний ответ
/// прежнего поколения отсекается `loadToken`/`mutationToken` до вызова, поэтому
/// смешанных снимков не возникает.
function applySnapshot(snapshot, text) {
var resource = snapshot.resource || {};
var version = snapshot.version || {};
state.updatedAt = resource.updated_at || '';
state.version = Number(version.version);
state.digest = version.digest || '';
state.resourceId = resource.resource_id || state.resourceId;
state.selectedLoaded = true;
root.setAttribute('data-resource-id', state.resourceId);
setText(document.querySelector(META_URI), resource.uri);
setText(document.querySelector(META_NAME), resource.name);
setText(document.querySelector(META_KIND), resource.kind);
setText(document.querySelector(META_MIME), version.mime_type);
setText(document.querySelector(META_SIZE), version.size_bytes);
setText(document.querySelector(META_DIGEST), version.digest);
setText(document.querySelector(META_VERSION), version.version);
setText(document.querySelector(META_DESCRIPTION), resource.description);
setText(document.querySelector(META_SENSITIVITY), version.sensitivity);
// Инертный текст ровно этого снимка: для binary (text === null) он не показывается
// вообще, для text/json — те же bytes, что и metadata (P3/F1).
setText(document.querySelector(PREVIEW_TEXT), text == null ? '' : text);
setStatus(statusElement, resource.uri || '');
if (downloadElement) {
downloadElement.setAttribute('href', apiPath('/' + encodeURIComponent(state.resourceId) + '/content'));
downloadElement.hidden = false;
}
if (exportLink) {
exportLink.setAttribute('href', exportUrl(state.resourceId, null));
exportLink.hidden = false;
}
if (editForm) {
byId('resource-edit-description').value = resource.description || '';
byId('resource-edit-mime-type').value = version.mime_type || '';
byId('resource-edit-sensitivity').value = version.sensitivity || 'internal';
// Редактор показывает bytes текущего снимка, а не пустое поле и не текст
// предыдущего выбора (F3).
byId('resource-edit-content').value = text == null ? '' : text;
}
renderLifecycle(resource);
// Story 3.10: source-факты и server findings принадлежат тому же снимку.
renderCardSource(snapshot);
markSelected(state.resourceId);
return { resource: resource, version: version };
}
// -------------------------------------------------------------------------
// Lifecycle: Draft / exact Published Version / Archived
// -------------------------------------------------------------------------
function statusLabel(status) {
return tKey('resources.status.' + status, status);
}
function refreshActionButtons() {
// D1: действия lifecycle доступны только для успешно загруженного текущего выбора
// с его собственным CAS; недогруженный/чужой Resource не может унаследовать его.
var actionable = state.selectedLoaded && Boolean(state.updatedAt) && !actionBusy;
var archived = state.status === 'archived';
// Story 3.10: server-authoritative blocker findings держат publish выключенным.
var blockedSource = Boolean(state.source) && state.sourceFindings.length > 0;
if (publishButton) {
publishButton.disabled = !actionable || archived || blockedSource;
}
if (archiveButton) {
archiveButton.disabled = !actionable || archived;
}
}
function refreshBindButton() {
if (!bindSubmit) {
return;
}
var publishedShown = state.latestPublishedVersion != null && state.publishedReady;
bindSubmit.disabled =
bindBusy || !state.bind || !state.selectedLoaded || !publishedShown || state.status === 'archived';
}
function renderLifecycle(resource) {
var previousVersion = state.latestPublishedVersion;
state.status = resource.status || 'draft';
state.latestPublishedVersion = resource.latest_published_version == null
? null
: Number(resource.latest_published_version);
// Новый указатель версии делает прежний exact snapshot недействительным.
if (previousVersion !== state.latestPublishedVersion) {
state.publishedReady = false;
clearHost(publishedHost);
}
if (lifecycleCard) {
lifecycleCard.hidden = !state.resourceId;
}
setText(document.querySelector(STATUS), statusLabel(state.status));
if (archivedHint) {
archivedHint.hidden = state.status !== 'archived';
}
if (state.status === 'archived') {
setEditEnabled(false);
clearHost(confirmHost);
}
refreshActionButtons();
renderBind();
}
function renderBind() {
var available = state.latestPublishedVersion != null;
if (bindForm) {
bindForm.hidden = !available;
}
setText(bindVersion, available ? String(state.latestPublishedVersion) : '');
if (bindAgent) {
bindAgent.disabled = !available || state.status === 'archived';
}
refreshBindButton();
}
/// Точная Published Version читается отдельным запросом к точному integer-version.
async function loadPublished(id, resource, token) {
var version = resource.latest_published_version;
if (version == null) {
state.publishedReady = false;
clearHost(publishedHost);
refreshBindButton();
return;
}
state.publishedReady = false;
refreshBindButton();
var response;
try {
response = await fetch(
apiPath('/' + encodeURIComponent(id) + '/versions/' + encodeURIComponent(version)),
{ credentials: 'same-origin' },
);
} catch (_error) {
// Сетевая ошибка точного чтения — та же видимая безопасная ошибка, без retry.
if (isCurrentSelection(token, id) && state.latestPublishedVersion === Number(version)) {
clearHost(publishedHost);
showPublishedError();
}
return;
}
var result = await readJson(response);
// Поздний ответ прежнего указателя не должен ни перерисовать, ни очистить блок,
// если карточка уже ушла вперёд (например, публикация только что принята).
if (!isCurrentSelection(token, id) || state.latestPublishedVersion !== Number(version)) {
return;
}
if (!response.ok) {
// D1: отказ точного чтения — видимая безопасная ошибка, а не тихое исчезновение
// блока. Binding не отправляется по указателю, который не был прочитан.
clearHost(publishedHost);
showPublishedError();
return;
}
state.publishedReady = true;
renderPublished(result.payload);
refreshBindButton();
}
function showPublishedError() {
if (!publishedHost) {
return;
}
var node = document.createElement('div');
node.className = 'resource-published-error';
node.setAttribute('data-testid', 'resource-published-error');
node.setAttribute('role', 'alert');
// Только локализованное безопасное сообщение: ни payload, ни bytes версии.
node.textContent = tKey(
'resources.published.error',
'The exact Published Version could not be loaded. Reload and try again.',
);
publishedHost.appendChild(node);
}
function renderPublished(record) {
clearHost(publishedHost);
if (!record || !publishedHost || !templates.published) {
return;
}
var node = templates.published.content.firstElementChild.cloneNode(true);
setText(node.querySelector('[data-published-title]'), tKey('resources.published.title', 'Exact Published Version'));
var labels = {
version: 'resources.published.version',
mime: 'resources.published.mime',
size: 'resources.published.size',
sensitivity: 'resources.published.sensitivity',
digest: 'resources.published.digest',
};
Object.keys(labels).forEach(function(key) {
setText(node.querySelector('[data-published-label="' + key + '"]'), tKey(labels[key], key));
});
Array.prototype.forEach.call(node.querySelectorAll('[data-published-value]'), function(value) {
var field = value.getAttribute('data-published-value');
setText(value, record[field]);
});
var link = node.querySelector('[data-published-download]');
if (link) {
link.textContent = tKey('resources.published.download', 'Download published version');
link.setAttribute(
'href',
apiPath('/' + encodeURIComponent(state.resourceId) + '/versions/' + encodeURIComponent(record.version) + '/content'),
);
}
// Story 3.9: экспорт именно этой точной Published Version (не latest-alias).
var publishedExport = node.querySelector('[data-published-export]');
if (publishedExport) {
publishedExport.textContent = tKey('resources.export.published', 'Export this version');
publishedExport.setAttribute('href', exportUrl(state.resourceId, record.version));
publishedExport.addEventListener('click', function(event) {
event.preventDefault();
startExport(exportUrl(state.resourceId, record.version), state.resourceId, state.loadToken);
});
}
publishedHost.appendChild(node);
}
function showConfirm(kindKey, template) {
clearHost(confirmHost);
if (!template || !confirmHost) {
return null;
}
var node = template.content.firstElementChild.cloneNode(true);
setText(node.querySelector('[data-confirm-text]'), tKey(kindKey + '.confirm', ''));
setText(node.querySelector('[data-confirm-accept]'), tKey('resources.confirm.accept', 'Confirm'));
setText(node.querySelector('[data-confirm-cancel]'), tKey('resources.confirm.cancel', 'Cancel'));
confirmHost.appendChild(node);
return node;
}
function showStale() {
clearHost(staleHost);
if (!templates.stale || !staleHost) {
return;
}
var node = templates.stale.content.firstElementChild.cloneNode(true);
setText(node.querySelector('[data-stale-text]'), tKey('resources.stale.message', 'The Resource changed since it was loaded. Reload and try again.'));
var reload = node.querySelector('[data-stale-reload]');
setText(reload, tKey('resources.stale.reload', 'Reload'));
reload.addEventListener('click', function() {
clearHost(staleHost);
reloadSelection();
});
staleHost.appendChild(node);
}
function reloadSelection() {
var id = state.resourceId;
if (!id) {
return;
}
var token = beginSelection(id);
markSelected(id);
setEditEnabled(false);
loadResource(id, token).catch(function() {
if (isCurrentSelection(token, id)) {
setStatus(statusElement, tKey('resources.error', 'The Resource could not be loaded.'));
}
});
}
function publishFailureMessage(result) {
var code = errorCode(result.payload);
if (code === 'resource_secret_findings') {
return tKey('resources.publish.secret', 'Publication refused: the content contains secret material or an access-bypassing reference.');
}
if (code === 'resource_stale') {
return tKey('resources.publish.stale', 'The Resource changed since it was loaded. Reload and try again.');
}
return errorMessage(result.payload, tKey('resources.publish.error', 'The Resource could not be published.'));
}
async function runPublish() {
var resourceId = state.resourceId;
var token = state.loadToken;
var expected = state.updatedAt;
// D1: мутация отправляется только для успешно загруженного текущего выбора с его CAS.
if (!resourceId || !state.selectedLoaded || !expected || state.status === 'archived') {
return;
}
clearHost(confirmHost);
setStatus(publishStatus, tKey('resources.publish.pending', 'Publishing…'));
actionBusy = true;
refreshActionButtons();
try {
var result = await sendJson('POST', apiPath('/' + encodeURIComponent(resourceId) + '/publish'), {
expected_updated_at: expected,
});
if (!isCurrentSelection(token, resourceId)) {
return;
}
if (result.status === 200 && result.payload) {
// Ответ публикации: { resource: <ResourceCardResponse>, published_version }.
var card = result.payload.resource || {};
var resource = card.resource || {};
state.updatedAt = resource.updated_at || state.updatedAt;
state.mutationToken += 1;
clearHost(staleHost);
renderLifecycle(resource);
state.publishedReady = true;
renderPublished(result.payload.published_version);
refreshBindButton();
setStatus(publishStatus, tKey('resources.publish.done', 'The Resource was published.'));
refreshEditor();
loadList();
return;
}
if (result.status === 428) {
// Stale precondition: отдельное видимое состояние с reload, а не общая ошибка.
setStatus(publishStatus, '');
showStale();
return;
}
setStatus(publishStatus, publishFailureMessage(result));
} catch (_error) {
if (isCurrentSelection(token, resourceId)) {
setStatus(publishStatus, tKey('resources.publish.error', 'The Resource could not be published.'));
}
} finally {
actionBusy = false;
refreshActionButtons();
}
}
async function runArchive() {
var resourceId = state.resourceId;
var token = state.loadToken;
var expected = state.updatedAt;
if (!resourceId || !state.selectedLoaded || !expected || state.status === 'archived') {
return;
}
clearHost(confirmHost);
setStatus(archiveStatus, tKey('resources.archive.pending', 'Archiving…'));
actionBusy = true;
refreshActionButtons();
try {
var result = await sendJson('POST', apiPath('/' + encodeURIComponent(resourceId) + '/archive'), {
expected_updated_at: expected,
});
if (!isCurrentSelection(token, resourceId)) {
return;
}
if (result.status === 200 && result.payload) {
var resource = result.payload.resource || {};
state.updatedAt = resource.updated_at || state.updatedAt;
state.mutationToken += 1;
clearHost(staleHost);
renderLifecycle(resource);
setStatus(archiveStatus, tKey('resources.archive.done', 'The Resource was archived.'));
setEditEnabled(false);
loadList();
return;
}
if (result.status === 428) {
setStatus(archiveStatus, '');
showStale();
return;
}
setStatus(archiveStatus, errorMessage(result.payload, tKey('resources.archive.error', 'The Resource could not be archived.')));
} catch (_error) {
if (isCurrentSelection(token, resourceId)) {
setStatus(archiveStatus, tKey('resources.archive.error', 'The Resource could not be archived.'));
}
} finally {
actionBusy = false;
refreshActionButtons();
}
}
// -------------------------------------------------------------------------
// Binding: exact Published Version к существующему Agent API
// -------------------------------------------------------------------------
function renderAgentOptions() {
if (!bindAgent) {
return;
}
var agents = Array.isArray(state.agents) ? state.agents : [];
bindAgent.textContent = '';
var placeholder = document.createElement('option');
placeholder.value = '';
placeholder.textContent = agents.length === 0
? tKey('resources.bind.empty', 'No Agents in this workspace yet.')
: tKey('resources.bind.select', 'Select an Agent first.');
bindAgent.appendChild(placeholder);
agents.forEach(function(agent) {
var option = document.createElement('option');
option.value = agent.id || agent.agent_id || '';
option.textContent = agent.display_name || agent.slug || option.value;
bindAgent.appendChild(option);
});
}
async function loadAgents() {
if (state.agents) {
renderAgentOptions();
return;
}
var response = await fetch(agentsPath(''), { credentials: 'same-origin' });
if (!response.ok) {
return;
}
var payload = await response.json();
state.agents = Array.isArray(payload && payload.items) ? payload.items : [];
renderAgentOptions();
}
/// Фиксирует состояние выбранного Agent: ETag (If-Match), draft-версию и полный
/// набор существующих Operation bindings / policy / Resource bindings. Отправка
/// использует именно этот снимок, поэтому stale-revision не обходится refetch-ом.
async function loadAgentState(agentId) {
var token = state.loadToken;
var base = agentsPath('/' + encodeURIComponent(agentId));
var detail = await fetch(base, { credentials: 'same-origin' });
if (!detail.ok) {
throw new Error('agent detail unavailable');
}
var etag = detail.headers.get('etag') || '';
var summary = await detail.json();
var version = summary.current_draft_version;
var versionResponse = await fetch(base + '/versions/' + encodeURIComponent(version), {
credentials: 'same-origin',
});
if (!versionResponse.ok) {
throw new Error('agent version unavailable');
}
var snapshot = await versionResponse.json();
if (!isCurrentSelection(token, state.resourceId) || !bindAgent || bindAgent.value !== agentId) {
return;
}
state.bind = {
agentId: agentId,
etag: etag,
version: version,
bindings: Array.isArray(snapshot.bindings) ? snapshot.bindings : [],
tool_selection_policy: (snapshot.snapshot && snapshot.snapshot.tool_selection_policy) || {},
resource_bindings: Array.isArray(snapshot.resource_bindings) ? snapshot.resource_bindings : [],
};
setText(bindAgentVersion, version);
refreshBindButton();
}
/// Обновление зафиксированного снимка Agent по явному действию пользователя.
/// Silent refetch перед отправкой запрещён: stale-guard не обходится.
function reloadBindAgent() {
var agentId = bindAgent ? bindAgent.value : '';
if (!agentId) {
return;
}
hideBindStale();
state.bind = null;
setText(bindAgentVersion, '');
setStatus(bindStatus, '');
refreshBindButton();
loadAgentState(agentId).catch(function() {
setStatus(bindStatus, tKey('resources.bind.error', 'The Resource could not be bound.'));
});
}
async function runBind() {
var resourceId = state.resourceId;
var token = state.loadToken;
var bind = state.bind;
var version = state.latestPublishedVersion;
if (!bind) {
setStatus(bindStatus, tKey('resources.bind.select', 'Select an Agent first.'));
return;
}
if (version == null || state.status === 'archived' || !state.selectedLoaded || !state.publishedReady) {
return;
}
hideBindStale();
setStatus(bindStatus, tKey('resources.bind.pending', 'Binding…'));
bindBusy = true;
refreshBindButton();
// Сохраняем существующие Operation bindings/policy/Resource bindings; заменяем
// только запись этого Resource и добавляем точную опубликованную версию.
var resourceBindings = bind.resource_bindings.filter(function(item) {
return item && item.resource_id !== resourceId;
});
resourceBindings.push({ resource_id: resourceId, resource_version: version });
try {
var result = await sendJson(
'POST',
agentsPath('/' + encodeURIComponent(bind.agentId) + '/bindings'),
{
bindings: bind.bindings,
tool_selection_policy: bind.tool_selection_policy,
resource_bindings: resourceBindings,
},
bind.etag ? { 'If-Match': bind.etag } : null,
);
// D4: поздний ответ не относится к текущему выбору Resource или Agent — его
// статус не должен появиться в форме другого Agent.
if (
!isCurrentSelection(token, resourceId) ||
!state.bind ||
state.bind.agentId !== bind.agentId ||
!bindAgent ||
bindAgent.value !== bind.agentId
) {
return;
}
if (result.status === 200) {
setStatus(bindStatus, tKey('resources.bind.done', 'The binding was saved.'));
// Снимок Agent устарел после успешной записи: обновляем его (но не перед send).
loadAgentState(bind.agentId).catch(function() {});
return;
}
var code = errorCode(result.payload);
// Stale Agent revision отличается от lifecycle/validation отказа стабильным кодом.
if (code === 'agent_stale_revision' || (result.status === 428 && code === 'agent_precondition_required')) {
setStatus(bindStatus, '');
state.bind = null;
if (bindStale) {
setText(bindStale, tKey('resources.bind.stale', 'The Agent revision changed: reload the form and bind again.'));
bindStale.hidden = false;
}
if (bindReload) {
bindReload.hidden = false;
}
refreshBindButton();
return;
}
setStatus(bindStatus, errorMessage(result.payload, tKey('resources.bind.error', 'The Resource could not be bound.')));
} catch (_error) {
if (isCurrentSelection(token, resourceId)) {
setStatus(bindStatus, tKey('resources.bind.error', 'The Resource could not be bound.'));
}
} finally {
bindBusy = false;
refreshBindButton();
}
}
/// Предпросмотр: тот же снимок, что и metadata, либо видимый безопасный отказ.
/// Findings запрашиваются и для binary (bytes в ответ не приходят, `text: null`).
async function loadPreview(id, kind, token) {
var mutationToken = state.mutationToken;
var response;
try {
response = await fetch(apiPath('/' + encodeURIComponent(id) + '/preview'), {
credentials: 'same-origin',
});
} catch (_error) {
if (isCurrentSelection(token, id)) {
if (kind === 'text' || kind === 'json') {
setText(document.querySelector(PREVIEW_TEXT), '');
}
showPreviewError(tKey('resources.preview.error', 'The preview could not be shown.'));
}
return;
}
var result = await readJson(response);
if (!isCurrentSelection(token, id)) {
return;
}
if (!response.ok) {
if (kind === 'text' || kind === 'json') {
setText(document.querySelector(PREVIEW_TEXT), '');
}
showPreviewError(errorMessage(result.payload, tKey('resources.preview.error', 'The preview could not be shown.')));
return;
}
var payload = result.payload || {};
var text = payload.preview ? payload.preview.text : null;
var shownText = kind === 'text' || kind === 'json' ? text : null;
// D1: ответ, выданный до принятой мутации (publish/archive/edit), не применяется:
// metadata/CAS/lifecycle уже принадлежат новому состоянию. Такой ответ
// перезапрашивается заново, чтобы экран остался одним coherent снимком.
if (mutationToken !== state.mutationToken) {
loadPreview(id, kind, token).catch(function() {});
return;
}
clearPreviewError();
// Текст и metadata берутся из одного и того же ответа предпросмотра (P3/F1);
// lifecycle/CAS применяются вместе с ними, поэтому экран не смешивает снимки.
applySnapshot(payload, shownText);
renderFindings(payload.findings);
// E1: редактор открывается только здесь — на coherent снимке текущего выбора
// (включая повторный preview после принятой мутации).
state.contentReady = true;
refreshEditor();
}
async function loadResource(id, token) {
state.contentReady = false;
setEditEnabled(false);
clearPreviewError();
setText(document.querySelector(PREVIEW_TEXT), '');
// Заменяемый файл относится к прежнему выбору и никогда не переносится (F3).
clearReplacementFile();
// Findings относятся к снимку: до ответа preview «нарушений нет» не утверждаем.
renderFindings(null);
// Пока карточка нового выбора не применена, действие скачивания прежнего выбора
// недоступно (R1).
clearDownload();
var response = await fetch(apiPath('/' + encodeURIComponent(id)), { credentials: 'same-origin' });
var result = await readJson(response);
if (!isCurrentSelection(token, id)) {
return;
}
if (!response.ok) {
// Отказ загрузки тоже не оставляет доступной ссылку прежнего выбора (R1).
clearDownload();
state.selectedLoaded = false;
state.updatedAt = '';
refreshActionButtons();
refreshBindButton();
setStatus(statusElement, errorMessage(result.payload, tKey('resources.error', 'The Resource could not be loaded.')));
return;
}
var card = applySnapshot(result.payload || {}, null);
if (!isCurrentSelection(token, id)) {
return;
}
await loadPublished(id, card.resource, token);
if (!isCurrentSelection(token, id)) {
return;
}
await loadPreview(id, card.resource.kind, token);
if (!isCurrentSelection(token, id)) {
return;
}
// Форма редактирования становится доступной только после загрузки текущего выбора
// и не открывается для архивного Resource.
refreshEditor();
}
// -------------------------------------------------------------------------
// Story 3.9: перенос Resource — экспорт envelope и импорт нового Draft
// -------------------------------------------------------------------------
function exportUrl(resourceId, version) {
if (version == null) {
return apiPath('/' + encodeURIComponent(resourceId) + '/export');
}
return apiPath(
'/' + encodeURIComponent(resourceId) + '/versions/' + encodeURIComponent(version) + '/export',
);
}
function filenameFromDisposition(value) {
var match = /filename="([^"]+)"/.exec(value || '');
return match && match[1] ? match[1] : '';
}
/// Скачивание начинается только из принятого ответа текущего выбора: поздний ответ
/// прежнего Resource не запускает download (stale-response state).
function downloadEnvelopeFile(text, filename) {
var blob = new Blob([text], { type: 'application/json' });
var url = URL.createObjectURL(blob);
var anchor = document.createElement('a');
anchor.href = url;
anchor.download = filename;
anchor.rel = 'noopener';
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(function() {
URL.revokeObjectURL(url);
}, 1000);
}
async function startExport(url, resourceId, token) {
if (!url || !resourceId) {
return;
}
clearPortabilityStale();
setStatus(exportStatus, tKey('resources.export.pending', 'Preparing the export…'));
var response;
try {
response = await fetch(url, {
credentials: 'same-origin',
headers: { 'Accept': 'application/json' },
});
} catch (_error) {
if (isCurrentSelection(token, resourceId)) {
setStatus(exportStatus, tKey('resources.export.error', 'The Resource could not be exported.'));
}
return;
}
var text = await response.text();
// Ответ прежнего выбора не открывает скачивание и не подменяет текущий Resource.
if (!isCurrentSelection(token, resourceId)) {
setStatus(exportStatus, '');
showPortabilityStale();
return;
}
if (!response.ok) {
setStatus(exportStatus, tKey('resources.export.error', 'The Resource could not be exported.'));
return;
}
setStatus(exportStatus, '');
downloadEnvelopeFile(
text,
filenameFromDisposition(response.headers.get('content-disposition')) ||
resourceId + '.crank-resource.json',
);
}
function clearPortabilityStale() {
clearHost(portabilityStaleHost);
}
function showPortabilityStale() {
clearPortabilityStale();
if (!portabilityStaleHost) {
return;
}
var node = document.createElement('div');
node.className = 'resource-stale';
node.setAttribute('data-testid', 'resource-portability-stale');
node.setAttribute('role', 'alert');
// Ответ прежнего выбора не применён: скачивание не началось, новый выбор не затронут.
node.textContent = tKey(
'resources.portability.stale',
'The previous selection changed: this portability response was not applied.',
);
portabilityStaleHost.appendChild(node);
}
function clearPortabilityTransient() {
clearHost(importConfirmHost);
clearPortabilityStale();
setStatus(importStatus, '');
clearImportError();
}
function showImportError(message) {
if (!importError) {
return;
}
importError.textContent = message;
importError.hidden = false;
}
function clearImportError() {
if (importError) {
importError.textContent = '';
importError.hidden = true;
}
}
function hasExactKeys(value, keys) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return false;
}
var actual = Object.keys(value).sort();
var expected = keys.slice().sort();
return (
actual.length === expected.length &&
actual.every(function(key, index) {
return key === expected[index];
})
);
}
/// Целое число в границах серверного контракта: `Number.isSafeInteger` отсекает дроби,
/// NaN/Infinity и непредставимые значения; верхние границы — `u32` для `source.version`
/// и `i64` (безопасный диапазон JS) для `content.size_bytes`.
function isBoundedInteger(value, min, max) {
return Number.isSafeInteger(value) && value >= min && value <= max;
}
/// Структурная проверка переносимого файла до подтверждения: те же поля, что
/// принимает сервер. Содержимое не оценивается здесь — integrity/размер проверяет API.
function parseImportEnvelope(text) {
var value;
try {
value = JSON.parse(text);
} catch (_error) {
return null;
}
if (!hasExactKeys(value, ['format', 'version', 'resource', 'source', 'content'])) {
return null;
}
if (value.format !== 'crank-resource-portability' || value.version !== 1) {
return null;
}
if (
!hasExactKeys(value.resource, ['uri', 'name', 'description', 'kind', 'mime_type', 'sensitivity']) ||
!['uri', 'name', 'description', 'kind', 'mime_type', 'sensitivity'].every(function(field) {
return typeof value.resource[field] === 'string';
})
) {
return null;
}
if (!hasExactKeys(value.source, ['kind', 'version'])) {
return null;
}
if (value.source.kind !== 'draft' && value.source.kind !== 'published') {
return null;
}
if (!isBoundedInteger(value.source.version, 1, 4294967295)) {
return null;
}
if (!hasExactKeys(value.content, ['size_bytes', 'digest', 'base64'])) {
return null;
}
if (
!isBoundedInteger(value.content.size_bytes, 0, Number.MAX_SAFE_INTEGER) ||
typeof value.content.digest !== 'string' ||
!/^[0-9a-f]{64}$/.test(value.content.digest) ||
typeof value.content.base64 !== 'string'
) {
return null;
}
return value;
}
/// Подтверждение с metadata и явным «новый Draft, публикации не будет»; до accept
/// ничего не создаётся.
function showImportConfirm(envelope) {
clearHost(importConfirmHost);
if (!templates.importConfirm || !importConfirmHost) {
return null;
}
var node = templates.importConfirm.content.firstElementChild.cloneNode(true);
var resource = envelope.resource;
setText(
node.querySelector('[data-confirm-text]'),
[
resource.name,
resource.uri,
resource.kind,
resource.mime_type,
envelope.content.size_bytes + ' B',
tKey(
'resources.import.confirm.draft',
'A new Draft will be created in this workspace; nothing will be published.',
),
].join(' · '),
);
setText(
node.querySelector('[data-confirm-accept]'),
tKey('resources.import.confirm.accept', 'Create the Draft'),
);
setText(node.querySelector('[data-confirm-cancel]'), tKey('resources.confirm.cancel', 'Cancel'));
importConfirmHost.appendChild(node);
return node;
}
/// Безопасные локализованные сообщения: код/status API, без bytes, digest и путей.
function importFailureMessage(result) {
var code = errorCode(result.payload);
if (result.status === 413 || code === 'resource_content_too_large') {
return tKey(
'resources.import.error.too_large',
'The content is too large for this Resource: it exceeds the size limit.',
);
}
if (code === 'resource_artifact_integrity') {
return tKey(
'resources.import.error.integrity',
'The file is damaged: its declared size or checksum does not match the content.',
);
}
if (code === 'resource_uri_duplicate') {
return tKey(
'resources.import.error.uri_duplicate',
'This workspace already has a Resource with the same URI.',
);
}
if (code === 'resource_name_duplicate') {
return tKey(
'resources.import.error.name_duplicate',
'This workspace already has a Resource with the same name.',
);
}
if (result.status === 400) {
return tKey(
'resources.import.error.invalid',
'The file is not a valid Crank Resource portability file.',
);
}
return tKey('resources.import.error.generic', 'The Resource could not be imported.');
}
async function runImport(envelope) {
var resourceId = state.resourceId;
var token = state.loadToken;
clearHost(importConfirmHost);
clearImportError();
// Loading state перенесён на кнопку: `resource-import-status` показывает только
// принятый результат, поэтому «в процессе» нельзя спутать с успехом.
setStatus(importStatus, '');
setImportBusy(true);
try {
var result = await sendJson('POST', apiPath('/import'), envelope);
// Список отражает серверную правду независимо от смены выбора.
loadList().catch(function() {});
// Поздний ответ импорта не приписывается другому Resource/контексту.
if (!isCurrentSelection(token, resourceId)) {
showPortabilityStale();
return;
}
if (result.status === 201 && result.payload) {
setStatus(
importStatus,
tKey('resources.import.done', 'The import created a new Draft.'),
);
if (importFile) {
importFile.value = '';
}
return;
}
showImportError(importFailureMessage(result));
} catch (_error) {
if (isCurrentSelection(token, resourceId)) {
showImportError(tKey('resources.import.error.generic', 'The Resource could not be imported.'));
}
} finally {
setImportBusy(false);
}
}
function setImportBusy(busy) {
if (!importSubmit) {
return;
}
importSubmit.disabled = busy;
importSubmit.setAttribute('aria-busy', busy ? 'true' : 'false');
importSubmit.textContent = busy
? tKey('resources.import.pending', 'Importing…')
: tKey('resources.import.submit', 'Import');
}
if (exportLink) {
exportLink.addEventListener('click', function(event) {
event.preventDefault();
startExport(exportLink.getAttribute('href'), state.resourceId, state.loadToken);
});
}
if (importSubmit) {
importSubmit.addEventListener('click', function() {
clearImportError();
setStatus(importStatus, '');
clearHost(importConfirmHost);
var file = importFile && importFile.files && importFile.files[0];
if (!file) {
showImportError(tKey('resources.import.select', 'Choose a portability file first.'));
return;
}
setStatus(importStatus, tKey('resources.import.reading', 'Reading the file…'));
file
.text()
.then(function(text) {
var envelope = parseImportEnvelope(text);
if (!envelope) {
setStatus(importStatus, '');
showImportError(
tKey(
'resources.import.error.invalid',
'The file is not a valid Crank Resource portability file.',
),
);
return;
}
setStatus(importStatus, '');
var confirmation = showImportConfirm(envelope);
if (!confirmation) {
return;
}
confirmation.querySelector('[data-confirm-accept]').addEventListener('click', function() {
runImport(envelope);
});
confirmation.querySelector('[data-confirm-cancel]').addEventListener('click', function() {
clearHost(importConfirmHost);
});
})
.catch(function() {
setStatus(importStatus, '');
showImportError(
tKey(
'resources.import.error.invalid',
'The file is not a valid Crank Resource portability file.',
),
);
});
});
}
// -------------------------------------------------------------------------
// Story 3.10: REST-backed Resource template — выбор опубликованной версии,
// mapping параметров, server findings, создание и публикация черновика.
// -------------------------------------------------------------------------
function operationsPath() {
return '/api/admin/workspaces/' + encodeURIComponent(state.workspaceId) + '/operations';
}
function sourceFindingMessage(code) {
return tKey('resources.source.finding.' + code, tKey('resources.source.finding.generic', ''));
}
function parameterFinding(findings, field) {
return (findings || []).some(function(finding) {
return finding && finding.field === field && String(finding.code || '').indexOf('resource_source_parameter_') === 0;
});
}
function renderSourceFindings(host, findings) {
if (!host) {
return;
}
clearHost(host);
(findings || []).forEach(function(finding) {
var item = document.createElement('li');
item.setAttribute('data-testid', 'resource-source-finding');
// Только стабильный код -> локализованный текст; raw code не попадает в прозу.
item.textContent = sourceFindingMessage(finding.code) || tKey('resources.source.finding.generic', '');
host.appendChild(item);
});
}
function resolvePinnedInputField(fields, inputPath) {
var parts = inputPath.split('.');
if (parts.shift() !== 'input' || !parts.length) return null;
var current = { fields: fields };
for (var i = 0; i < parts.length; i += 1) {
current = current && current.fields && current.fields[parts[i]];
}
return current || null;
}
function mergeMappedSchema(previous, pinned) {
var schema = Object.assign({}, previous || {});
['type', 'format', 'enum_values'].forEach(function(key) {
if (Object.prototype.hasOwnProperty.call(pinned, key)) schema[key] = pinned[key];
else delete schema[key];
});
return schema;
}
function renderParamRows(host, parameters, findings) {
if (!host) {
return;
}
var active = document.activeElement;
var restoreFocus = active && host.contains(active) && active.getAttribute('data-testid') === 'resource-param-input-path'
? {
name: active.getAttribute('data-param-name'),
start: active.selectionStart,
end: active.selectionEnd,
direction: active.selectionDirection,
}
: null;
clearHost(host);
(parameters || []).forEach(function(parameter) {
var schema = parameter.schema || {};
var row = document.createElement('div');
row.className = 'resource-param-row';
row.setAttribute('data-testid', 'resource-param-row');
var name = document.createElement('span');
name.setAttribute('data-testid', 'resource-param-name');
name.textContent = parameter.name || '';
row.appendChild(name);
var type = document.createElement('span');
type.setAttribute('data-testid', 'resource-param-type');
type.textContent = String(schema.type || '');
row.appendChild(type);
var required = document.createElement('span');
required.setAttribute('data-testid', 'resource-param-required');
required.textContent = schema.required === true
? tKey('resources.source.required', 'required')
: tKey('resources.source.optional', 'optional');
row.appendChild(required);
var defaultValue = document.createElement('span');
defaultValue.setAttribute('data-testid', 'resource-param-default');
defaultValue.textContent = schema.default_value == null ? '' : String(schema.default_value);
row.appendChild(defaultValue);
var enumValues = document.createElement('span');
enumValues.setAttribute('data-testid', 'resource-param-enum');
enumValues.textContent = Array.isArray(schema.enum_values) ? schema.enum_values.join(', ') : '';
row.appendChild(enumValues);
var format = document.createElement('span');
format.setAttribute('data-testid', 'resource-param-format');
format.textContent = String(schema.format || '');
row.appendChild(format);
var inputPath = document.createElement('input');
inputPath.type = 'text';
inputPath.setAttribute('data-testid', 'resource-param-input-path');
inputPath.value = parameter.input_path || '';
inputPath.setAttribute('data-param-name', parameter.name || '');
inputPath.setAttribute('aria-label', (parameter.name || '') + ' input path');
inputPath.addEventListener('input', function() {
parameter.input_path = inputPath.value.trim();
if (state.binding && state.binding.parameters.indexOf(parameter) !== -1) {
state.binding.parameters = state.binding.parameters.map(function(item) {
return item.name === parameter.name ? parameter : item;
});
var binding = state.binding;
var bindingFields = getPinnedInputFields(binding.operation_id, binding.operation_version);
if (bindingFields) {
var boundField = resolvePinnedInputField(bindingFields, parameter.input_path);
if (boundField) parameter.schema = mergeMappedSchema(parameter.schema, boundField);
renderParamRows(sourceParamsHost, binding.parameters, []);
}
}
if (host === draftParamsHost && state.source && state.source.parameters) {
var sourceAtEdit = state.source;
var pathAtEdit = parameter.input_path;
function applyMappedField(fields) {
if (state.source !== sourceAtEdit || parameter.input_path !== pathAtEdit) return;
var pinned = resolvePinnedInputField(fields, pathAtEdit);
if (!pinned) return;
state.source.parameters = state.source.parameters.map(function(item) {
return item.name === parameter.name
? Object.assign({}, item, { input_path: pathAtEdit, schema: mergeMappedSchema(item.schema, pinned) })
: item;
});
renderCardSource({ source: state.source, findings: state.sourceFindings });
}
var pinnedFields = getPinnedInputFields(sourceAtEdit.operation_id, sourceAtEdit.operation_version);
if (pinnedFields) applyMappedField(pinnedFields);
else fetch(operationsPath() + '/' + encodeURIComponent(sourceAtEdit.operation_id) + '/versions/' + encodeURIComponent(sourceAtEdit.operation_version), { credentials: 'same-origin' })
.then(readJson).then(function(result) {
if (result.status === 200) applyMappedField((((result.payload || {}).snapshot || {}).input_schema || {}).fields || {});
}).catch(function() {});
}
});
row.appendChild(inputPath);
if (parameterFinding(findings, 'source.parameters')) {
var error = document.createElement('span');
error.className = 'resource-param-error';
error.setAttribute('data-testid', 'resource-param-error');
error.textContent = tKey(
'resources.source.finding.resource_source_parameter_unmapped',
'This parameter does not match the pinned operation input.',
);
row.appendChild(error);
}
host.appendChild(row);
});
if (restoreFocus) {
var inputs = host.querySelectorAll('[data-testid="resource-param-input-path"]');
for (var i = 0; i < inputs.length; i += 1) {
if (inputs[i].getAttribute('data-param-name') === restoreFocus.name) {
inputs[i].focus();
if (restoreFocus.start != null && restoreFocus.end != null) {
inputs[i].setSelectionRange(restoreFocus.start, restoreFocus.end, restoreFocus.direction || 'none');
}
break;
}
}
}
}
function pinnedInputKey(operationId, version) {
return String(operationId) + '@' + String(version);
}
function getPinnedInputFields(operationId, version) {
return state.pinnedInputFields[pinnedInputKey(operationId, version)] || null;
}
function renderCardSource(snapshot) {
var source = snapshot && snapshot.source ? snapshot.source : null;
var findings = snapshot && snapshot.findings ? snapshot.findings : [];
state.source = source;
state.sourceFindings = findings;
renderResourceTest(source && findings.length === 0 ? source : null);
if (source && source.operation_id && source.operation_version != null) {
var sourceAtRender = source;
var resourceAtRender = state.resourceId;
var sourceKey = pinnedInputKey(source.operation_id, source.operation_version);
fetch(operationsPath() + '/' + encodeURIComponent(source.operation_id) + '/versions/' + encodeURIComponent(source.operation_version), { credentials: 'same-origin' })
.then(readJson).then(function(result) {
if (state.source !== sourceAtRender || state.resourceId !== resourceAtRender || result.status !== 200) return;
state.pinnedInputFields[sourceKey] = ((result.payload || {}).snapshot || {}).input_schema
? (((result.payload || {}).snapshot.input_schema.fields) || {}) : {};
}).catch(function() {});
}
if (sourceFacts) {
sourceFacts.hidden = !source;
}
if (!source) {
if (draftParamsHost) {
clearHost(draftParamsHost);
}
if (sourceFindings) {
clearHost(sourceFindings);
}
refreshActionButtons();
return;
}
setText(sourcePinned, String(source.operation_id || '') + ' · v' + String(source.operation_version || ''));
var safety = source.read_safety || {};
var readSafe = safety.read_safe === true;
setText(
sourceSafety,
String(safety.method || '') + ' · ' + (readSafe
? tKey('resources.source.read_safe', 'read-safe')
: tKey('resources.source.not_read_safe', 'not read-safe')),
);
setText(sourceSensitivity, snapshot.version && snapshot.version.sensitivity ? snapshot.version.sensitivity : '');
var access = source.access || {};
setText(
sourceAccess,
String(access.security_level || '') + (access.auth_profile_ref ? ' · ' + access.auth_profile_ref : ''),
);
renderParamRows(draftParamsHost, source.parameters || [], findings);
renderSourceFindings(sourceFindings, findings);
refreshActionButtons();
}
function renderResourceTest(source) {
var card = byId('resource-test-card');
var host = byId('resource-test-parameters');
var start = byId('resource-test-start');
if (!card || !host) return;
clearHost(host);
card.hidden = !source;
if (!source) return;
var sensitivity = document.querySelector(META_SENSITIVITY);
setText(byId('resource-test-pinned'), source.operation_id + ' · v' + source.operation_version +
' · ' + tKey('resources.meta.sensitivity', 'Sensitivity') + ': ' + (sensitivity ? sensitivity.textContent : '') +
' · ' + String((source.access || {}).security_level || '') +
((source.access || {}).auth_profile_ref ? ' · ' + source.access.auth_profile_ref : ''));
(source.parameters || []).forEach(function(parameter) {
var label = document.createElement('label');
label.className = 'resource-field';
var title = document.createElement('span');
title.textContent = parameter.name + (parameter.schema && parameter.schema.required ? ' *' : '');
var input = document.createElement('input');
input.setAttribute('data-testid', 'resource-test-parameter');
input.setAttribute('data-name', parameter.name);
input.setAttribute('data-type', parameter.schema && parameter.schema.type || 'string');
input.value = parameter.schema && parameter.schema.default_value != null ? String(parameter.schema.default_value) : '';
input.required = Boolean(parameter.schema && parameter.schema.required);
label.appendChild(title);
label.appendChild(input);
host.appendChild(label);
});
start.disabled = !state.selectedLoaded || !state.version || !state.digest;
clearHost(byId('resource-test-output'));
setStatus(byId('resource-test-status'), '');
byId('resource-test-confirm').hidden = true;
}
function collectResourceTestParameters() {
var values = {};
var inputs = byId('resource-test-parameters').querySelectorAll('[data-testid="resource-test-parameter"]');
for (var i = 0; i < inputs.length; i += 1) {
var input = inputs[i];
if (input.required && !input.value.trim()) return null;
if (!input.value.trim()) continue;
var value = input.value;
if (input.getAttribute('data-type') === 'integer') {
value = Number(value);
if (!Number.isSafeInteger(value)) return null;
} else if (input.getAttribute('data-type') === 'number') {
value = Number(value);
if (!Number.isFinite(value)) return null;
} else if (input.getAttribute('data-type') === 'boolean') {
if (value !== 'true' && value !== 'false') return null;
value = value === 'true';
}
values[input.getAttribute('data-name')] = value;
}
return values;
}
async function runResourceTest() {
var resourceId = state.resourceId;
var token = state.loadToken;
var testToken = ++resourceTestToken;
var identity = { version: state.version, digest: state.digest, updated_at: state.updatedAt };
var parameters = collectResourceTestParameters();
byId('resource-test-confirm').hidden = true;
if (!parameters) {
setStatus(byId('resource-test-status'), tKey('resources.test.error', 'Invalid parameters.'));
return;
}
setStatus(byId('resource-test-status'), tKey('resources.test.loading', 'Reading from the pinned operation…'));
var response;
try {
response = await sendJson('POST', apiPath('/' + encodeURIComponent(resourceId) + '/test-runs'),
Object.assign({}, identity, { parameters: parameters }));
} catch (_error) {
if (testToken === resourceTestToken && isCurrentSelection(token, resourceId)) setStatus(byId('resource-test-status'), tKey('resources.test.error', 'The test read failed safely.'));
return;
}
if (testToken !== resourceTestToken) return;
if (!isCurrentSelection(token, resourceId) || identity.version !== state.version || identity.digest !== state.digest || identity.updated_at !== state.updatedAt || JSON.stringify(parameters) !== JSON.stringify(collectResourceTestParameters())) {
if (isCurrentSelection(token, resourceId)) setStatus(byId('resource-test-status'), tKey('resources.test.stale', 'The Resource or parameters changed; this result was not applied.'));
return;
}
if (response.status !== 200 || !response.payload) {
setStatus(byId('resource-test-status'), tKey('resources.test.error', 'The test read failed safely.'));
return;
}
var output = response.payload.output;
if (response.payload.ok && (output == null || output === '')) {
setStatus(byId('resource-test-status'), tKey('resources.test.empty', 'The read returned no content.'));
setText(byId('resource-test-output'), '');
return;
}
setStatus(byId('resource-test-status'), response.payload.ok
? tKey('resources.test.done', 'Test read completed.')
: tKey('resources.test.error', 'The test read failed safely.'));
setText(byId('resource-test-output'), JSON.stringify(output != null ? output : response.payload.error || {}, null, 2));
}
var resourceTestStart = byId('resource-test-start');
var resourceTestAccept = byId('resource-test-accept');
if (resourceTestStart) resourceTestStart.addEventListener('click', function() {
if (state.selectedLoaded && state.source && state.sourceFindings.length === 0) byId('resource-test-confirm').hidden = false;
});
if (resourceTestAccept) resourceTestAccept.addEventListener('click', runResourceTest);
if (byId('resource-test-cancel')) byId('resource-test-cancel').addEventListener('click', function() {
byId('resource-test-confirm').hidden = true;
});
function fillVersionOptions(latestVersion) {
if (!sourceVersion) {
return;
}
clearHost(sourceVersion);
if (latestVersion == null) {
return;
}
// Опубликованная версия адресуется exact integer, не latest-alias.
var option = document.createElement('option');
option.value = String(latestVersion);
option.textContent = String(latestVersion);
sourceVersion.appendChild(option);
}
function invalidateSourceBinding() {
state.binding = null;
state.bindingToken += 1;
if (sourceParamsHost) {
clearHost(sourceParamsHost);
}
}
function selectOperationVersion() {
invalidateSourceBinding();
if (!sourceOperation) {
return;
}
var option = sourceOperation.options[sourceOperation.selectedIndex];
fillVersionOptions(option && option.getAttribute('data-version'));
}
async function loadSourceOperations() {
invalidateSourceBinding();
var requestToken = state.bindingToken;
state.binding = null;
if (sourceParamsHost) {
clearHost(sourceParamsHost);
}
if (sourceEmpty) {
sourceEmpty.hidden = true;
}
if (sourceOperation) {
clearHost(sourceOperation);
}
if (sourceVersion) {
clearHost(sourceVersion);
}
setStatus(sourceStatus, '');
if (sourceLoading) {
sourceLoading.hidden = false;
}
var response;
try {
response = await fetch(operationsPath(), { credentials: 'same-origin' });
} catch (_error) {
if (requestToken !== state.bindingToken) {
return;
}
if (sourceLoading) {
sourceLoading.hidden = true;
}
setStatus(sourceStatus, tKey('resources.source.error', 'The published operations could not be loaded. Try again.'));
return;
}
var result = await readJson(response);
if (requestToken !== state.bindingToken) {
return;
}
if (sourceLoading) {
sourceLoading.hidden = true;
}
if (!response.ok) {
setStatus(sourceStatus, tKey('resources.source.error', 'The published operations could not be loaded. Try again.'));
return;
}
var items = (result.payload && result.payload.items) || [];
var published = items.filter(function(item) {
return item && item.latest_published_version != null;
});
if (!published.length) {
if (sourceEmpty) {
sourceEmpty.hidden = false;
}
return;
}
published.forEach(function(item) {
var option = document.createElement('option');
// OperationSummaryView называет идентификатор `id`.
option.value = item.id || item.operation_id || '';
option.textContent = item.name || item.display_name || option.value;
option.setAttribute('data-version', String(item.latest_published_version));
sourceOperation.appendChild(option);
});
selectOperationVersion();
}
async function bindSource() {
if (!sourceOperation || !sourceVersion || !sourceUriTemplate) {
return;
}
var operationId = sourceOperation.value;
var version = sourceVersion.value;
var uriTemplate = sourceUriTemplate.value.trim();
var bindingToken = ++state.bindingToken;
state.binding = null;
if (!operationId || !version) {
setStatus(sourceStatus, tKey('resources.source.empty', 'Choose a published operation first.'));
return;
}
var uriPlaceholders = [];
uriTemplate.replace(/\{([a-z][a-z0-9_]*)\}/g, function(_match, name) {
if (uriPlaceholders.indexOf(name) === -1) {
uriPlaceholders.push(name);
}
return _match;
});
var response;
try {
response = await fetch(
operationsPath() + '/' + encodeURIComponent(operationId) + '/versions/' + encodeURIComponent(version),
{ credentials: 'same-origin' },
);
} catch (_error) {
if (bindingToken !== state.bindingToken || operationId !== sourceOperation.value
|| version !== sourceVersion.value || uriTemplate !== sourceUriTemplate.value.trim()) return;
state.binding = null;
setStatus(sourceStatus, tKey('resources.source.bind_error', 'The selected version could not be pinned. Try again.'));
return;
}
var result;
try {
result = await readJson(response);
} catch (_error) {
if (bindingToken !== state.bindingToken || operationId !== sourceOperation.value
|| version !== sourceVersion.value || uriTemplate !== sourceUriTemplate.value.trim()) return;
state.binding = null;
setStatus(sourceStatus, tKey('resources.source.bind_error', 'The selected version could not be pinned. Try again.'));
return;
}
if (bindingToken !== state.bindingToken || operationId !== sourceOperation.value
|| version !== sourceVersion.value || uriTemplate !== sourceUriTemplate.value.trim()) return;
if (!response.ok) {
state.binding = null;
setStatus(sourceStatus, tKey('resources.source.bind_error', 'The selected version could not be pinned. Try again.'));
return;
}
var snapshot = (result.payload && result.payload.snapshot) || {};
var fields = (snapshot.input_schema && snapshot.input_schema.fields) || {};
state.pinnedInputFields[pinnedInputKey(operationId, version)] = fields;
var parameters = uriPlaceholders.map(function(name) {
return {
name: name,
input_path: 'input.' + name,
// Факты pinned поля, не клиентская копия серверных правил.
schema: fields[name] || { type: 'string', required: true },
};
});
state.binding = {
operation_id: operationId,
operation_version: Number(version),
uri_template: uriTemplate,
parameters: parameters,
};
renderParamRows(sourceParamsHost, parameters, []);
setStatus(
sourceStatus,
tKey('resources.source.pinned_done', 'Pinned operation') + ' ' + operationId + ' · v' + version,
);
}
function templateMetadata() {
var binding = state.binding;
var parameters = (binding.parameters || []).map(function(parameter) {
return {
name: parameter.name,
input_path: parameter.input_path,
schema: parameter.schema,
};
});
var vary = parameters.map(function(parameter) {
return parameter.name;
});
return {
uri: byId('resource-form-uri').value.trim(),
name: byId('resource-form-name').value.trim(),
description: byId('resource-form-description').value.trim(),
kind: byId('resource-form-kind').value,
mime_type: byId('resource-form-mime-type').value.trim(),
sensitivity: byId('resource-form-sensitivity').value,
source: {
operation_id: binding.operation_id,
operation_version: binding.operation_version,
uri_template: binding.uri_template,
parameters: parameters,
cache: { ttl_ms: 60000, vary: vary, max_bytes: 65536 },
failure: { outcome: 'error' },
},
};
}
async function createTemplateDraft() {
if (!state.binding || state.binding.operation_id !== sourceOperation.value
|| String(state.binding.operation_version) !== sourceVersion.value
|| state.binding.uri_template !== sourceUriTemplate.value.trim()) {
invalidateSourceBinding();
setStatus(sourceStatus, tKey('resources.source.empty', 'Choose a published operation first.'));
return;
}
var metadata = templateMetadata();
var token = await csrfToken();
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }), 'metadata.json');
setStatus(sourceStatus, tKey('resources.source.pending', 'Creating the template draft…'));
var response;
try {
response = await fetch(apiPath(''), {
method: 'POST',
credentials: 'same-origin',
headers: { 'X-CSRF-Token': token },
body: form,
});
} catch (_error) {
setStatus(sourceStatus, tKey('resources.source.preview_error', 'The template draft could not be created.'));
return;
}
var result = await readJson(response);
if (response.status !== 201) {
setStatus(sourceStatus, errorMessage(result.payload, tKey('resources.source.preview_error', 'The template draft could not be created.')));
return;
}
setStatus(sourceStatus, tKey('resources.source.done', 'The template draft was created.'));
// Ответ create уже содержит источник и server findings того же снимка.
renderCardSource(result.payload);
await loadList();
var created = result.payload && result.payload.resource ? result.payload.resource.resource_id : '';
if (created) {
selectResource(created);
}
}
if (sourceMode) {
sourceMode.addEventListener('change', function() {
invalidateSourceBinding();
var rest = sourceMode.value === 'rest';
if (staticContent) {
staticContent.hidden = rest;
}
if (sourcePanel) {
sourcePanel.hidden = !rest;
}
if (rest) {
loadSourceOperations();
}
});
}
if (sourceOperation) {
sourceOperation.addEventListener('change', selectOperationVersion);
}
if (sourceVersion) {
sourceVersion.addEventListener('change', invalidateSourceBinding);
}
if (sourceUriTemplate) {
sourceUriTemplate.addEventListener('input', invalidateSourceBinding);
}
if (sourceBind) {
sourceBind.addEventListener('click', function() {
bindSource().catch(function() {
setStatus(sourceStatus, tKey('resources.source.bind_error', 'The selected version could not be pinned. Try again.'));
});
});
}
if (sourcePreview) {
sourcePreview.addEventListener('click', function() {
createTemplateDraft().catch(function() {
setStatus(sourceStatus, tKey('resources.source.preview_error', 'The template draft could not be created.'));
});
});
}
// -------------------------------------------------------------------------
// Создание черновика
// -------------------------------------------------------------------------
if (createForm) {
createForm.addEventListener('submit', function(event) {
event.preventDefault();
// Story 3.10: в режиме REST источником является определение, а не файл.
if (sourceMode && sourceMode.value === 'rest') {
createTemplateDraft().catch(function() {
setStatus(sourceStatus, tKey('resources.source.preview_error', 'The template draft could not be created.'));
});
return;
}
// Синхронный снимок формы: запрос начинается без ожиданий, переход страницы
// не обрывает принятую мутацию.
var kind = byId('resource-form-kind').value;
var mimeType = byId('resource-form-mime-type').value.trim();
var fileInput = byId('resource-form-file');
var metadata = {
uri: byId('resource-form-uri').value.trim(),
name: byId('resource-form-name').value.trim(),
description: byId('resource-form-description').value.trim(),
kind: kind,
mime_type: mimeType,
sensitivity: byId('resource-form-sensitivity').value,
};
var content = {
file: kind === 'binary' && fileInput.files && fileInput.files[0] ? fileInput.files[0] : null,
text: byId('resource-form-content').value,
};
setStatus(createStatus, tKey('resources.create.pending', 'Creating the draft…'));
sendDraft('POST', apiPath(''), metadata, content, mimeType).then(function(result) {
if (result.status !== 201) {
setStatus(createStatus, errorMessage(result.payload, tKey('resources.create.error', 'The draft could not be created.')));
return;
}
setStatus(createStatus, tKey('resources.create.done', 'The draft was created.'));
createForm.reset();
return loadList().then(function() {
var created = result.payload && result.payload.resource ? result.payload.resource.resource_id : '';
if (created) {
selectResource(created);
}
});
}).catch(function() {
setStatus(createStatus, tKey('resources.create.error', 'The draft could not be created.'));
});
});
}
// -------------------------------------------------------------------------
// Редактирование: изменяемые description/MIME/sensitivity/content и
// precondition текущей загруженной версии. uri/name/kind не отправляются.
// -------------------------------------------------------------------------
if (editForm) {
editForm.addEventListener('submit', function(event) {
event.preventDefault();
if (!state.resourceId) {
setStatus(editStatus, tKey('resources.edit.select', 'Select a draft first.'));
return;
}
var kind = (document.querySelector(META_KIND) || {}).textContent || '';
var mimeType = byId('resource-edit-mime-type').value.trim();
var fileInput = byId('resource-edit-file');
// Для binary контракт полной замены сохраняется, но заменяемый файл обязан быть
// выбран явно **для текущего** Draft: файл прежнего выбора никогда не отправляется (F3).
if (kind === 'binary' && !state.source && !(fileInput.files && fileInput.files[0])) {
setStatus(
editStatus,
tKey('resources.edit.file', 'Choose the replacement file for the selected draft first.'),
);
return;
}
var metadata = {
description: byId('resource-edit-description').value,
mime_type: mimeType,
sensitivity: byId('resource-edit-sensitivity').value,
expected_updated_at: state.updatedAt,
};
var content = {
file: kind === 'binary' && fileInput.files && fileInput.files[0] ? fileInput.files[0] : null,
text: byId('resource-edit-content').value,
};
if (state.source) {
metadata.source = {
operation_id: state.source.operation_id,
operation_version: state.source.operation_version,
uri_template: state.source.uri_template,
parameters: state.source.parameters.map(function(parameter) {
return { name: parameter.name, input_path: parameter.input_path, schema: parameter.schema };
}),
cache: { ttl_ms: state.source.cache.ttl_ms, vary: state.source.cache.vary, max_bytes: state.source.cache.max_bytes },
failure: { outcome: state.source.failure.outcome },
};
content = null;
}
var resourceId = state.resourceId;
var token = state.loadToken;
setStatus(editStatus, tKey('resources.edit.pending', 'Saving the new version…'));
sendDraft('PUT', apiPath('/' + encodeURIComponent(resourceId)), metadata, content, mimeType).then(function(result) {
// Поздний ответ правки не применяется, если выбор уже сменился (F2).
if (!isCurrentSelection(token, resourceId)) {
return;
}
if (result.status !== 200) {
setStatus(editStatus, errorMessage(result.payload, tKey('resources.edit.error', 'The draft could not be updated.')));
return;
}
setStatus(editStatus, tKey('resources.edit.done', 'The new version was saved.'));
state.mutationToken += 1;
return loadList().then(function() {
if (!isCurrentSelection(token, resourceId)) {
return;
}
return loadResource(resourceId, token);
});
}).catch(function() {
if (isCurrentSelection(token, resourceId)) {
setStatus(editStatus, tKey('resources.edit.error', 'The draft could not be updated.'));
}
});
});
}
if (publishButton) {
publishButton.addEventListener('click', function() {
if (!state.resourceId || publishButton.disabled) {
return;
}
var confirmation = showConfirm('resources.publish', templates.publishConfirm);
if (!confirmation) {
return;
}
// Story 3.10: подтверждение показывает pinned факты выбранного шаблона.
if (state.source) {
var facts = confirmation.querySelector('[data-testid="resource-source-confirm-facts"]');
if (facts) {
var safety = state.source.read_safety || {};
var access = state.source.access || {};
var sensitivity = (document.querySelector(META_SENSITIVITY) || {}).textContent || '';
facts.textContent = [
state.source.operation_id + ' · v' + state.source.operation_version,
safety.method || '',
sensitivity,
access.security_level || '',
].filter(Boolean).join(' · ');
}
}
confirmation.querySelector('[data-confirm-accept]').addEventListener('click', runPublish);
confirmation.querySelector('[data-confirm-cancel]').addEventListener('click', function() {
clearHost(confirmHost);
});
});
}
if (archiveButton) {
archiveButton.addEventListener('click', function() {
if (!state.resourceId || archiveButton.disabled) {
return;
}
var confirmation = showConfirm('resources.archive', templates.archiveConfirm);
if (!confirmation) {
return;
}
confirmation.querySelector('[data-confirm-accept]').addEventListener('click', runArchive);
confirmation.querySelector('[data-confirm-cancel]').addEventListener('click', function() {
clearHost(confirmHost);
});
});
}
if (bindAgent) {
bindAgent.addEventListener('change', function() {
var agentId = bindAgent.value;
state.bind = null;
hideBindStale();
setText(bindAgentVersion, '');
setStatus(bindStatus, '');
refreshBindButton();
if (!agentId) {
return;
}
loadAgentState(agentId).catch(function() {
setStatus(bindStatus, tKey('resources.bind.error', 'The Resource could not be bound.'));
});
});
}
if (bindReload) {
bindReload.addEventListener('click', reloadBindAgent);
}
if (bindSubmit) {
bindSubmit.addEventListener('click', function() {
if (bindSubmit.disabled) {
return;
}
runBind();
});
}
async function loadPage() {
if (window.whenWorkspacesReady) {
await window.whenWorkspacesReady();
}
state.workspaceId = workspaceId();
if (!state.workspaceId && typeof window.refreshWorkspaces === 'function') {
// Reload может обогнать bootstrap сессии: первый список workspace тогда пуст.
// Один явный повтор после готовности сессии; бесконечных retry нет.
if (window.CrankAuth && typeof window.CrankAuth.fetchSession === 'function') {
try {
await window.CrankAuth.fetchSession(false);
} catch (_error) {
// сессия остаётся неподтверждённой — ниже видимая ошибка
}
}
try {
await window.refreshWorkspaces();
} catch (_error) {
// отказ остаётся видимым ниже
}
state.workspaceId = workspaceId();
}
if (!state.workspaceId) {
setStatus(statusElement, tKey('resources.error', 'The Resource could not be loaded.'));
return;
}
if (findingsTitle) {
setText(findingsTitle, tKey('resources.findings.title', 'Publication checks'));
}
var initial = resourceIdFromUrl();
if (initial) {
beginSelection(initial);
setEditEnabled(false);
}
await loadList();
loadAgents().catch(function() {});
if (!initial) {
setStatus(statusElement, tKey('resources.empty', 'No Resource selected.'));
return;
}
await loadResource(initial, state.loadToken);
}
setEditEnabled(false);
refreshActionButtons();
refreshBindButton();
loadPage().catch(function(error) {
if (window.CrankDiagnostics && typeof window.CrankDiagnostics.report === 'function') {
window.CrankDiagnostics.report('resources-load', error, 'resources');
}
setStatus(statusElement, tKey('resources.error', 'The Resource could not be loaded.'));
});
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initResourcesPage);
} else {
initResourcesPage();
}