Author SHA1 Message Date
DCCONSTRUCTIONS ccaf032db5 Clear previous media selection before opening a new picker
DC CMS qualification / qualify (push) Successful in 1m23s
2026-11-13 18:21:45 +03:00
DCCONSTRUCTIONS 9f4b74a6d3 Add site-wide media grid with combined filters and shared path bar
DC CMS qualification / qualify (push) Successful in 1m46s
2026-11-13 18:11:18 +03:00
DCCONSTRUCTIONS 5d56f5fe21 Persist user GUI preferences and resize the shared media modal
DC CMS qualification / qualify (push) Successful in 2m22s
2026-11-13 17:56:23 +03:00
DCCONSTRUCTIONS ff90b633d9 Add site-scoped file manager navigation and original file downloads
DC CMS qualification / qualify (push) Successful in 1m53s
2026-11-13 17:16:54 +03:00
DCCONSTRUCTIONS 944b88f30f Choose the Open Graph image from the current site media library
DC CMS qualification / qualify (push) Successful in 1m47s
2026-11-06 11:38:09 +03:00
DCCONSTRUCTIONS cf204a73dd Use the shared color picker for editable site fields
DC CMS qualification / qualify (push) Successful in 1m43s
2026-11-06 10:28:17 +03:00
DCCONSTRUCTIONS f0949f5e75 fix(cms): acknowledge saved edits and publish the latest editor content
DC CMS qualification / qualify (push) Successful in 1m56s
2026-11-06 09:15:16 +03:00
DCCONSTRUCTIONS 5ea737318b feat(cms): download portable backups from site settings
DC CMS qualification / qualify (push) Successful in 1m57s
2026-11-05 22:37:55 +03:00
DCCONSTRUCTIONS d86be605a8 fix(cms): align setting label and switch in the shared horizontal row
DC CMS qualification / qualify (push) Successful in 1m29s
2026-11-05 21:36:59 +03:00
DCCONSTRUCTIONS be8ebe43e7 feat(cms): reuse shared setting rows for boolean content controls
DC CMS qualification / qualify (push) Successful in 1m49s
2026-11-05 21:32:59 +03:00
DCCONSTRUCTIONS 7f25f59d3e fix(cms): publish saved content through queued rebuild and SFTP
DC CMS qualification / qualify (push) Successful in 2m26s
2026-11-05 19:43:19 +03:00
DCCONSTRUCTIONS b208b83d4f fix(cms): use Mission Core neutral form groups without black inserts
DC CMS qualification / qualify (push) Successful in 1m49s
2026-11-05 16:04:35 +03:00
36 changed files with 1410 additions and 441 deletions
+2
View File
@@ -14,3 +14,5 @@ projects/*.publish.log.jsonl
# Persistent independent site workspaces are runtime data.
projects/sites/
projects/*.publish-state.json*
+1 -1
View File
File diff suppressed because one or more lines are too long
+88 -88
View File
File diff suppressed because one or more lines are too long
+9 -4
View File
File diff suppressed because one or more lines are too long
+35 -11
View File
@@ -91,29 +91,53 @@ Verified: dark/light, accent change and reload persistence, reset to white,
nested palette Escape, 390px modal, plus/template picker, pointer drag/reorder
(discarded), switching independent sites, and the shared component/type checks.
Form groups, collection entries and JSON disclosures consume `GlassSurface tone="soft"`
with its shared padding/radius/material. The former app-local translucent
item background accumulated across nested cards and converged with TextField
fill; using the canonical opaque nested surface preserves visible field zones
in both themes without adding borders or changing input tokens.
Form groups outside collections use the same nested surface so light-theme
white inputs remain separated from white outer panels; collections already
provide that surface and do not receive a second wrapper or double padding.
Forms follow the running Mission Core environment settings: SettingsCard owns
the group and fields sit directly in its transparent layout grid. A standalone
collection entry or native JSON disclosure adopts GlassSurface tone="group",
which uses the same neutral material. The content overview is layout rather
than another surrounding card. Native details, drag nodes and input bindings
stay intact; no CMS-specific colors or component overrides are added.
## Mission Core foundation — 2026-11-05
Pinned Design Guideline: `3750a9420058fb76880cd73bb9f2d106d7cd10d5`.
Pinned Design Guideline: `189bb7037740f577cc65e72f2b7c07651201ef19`.
CMS applies `missionDarkTheme` / `missionLightTheme` at documentElement, so menus
and settings portals share the same profile. The library owns all palette values;
reset clears a custom accent and returns to the preset. Existing explicit user
accent preferences remain supported. The static HTML declares Mission/flat before
JavaScript to avoid a flash of the legacy appearance.
Nested forms use the same SettingsCard → GlassSurface soft → field composition
as the living catalog. Media-stage and dropdown materials now reference shared
Forms use the same SettingsCard → fields and optional GlassSurface group
collection composition as the living catalog. Media-stage and dropdown materials now reference shared
tokens. No business module, site data, deployment settings or server API changed.
Validation: deterministic generated build, multisite and release-contract tests;
local browser checks of the reported navigation-link fields, dark/light, settings
through the profile menu, custom accent, reset, and Escape focus restoration.
## Full-width boolean setting rows
A boolean editable field can declare `layout: "row"` and an optional `title`.
The editor uses the shared SettingsCard (title left, Switch right) and Switch,
above the following field in schema order. Values continue through the standard
model save/render/publish flow; no carousel-specific CMS state or new CSS is
introduced. Mission Core uses this for its per-carousel image-opening setting.
Local UI acceptance: toggle on → Save → reload retains true, toggle off → Save
removes the image links while preserving the other carousels.
## File manager window and navigation
The ui-dom package is pinned separately at `1326ec6` (`modal.2` archive) in
`ui/design-system.lock.json`; the existing Mission Core palette and other
packages keep their original pinned versions. CMS consumes the shared
`createModalSizeController` and `renderPathBar` exports, including the package's
path-bar stylesheet. The application adapter supplies site paths, standard
Icon templates and navigation callbacks. It does not copy either component.
Window geometry and appearance persist in the authenticated user's server-side
GUI metadata. File type controls reuse IconButton, support combined selection,
and switch between the site's flat asset index and existing folder browser.
Acceptance: mixed image/video/3D filtering, deep-folder search and path navigation,
isolation between two sites, 390 px layout, resize/reopen/reload and theme
persistence. Source tests cover the flat index's site boundary and exclusions.
+67 -1
View File
@@ -6,7 +6,65 @@
Перенос деплоя сначала отключает исходный проект, затем переносит зашифрованный секрет и параметры хостинга. Получатель остаётся отключённым до явного включения. Два проекта не могут одновременно публиковать в одну или вложенную папку на одном SFTP-аккаунте. После прерывания возможны два отключённых проекта, но не два включённых публикационных направления.
Сохранение и пересборка отделены от публикации. Автоматическая публикация после пересборки требует двух флагов: `enabled` и `deployOnRender`. Старые настройки без второго флага переходят в ручной режим публикации.
«Сохранить» записывает контент или SEO/базу знаний и запускает пересборку. Когда включены `deploy.enabled` и «Публиковать при сохранении» (`deployOnRender`), CMS ставит фоновое задание: собирает главную и базу знаний, фиксирует копию публичных файлов и отправляет её по SFTP. Прогресс и ошибки доступны в редакторе и настройках проекта. Сохранение во время передачи ставит ещё один проход с последней версией; изменения не теряются. Без этих флагов обновляется только предпросмотр.
«Опубликовать» также сначала собирает обе части сайта. Файлы пропускаются только при совпадении SHA-256 с последней успешной публикацией и метаданных на хостинге; размер и время сами по себе недостаточны для сравнения. Частный файл `projects/<id>.publish-state.json` привязан к конкретному SFTP-направлению, не попадает в сайт и не содержит паролей. Первая публикация после обновления передаёт все файлы, следующие — только изменения. Ошибку передачи можно повторить кнопкой «Опубликовать».
ZIP нужен для обновления кода и шаблонов локально. Для обычного редактирования текста и изображений повторный импорт не нужен. Новые изображения получают уникальный URL, поэтому кеш браузера не скрывает замену.
## Скачать бэкап
В настройках каждого сайта рядом с публикацией доступна кнопка «Скачать бэкап».
Она скачивает текущую **сохранённую** копию выбранного сайта: модели контента,
SEO и базы знаний, шаблоны, инструменты рендера, готовые страницы и медиа.
Несохранённые изменения редактора в архив не входят; скачивание ничего не
сохраняет и не публикует. Архив можно вернуть через существующий импорт ZIP.
Маршрут `POST /s/<id>/api/project/backup` готовит снимок; одноразовый GET
по возвращённой ссылке передаёт ZIP штатному загрузчику браузера без Blob в JS.
Оба маршрута закрыты общей авторизацией CMS и не принимают произвольный путь
к файлам. Невостребованный архив удаляется через 10 минут. Имя содержит ID сайта, дату по Москве
и суффикс TECH: `NODEDC_SITE_2026-11-05_MISSION_CORE_TECH.zip`.
Это бэкап сайта, а не инсталляции CMS: реквизиты публикации, учётные записи
и реестр сайтов находятся отдельно. `.env*`, `*.secrets.json`, `.git`,
старые бэкапы, корзина и зависимости исключены; символические ссылки отклоняются.
Подготовка блокирует одновременную запись, импорт и публикацию этого сайта.
Файлы и их состав проверяются повторно: при внешнем изменении скачивание
возвращает ошибку с предложением повторить. Готовый ZIP передаётся из приватной
временной папки, которая удаляется после передачи или отключения клиента.
ZIP собирается потоково методом STORE, без полной копии медиа в памяти и новых
runtime-зависимостей. Лимит — 2 ГБ и 60 000 файлов. После подготовки снимка
обычное редактирование снова доступно, пока браузер скачивает архив.
Проверки: `test/backup.test.mjs` сверяет ZIP/CRC, UTF-8 имена, медиа, исключения,
ссылки и отмену; `test/multisite.test.mjs` скачивает оба сайта, проверяет
изоляцию и авторизацию и импортирует полученный ZIP обратно в тестовый сайт.
## Файлы сайта
Кнопка «Файлы» в верхней навигации открывает существующий файловый менеджер
для выбранного сайта. В заголовке указано имя сайта; список, загрузки, корзина,
скачивание и запомненная папка изолированы по `/s/<site-id>/`. Просмотр и загрузка
в этом режиме не подставляют файл в открытое поле и не меняют черновик страницы.
Загрузки без привязки к полю сохраняются в `assets/uploads/media/library`.
Менеджер из шапки открывается общей сеткой файлов из всех вложенных каталогов
`assets`. Фильтры-иконки изображений, видео и 3D можно сочетать; «Все» сбрасывает
выбор типов. Поиск проверяет имя и полный путь. Справа переключается общий
список и просмотр папок. Нижняя строка пути использует общий `renderPathBar`:
нейтральные иконки папок, компактные названия и переход по любому каталогу.
Выбор файла показывает его полный путь, исходное имя и кнопку скачивания.
Индекс исключает скрытые/служебные каталоги и символические ссылки, не выходит
за пределы выбранного сайта. Обычный picker сохраняет ограничение типа поля.
После выбора файла кнопка «Скачать» передаёт его исходные байты и имя через
авторизованный `GET /s/<site-id>/api/media/download?path=assets/...`.
Видео передаются потоком без сборки ZIP и без загрузки целого файла в память
браузера. Доступны публичные файлы `assets`; директории, скрытые/служебные
пути и символические ссылки запрещены. Для удалённого файла сначала требуется
восстановление из корзины. Кнопка скачивания доступна также в обычном выборе
изображения, включая Open Graph. Публикация сайта остаётся отдельным действием.
## Git
@@ -31,3 +89,11 @@ Workflow `.gitea/workflows/ci.yml` квалифицирует точный commi
## Проверка
`node --test test/multisite.test.mjs` проверяет изоляцию контента, медиа, рендера и ссылок предпросмотра, секреты, конфликт направлений, перезапуск и авторизацию. `python3 -m unittest discover -s infra/ci -p 'test_*.py'` проверяет формат пакета и запрет runtime-файлов.
## Пользовательские настройки интерфейса
`GET/PATCH /api/user/preferences` использует текущую авторизованную сессию; идентификатор пользователя не принимается из запроса. Файл: `<CMS_PROJECTS_ROOT>/.user-meta/<sha256(principal)>.json`, права 0600. Каталог находится в существующем persistent mount, вне корней сайтов, публикации и ZIP-бэкапов. В режиме без авторизации используется отдельный локальный профиль.
Схема: `schemaVersion: 1`, `appearance: {theme, accent}`, `gui: {modals: {"media-library": {width, height}}}`. PATCH объединяет независимые поля последовательно на пользователя; запись атомарная. `null` у ключа модального окна сбрасывает его размер. Тема из прежнего localStorage импортируется один раз при отсутствии серверного профиля.
Файловый менеджер использует общий `createModalSizeController`: края/углы мышью, Shift + стрелки при фокусе на шапке. Сохраняется завершённый resize. Подгонка под меньший экран не перезаписывает предпочтительный размер. Геометрия общая для сайтов текущего пользователя; контент менеджера по-прежнему изолирован по сайту. Ошибка записи отображается с повтором, закрытие окна не блокируется.
+1 -1
View File
@@ -61,7 +61,7 @@ def main():
files=tracked_payload()
for name in files:
if name.endswith(('.js','.mjs')): run(['node','--check',name])
run(['node','--test','test/multisite.test.mjs'])
run(['node','--test','test/multisite.test.mjs','test/publication.test.mjs','test/backup.test.mjs','test/user-preferences.test.mjs'])
run(['python3','-m','unittest','discover','-s','infra/ci','-p','test_*.py'])
# The ordinary release cannot change its build, dependency or deployment foundation.
foundation={name:digest((ROOT/name).read_bytes()) for name in ['Dockerfile','package.json','package-lock.json','infra/docker-compose.yml']}
+45
View File
@@ -0,0 +1,45 @@
import { constants } from "node:fs";
import { lstat, open } from "node:fs/promises";
import { join } from "node:path";
// Downloads belong to one site and contain only its public assets. In particular,
// never follow a symlink into another site's files, CMS settings or credentials.
export async function openMediaDownload(siteRoot, path) {
const segments = String(path || "").split("/");
if (segments.length < 2 || segments[0] !== "assets" || segments.some(segment =>
!segment || segment.startsWith(".") || segment === "node_modules" || /[\\\x00-\x1f\x7f]/.test(segment)
)) {
throw Object.assign(new Error("Скачивание доступно только для файлов медиатеки текущего сайта"), { status: 403 });
}
let absolutePath = siteRoot;
for (const segment of segments) {
absolutePath = join(absolutePath, segment);
const info = await lstat(absolutePath);
if (info.isSymbolicLink()) {
throw Object.assign(new Error("Скачивание по символической ссылке запрещено"), { status: 403 });
}
if (!info.isDirectory() && !info.isFile()) throw Object.assign(new Error("Выберите файл для скачивания"), { status: 400 });
}
const handle = await open(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW);
try {
const info = await handle.stat();
if (!info.isFile()) throw Object.assign(new Error("Выберите файл для скачивания"), { status: 400 });
const name = segments.at(-1);
const fallback = name.replace(/[^a-zA-Z0-9._-]/g, "_");
const encoded = encodeURIComponent(name).replace(/[!'()*]/g, char => `%${char.charCodeAt(0).toString(16).toUpperCase()}`);
return {
handle,
headers: {
"content-type": "application/octet-stream",
"content-disposition": `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`,
"content-length": info.size,
"cache-control": "no-store",
"x-content-type-options": "nosniff",
},
};
} catch (error) {
await handle.close();
throw error;
}
}
+8
View File
@@ -4,6 +4,7 @@ import { dirname, join, resolve, posix, relative } from "node:path";
import { fileURLToPath } from "node:url";
import { randomBytes } from "node:crypto";
import { createSiteApplication } from "./site-app.mjs";
import { UserPreferencesStore } from "./user-preferences.mjs";
const cmsRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const projectsRoot = resolve(process.env.CMS_PROJECTS_ROOT || join(cmsRoot, "projects"));
@@ -150,6 +151,7 @@ function json(res, status, payload) {
}
await mkdir(projectsRoot, { recursive: true });
const auth = await application(defaultId);
const userPreferences = new UserPreferencesStore(projectsRoot);
const server = createServer(async (req, res) => {
try {
const url = new URL(req.url, "http://cms.local");
@@ -160,6 +162,12 @@ const server = createServer(async (req, res) => {
const expected = new URL(process.env.CMS_BASE_URL || `http://${req.headers.host}`).origin;
if (req.headers["sec-fetch-site"] === "cross-site" || (origin && origin !== expected)) throw fail("Недопустимый источник запроса", 403);
}
if (url.pathname === "/api/user/preferences") {
const principal = auth.authEnabled ? (req.cmsUser?.sub ? `oidc:${req.cmsUser.sub}` : null) : 'local:no-auth';
if (req.method === 'GET') return json(res, 200, { ok: true, ...await userPreferences.read(principal) });
if (req.method === 'PATCH') return json(res, 200, { ok: true, ...await userPreferences.patch(principal, await body(req), { ifAbsent: req.headers['if-none-match'] === '*' }) });
throw fail('Метод не поддерживается', 405);
}
if (url.pathname === "/api/sites") {
if (req.method === "GET") return json(res, 200, { ok: true, sites: await siteList() });
if (req.method === "POST") return json(res, 201, { ok: true, project: await createSite(await body(req)) });
+163 -60
View File
@@ -1,5 +1,6 @@
import { createReadStream, statSync } from "node:fs";
import { appendFile, copyFile, cp, mkdir, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import { appendFile, copyFile, cp, lstat, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { extname, join, normalize, relative, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { spawn } from "node:child_process";
@@ -8,6 +9,9 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes,
import { createLocalJWKSet, jwtVerify } from "jose";
import SftpClient from "ssh2-sftp-client";
import AdmZip from "adm-zip";
import { pipeline } from "node:stream/promises";
import { createSiteBackup, siteBackupFilename } from "./site-backup.mjs";
import { openMediaDownload } from "./media-download.mjs";
const cmsRoot = join(dirname(fileURLToPath(import.meta.url)), "..");
const port = Number(process.env.PORT || 8090);
@@ -17,7 +21,10 @@ const activeProjectId = projectId;
const projectConfigPath = join(projectsRoot, `${activeProjectId}.json`);
const projectSecretsPath = join(projectsRoot, `${activeProjectId}.secrets.json`);
const publishLogPath = join(projectsRoot, `${activeProjectId}.publish.log.jsonl`);
const publishStatePath = join(projectsRoot, `${activeProjectId}.publish-state.json`);
const publishJobs = new Map();
let backupRunning = false;
let preparedBackup = null;
const PUBLISH_JOB_RETENTION_MS = 24 * 60 * 60 * 1000;
async function loadProjectConfig() {
@@ -57,36 +64,7 @@ const trashStores = [
displayPrefix: "assets/uploads/.trash",
},
];
const mediaRoots = [
{
id: "uploads",
label: "Uploads",
rootPath: uploadRoot,
urlPrefix: "./assets/uploads",
writable: true,
},
{
id: "media",
label: "Legacy media",
rootPath: join(repoRoot, "assets", "media"),
urlPrefix: "./assets/media",
writable: true,
},
{
id: "site-images",
label: "Site images",
rootPath: join(repoRoot, "assets", "site", "images"),
urlPrefix: "./assets/site/images",
writable: true,
},
{
id: "custom-assets",
label: "Custom assets",
rootPath: join(repoRoot, "assets", "custom"),
urlPrefix: "./assets/custom",
writable: true,
},
];
const mediaRoots = [{ id: "assets", label: "Файлы сайта", rootPath: join(repoRoot, "assets"), urlPrefix: "./assets", writable: true }];
const MEDIA_EXTENSIONS = new Set([
".avif",
".gif",
@@ -1357,16 +1335,19 @@ async function scanMediaRoot(root) {
let entries = [];
try {
const directoryStat = await lstat(directory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) return;
entries = await readdir(directory, { withFileTypes: true });
} catch {
return;
} catch (error) {
if (error.code === "ENOENT") return;
throw error;
}
for (const entry of entries) {
const filePath = join(directory, entry.name);
const relativePath = relative(root.rootPath, filePath).replace(/\\/g, "/");
if (!relativePath || relativePath.split("/").includes(".trash")) continue;
if (!relativePath || relativePath.split("/").some(part => part.startsWith(".") || BROWSER_EXCLUDED_DIRS.has(part))) continue;
if (entry.isDirectory()) {
await walk(filePath);
@@ -1384,6 +1365,9 @@ async function scanMediaRoot(root) {
files.push({
id: `${root.id}:${relativePath}`,
type: "file",
path: relative(repoRoot, filePath).replace(/\\/g, "/"),
selectable: true,
rootId: root.id,
rootLabel: root.label,
writable: root.writable,
@@ -1778,17 +1762,29 @@ async function ensureRemoteDirectory(client, path, cache) {
cache.add(normalized);
}
async function shouldSkipRemoteFile(client, localFile, remotePath) {
async function fileDigest(path) {
const hash = createHash("sha256");
for await (const chunk of createReadStream(path)) hash.update(chunk);
return hash.digest("hex");
}
async function shouldSkipRemoteFile(client, localFile, remotePath, previous) {
// SFTP timestamps have second precision: equal size + mtime loses one-letter edits.
if (previous?.sha256 !== localFile.sha256) return false;
try {
const remoteStat = await client.stat(remotePath);
if (!remoteStat || Number(remoteStat.size) !== localFile.size) return false;
const remoteMtime = Number(remoteStat.modifyTime || remoteStat.mtime || 0);
return remoteMtime && remoteMtime >= localFile.mtimeMs - 1000;
return Number(remoteStat.size) === localFile.size
&& Number(remoteStat.modifyTime || remoteStat.mtime || 0) === previous.remoteMtime;
} catch {
return false;
}
}
async function buildPublicSite() {
await runNodeScript("render-home.mjs");
await runNodeScript("render-knowledge.mjs");
}
function publishJobPercent(job) {
if (job.state === "completed") return 100;
if (!job.totalBytes) return 0;
@@ -1801,6 +1797,7 @@ function publicPublishJob(job) {
id: job.id,
state: job.state,
rendered: job.rendered,
pendingChanges: Boolean(job.rerunRequested),
host: job.host,
remoteRoot: job.remoteRoot,
totalFiles: job.totalFiles,
@@ -1865,7 +1862,9 @@ async function publishProject(options = {}) {
publishing = true;
try {
await hooks.validateDeploy(activeProjectId, projectConfig);
return await performPublish(options);
if (options.job) touchPublishJob(options.job, { state: "building" });
await buildPublicSite();
return await performPublish({ ...options, rendered: true });
} finally { publishing = false; }
}
@@ -1874,7 +1873,17 @@ async function performPublish({ rendered = false, job = null } = {}) {
const files = await collectPublicDeployFiles();
if (!files.length) throw new Error("Нет публичных файлов для публикации");
const client = new SftpClient();
const client = hooks.createSftpClient ? hooks.createSftpClient() : new SftpClient();
const destination = createHash("sha256").update(JSON.stringify([
deployConfig.host, deployConfig.port, deployConfig.username, deployConfig.remoteRoot,
])).digest("hex");
const savedState = await readFile(publishStatePath, "utf8").then(JSON.parse).catch((error) => {
if (error.code === "ENOENT" || error instanceof SyntaxError) return {};
throw error;
});
const previousFiles = savedState.destination === destination ? savedState.files || {} : {};
const nextFiles = {};
const snapshotRoot = await mkdtemp(join(tmpdir(), "dc-cms-publish-"));
const directoryCache = new Set();
const report = {
ok: true,
@@ -1903,6 +1912,18 @@ async function performPublish({ rendered = false, job = null } = {}) {
}
try {
// Freeze bytes for this pass. Edits arriving during transfer schedule a new pass.
if (job) touchPublishJob(job, { state: "scanning", rendered: true });
for (const file of files) {
const snapshotPath = join(snapshotRoot, file.relativePath);
await mkdir(dirname(snapshotPath), { recursive: true });
await copyFile(file.absolutePath, snapshotPath);
file.absolutePath = snapshotPath;
file.size = (await stat(snapshotPath)).size;
file.sha256 = await fileDigest(snapshotPath);
}
report.totalBytes = files.reduce((sum, file) => sum + file.size, 0);
if (job) touchPublishJob(job, { state: "connecting", totalBytes: report.totalBytes });
await client.connect({
host: deployConfig.host,
port: deployConfig.port,
@@ -1927,7 +1948,8 @@ async function performPublish({ rendered = false, job = null } = {}) {
}
await ensureRemoteDirectory(client, remoteParent(remotePath), directoryCache);
if (await shouldSkipRemoteFile(client, file, remotePath)) {
if (await shouldSkipRemoteFile(client, file, remotePath, previousFiles[file.relativePath])) {
nextFiles[file.relativePath] = previousFiles[file.relativePath];
report.skippedFiles += 1;
report.skippedBytes += file.size;
report.processedFiles += 1;
@@ -1954,6 +1976,12 @@ async function performPublish({ rendered = false, job = null } = {}) {
});
},
});
const remoteStat = await client.stat(remotePath);
if (Number(remoteStat.size) !== file.size) throw new Error(`Неполная передача: ${file.relativePath}`);
nextFiles[file.relativePath] = {
sha256: file.sha256,
remoteMtime: Number(remoteStat.modifyTime || remoteStat.mtime || 0),
};
report.uploadedFiles += 1;
report.uploadedBytes += file.size;
report.processedFiles += 1;
@@ -1969,19 +1997,26 @@ async function performPublish({ rendered = false, job = null } = {}) {
}
}
const nextStatePath = `${publishStatePath}.tmp`;
await writeFile(nextStatePath, JSON.stringify({ destination, files: nextFiles }), { mode: 0o600 });
await rename(nextStatePath, publishStatePath);
report.totalLabel = formatProjectSize(report.totalBytes);
report.uploadedLabel = formatProjectSize(report.uploadedBytes);
report.skippedLabel = formatProjectSize(report.skippedBytes);
return report;
} finally {
await client.end().catch(() => {});
await rm(snapshotRoot, { recursive: true, force: true });
}
}
function startPublishJob({ rendered = false } = {}) {
cleanupPublishJobs();
const activeJob = activePublishJob();
if (activeJob) return { job: publicPublishJob(activeJob), reused: true };
if (activeJob) {
touchPublishJob(activeJob, { rerunRequested: true });
return { job: publicPublishJob(activeJob), reused: true };
}
const now = new Date().toISOString();
const job = {
@@ -2011,8 +2046,16 @@ function startPublishJob({ rendered = false } = {}) {
void (async () => {
try {
touchPublishJob(job, { state: "scanning" });
const report = await publishProject({ rendered, job });
let report;
do {
touchPublishJob(job, {
state: "building", rerunRequested: false,
processedFiles: 0, processedBytes: 0, uploadedFiles: 0, uploadedBytes: 0,
skippedFiles: 0, skippedBytes: 0, totalFiles: 0, totalBytes: 0,
currentFile: "", currentFileBytes: 0, currentFileSize: 0,
});
report = await publishProject({ rendered, job });
} while (job.rerunRequested);
touchPublishJob(job, {
state: "completed",
processedFiles: report.totalFiles,
@@ -2061,19 +2104,11 @@ async function recentPublishLog(limit = 20) {
.reverse();
}
async function maybePublishAfterRender(renderResult) {
if (!projectConfig.deploy?.enabled || !projectConfig.deploy?.deployOnRender) {
return {
publish: null,
...renderResult,
};
async function renderAndMaybePublish(scriptName) {
if (projectConfig.deploy?.enabled && projectConfig.deploy?.deployOnRender) {
return { publish: null, publishJob: startPublishJob().job };
}
const publish = await publishProject({ rendered: true });
return {
publish,
...renderResult,
};
return { publish: null, ...(await runNodeScript(scriptName)) };
}
function resolveBrowserEntry(value) {
@@ -2846,6 +2881,60 @@ async function handle(req, res) {
return;
}
if (req.method === "POST" && url.pathname === "/api/project/backup") {
if (!ensureSiteReady(res)) return;
if (backupRunning) {
sendJson(res, 409, { ok: false, error: "Бэкап этого сайта уже готовится или скачивается" });
return;
}
backupRunning = true;
const abort = new AbortController();
const onClose = () => abort.abort();
res.once("close", onClose);
try {
const backup = await createSiteBackup(repoRoot, { required: REQUIRED_SITE_FILES.map(file => file.label), signal: abort.signal });
res.off("close", onClose);
if (res.destroyed) { await backup.cleanup(); backupRunning = false; return; }
const token = randomBytes(24).toString("hex");
const fileName = siteBackupFilename(activeProjectId);
const release = async () => {
if (preparedBackup?.token === token) preparedBackup = null;
try { await backup.cleanup(); } finally { backupRunning = false; }
};
const timer = setTimeout(() => release().catch(error => console.error("Backup cleanup failed", error)), 10 * 60 * 1000);
timer.unref();
preparedBackup = { ...backup, token, fileName, timer, release, claimed: false };
sendJson(res, 200, { ok: true, fileName, files: backup.files, bytes: backup.size, downloadUrl: `/api/project/backup?token=${token}` });
} catch (error) {
res.off("close", onClose); backupRunning = false;
if (!res.destroyed) throw error;
}
return;
}
if (req.method === "GET" && url.pathname === "/api/project/backup") {
const backup = preparedBackup;
if (!backup || backup.claimed || url.searchParams.get("token") !== backup.token) {
sendJson(res, 404, { ok: false, error: "Бэкап недоступен. Нажмите «Скачать бэкап» ещё раз" });
return;
}
backup.claimed = true; clearTimeout(backup.timer);
res.writeHead(200, {
"content-type": "application/zip",
"content-disposition": `attachment; filename="${backup.fileName}"`,
"content-length": backup.size,
"cache-control": "no-store",
"x-content-type-options": "nosniff",
"referrer-policy": "no-referrer",
});
// Native browser download streams an immutable ZIP without a JS Blob.
pipeline(createReadStream(backup.path), res)
.catch(() => {})
.finally(backup.release)
.catch(error => console.error("Backup cleanup failed", error));
return;
}
if (req.method === "POST" && url.pathname === "/api/project/publish") {
if (!ensureSiteReady(res)) return;
const publish = await publishProject();
@@ -2923,6 +3012,21 @@ async function handle(req, res) {
return;
}
if (req.method === "GET" && url.pathname === "/api/media/download") {
let download;
try {
download = await openMediaDownload(repoRoot, url.searchParams.get("path"));
} catch (error) {
const status = error.status || (["ENOENT", "ENOTDIR"].includes(error.code) ? 404 : 500);
sendJson(res, status, { ok: false, error: status === 404 ? "Файл не найден" : status === 500 ? "Не удалось скачать файл" : error.message });
return;
}
res.writeHead(200, download.headers);
// Stream large videos directly to the browser; do not hold a Blob in memory.
pipeline(download.handle.createReadStream(), res).catch(() => {});
return;
}
if (req.method === "GET" && url.pathname === "/api/media/site-size") {
sendJson(res, 200, await calculateProjectSize());
return;
@@ -2954,15 +3058,13 @@ async function handle(req, res) {
if (req.method === "POST" && url.pathname === "/api/render/home") {
if (!ensureSiteReady(res)) return;
const result = await runNodeScript("render-home.mjs");
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-home.mjs")) });
return;
}
if (req.method === "POST" && url.pathname === "/api/render/knowledge") {
if (!ensureSiteReady(res)) return;
const result = await runNodeScript("render-knowledge.mjs");
sendJson(res, 200, { ok: true, ...(await maybePublishAfterRender(result)) });
sendJson(res, 200, { ok: true, ...(await renderAndMaybePublish("render-knowledge.mjs")) });
return;
}
@@ -3041,6 +3143,7 @@ async function handle(req, res) {
}
return {
handle, handleAuthRoute, authorizeRequest,
authEnabled: authConfig.enabled,
config: () => structuredClone(projectConfig),
publicConfig: publicProjectConfig,
root: repoRoot,
+101
View File
@@ -0,0 +1,101 @@
import { constants } from 'node:fs';
import { lstat, mkdtemp, open, readdir, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { crc32 } from 'node:zlib';
const excluded = new Set(['.git', '.cms-backups', '.trash', 'node_modules', '.DS_Store', '__MACOSX']);
const skip = name => excluded.has(name) || name.startsWith('._') || name === '.env' || name.startsWith('.env.') || name.endsWith('.secrets.json');
const fail = (message, status = 409) => Object.assign(new Error(message), { status });
const signature = s => `${s.dev}:${s.ino}:${s.size}:${s.mtimeNs}:${s.ctimeNs}`;
const MAX_BYTES = 2 * 1024 ** 3;
// STORE is intentional: site media is already compressed. Write in bounded
// chunks rather than loading hundreds of MB into the CMS process or blocking it.
export async function createSiteBackup(root, { required = [], signal } = {}) {
async function scan(directory = root, prefix = '') {
signal?.throwIfAborted();
const directoryStat = await lstat(directory);
if (!directoryStat.isDirectory() || directoryStat.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
const result = [];
for (const entry of (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, 'en'))) {
if (skip(entry.name)) continue;
const path = join(directory, entry.name), name = prefix + entry.name;
if (entry.name.includes('\\') || Buffer.byteLength(name) > 65535) throw fail('Недопустимый путь в сайте');
if (entry.isSymbolicLink()) throw fail('Бэкап сайта с символическими ссылками не поддерживается');
if (entry.isDirectory()) result.push(...await scan(path, name + '/'));
else if (entry.isFile()) {
const info = await lstat(path, { bigint: true });
result.push({ name, path, size: Number(info.size), stamp: signature(info), modified: new Date(Number(info.mtimeMs)) });
} else throw fail('Бэкап поддерживает только обычные файлы и папки');
}
return result;
}
const files = await scan();
if (!files.length || files.length > 60000 || files.reduce((n, f) => n + f.size, 0) > MAX_BYTES) throw fail('Бэкап поддерживает сайты до 2 ГБ и 60 000 файлов', 413);
if (required.some(name => !files.some(file => file.name === name))) throw fail('Сайт неполный: отсутствуют файлы для восстановления');
const temp = await mkdtemp(join(tmpdir(), 'dc-cms-backup-'));
const cleanup = () => rm(temp, { recursive: true, force: true });
const path = join(temp, 'site.zip');
let output;
try {
output = await open(path, 'wx', 0o600);
let offset = 0;
const directory = [];
async function write(data, position = offset) {
let written = 0;
while (written < data.length) {
signal?.throwIfAborted();
const result = await output.write(data, written, data.length - written, position + written);
if (!result.bytesWritten) throw fail('Не удалось записать бэкап', 500);
written += result.bytesWritten;
}
offset = Math.max(offset, position + written);
}
for (const file of files) {
signal?.throwIfAborted();
const input = await open(file.path, constants.O_RDONLY | constants.O_NOFOLLOW);
try {
if (signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
const name = Buffer.from(file.name), start = offset, date = file.modified;
const dosTime = (date.getHours() << 11) | (date.getMinutes() << 5) | (date.getSeconds() >> 1);
const dosDate = ((Math.min(2107, Math.max(1980, date.getFullYear())) - 1980) << 9) | ((date.getMonth() + 1) << 5) | date.getDate();
const header = Buffer.alloc(30);
header.writeUInt32LE(0x04034b50, 0); header.writeUInt16LE(20, 4); header.writeUInt16LE(0x800, 6);
header.writeUInt16LE(dosTime, 10); header.writeUInt16LE(dosDate, 12);
header.writeUInt32LE(file.size, 18); header.writeUInt32LE(file.size, 22); header.writeUInt16LE(name.length, 26);
await write(header); await write(name);
let checksum = 0, bytes = 0;
for await (const chunk of input.createReadStream({ autoClose: false, highWaterMark: 256 * 1024 })) {
bytes += chunk.length;
if (bytes > file.size) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
checksum = crc32(chunk, checksum); await write(chunk);
}
if (bytes !== file.size || signature(await input.stat({ bigint: true })) !== file.stamp) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
header.writeUInt32LE(checksum, 14); await write(header, start);
const central = Buffer.alloc(46);
central.writeUInt32LE(0x02014b50, 0); central.writeUInt16LE(20, 4); central.writeUInt16LE(20, 6);
header.copy(central, 8, 6, 28); central.writeUInt32LE(start, 42);
directory.push(central, name);
} finally { await input.close(); }
}
const after = await scan();
if (JSON.stringify(after.map(f => [f.name, f.stamp])) !== JSON.stringify(files.map(f => [f.name, f.stamp]))) throw fail('Сайт изменился во время бэкапа. Повторите скачивание');
const directoryStart = offset;
for (const data of directory) await write(data);
const end = Buffer.alloc(22);
end.writeUInt32LE(0x06054b50, 0); end.writeUInt16LE(files.length, 8); end.writeUInt16LE(files.length, 10);
end.writeUInt32LE(offset - directoryStart, 12); end.writeUInt32LE(directoryStart, 16);
await write(end);
await output.close(); output = null;
return { path, size: offset, files: files.length, cleanup };
} catch (error) {
await output?.close(); await cleanup(); throw error;
}
}
export function siteBackupFilename(projectId, now = new Date()) {
const date = new Intl.DateTimeFormat('en-CA', { timeZone: 'Europe/Moscow', year: 'numeric', month: '2-digit', day: '2-digit' }).format(now);
const id = String(projectId).replace(/[^a-zA-Z0-9-]/g, '').replace(/-/g, '_').toUpperCase() || 'SITE';
return `NODEDC_SITE_${date}_${id}_TECH.zip`;
}
+67
View File
@@ -0,0 +1,67 @@
import { createHash, randomBytes } from 'node:crypto';
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
const fail = () => Object.assign(new Error('Некорректные настройки интерфейса'), { status: 400 });
const object = value => value && typeof value === 'object' && !Array.isArray(value);
const defaults = () => ({ schemaVersion: 1, appearance: { theme: 'dark', accent: null }, gui: { modals: {} } });
export function validatePreferencesPatch(patch) {
if (!object(patch) || Object.keys(patch).some(k => !['appearance', 'gui'].includes(k))) throw fail();
if (patch.appearance !== undefined) {
const a = patch.appearance;
if (!object(a) || Object.keys(a).some(k => !['theme', 'accent'].includes(k))) throw fail();
if (a.theme !== undefined && !['dark', 'light'].includes(a.theme)) throw fail();
if (a.accent !== undefined && a.accent !== null && (typeof a.accent !== 'string' || !/^#[a-f\d]{6}$/i.test(a.accent))) throw fail();
}
if (patch.gui !== undefined) {
if (!object(patch.gui) || Object.keys(patch.gui).some(k => k !== 'modals') || !object(patch.gui.modals)) throw fail();
for (const [key, size] of Object.entries(patch.gui.modals)) {
if (!/^[a-z][a-z0-9-]{0,63}$/.test(key) || ['constructor', 'prototype'].includes(key)) throw fail();
if (size === null) continue;
if (!object(size) || Object.keys(size).length !== 2 || !Number.isInteger(size.width) || !Number.isInteger(size.height) || size.width < 100 || size.height < 100 || size.width > 10000 || size.height > 10000) throw fail();
}
}
return patch;
}
/** Private per-principal metadata, outside all sites, exports and publish roots. */
export class UserPreferencesStore {
#root; #queues = new Map();
constructor(projectsRoot) { this.#root = join(projectsRoot, '.user-meta'); }
#key(principal) {
if (typeof principal !== 'string' || !principal) throw Object.assign(new Error('Требуется вход'), { status: 401 });
return createHash('sha256').update(principal).digest('hex');
}
async read(principal) {
const key = this.#key(principal);
try {
const document = JSON.parse(await readFile(join(this.#root, `${key}.json`), 'utf8'));
if (document.schemaVersion !== 1) throw new Error('Unsupported GUI metadata version');
validatePreferencesPatch({ appearance: document.appearance, gui: document.gui });
return { preferences: document, exists: true };
} catch (error) { if (error.code === 'ENOENT') return { preferences: defaults(), exists: false }; throw error; }
}
async patch(principal, patch, { ifAbsent = false } = {}) {
validatePreferencesPatch(patch);
const key = this.#key(principal);
const pending = (this.#queues.get(key) || Promise.resolve()).then(async () => {
const current = await this.read(principal);
if (ifAbsent && current.exists) return current;
const next = current.preferences;
Object.assign(next.appearance, patch.appearance);
if (next.appearance.accent) next.appearance.accent = next.appearance.accent.toLowerCase();
for (const [id, size] of Object.entries(patch.gui?.modals || {})) {
if (size === null) delete next.gui.modals[id]; else next.gui.modals[id] = size;
}
if (Object.keys(next.gui.modals).length > 64) throw fail();
await mkdir(this.#root, { recursive: true, mode: 0o700 });
const path = join(this.#root, `${key}.json`), temporary = `${path}.${randomBytes(8).toString('hex')}.tmp`;
try { await writeFile(temporary, JSON.stringify(next, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); await rename(temporary, path); }
finally { await rm(temporary, { force: true }); }
return { preferences: next, exists: true };
});
const settled = pending.catch(() => {});
this.#queues.set(key, settled);
try { return await pending; } finally { if (this.#queues.get(key) === settled) this.#queues.delete(key); }
}
}
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, mkdir, writeFile, readFile, rm, symlink, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import AdmZip from 'adm-zip';
import { createSiteBackup, siteBackupFilename } from '../server/site-backup.mjs';
test('backup is a portable current workspace, with UTF-8 paths and exact media bytes', async t => {
const root = await mkdtemp(join(tmpdir(), 'backup-fixture-'));
t.after(() => rm(root, { recursive: true, force: true }));
const files = {
'content/pages/home.json': Buffer.from('{"title":"Current"}'),
'templates/pages/home/shell.html': Buffer.from('<html>current</html>'),
'assets/фото ровера.bin': Buffer.from(Array.from({ length: 700000 }, (_, i) => i % 251)),
'.htaccess': Buffer.from('DirectoryIndex index.html'),
'empty.txt': Buffer.alloc(0),
};
const privateFiles = ['.cms-backups/old.zip', '.git/config', '.env', '.env.local', 'demo.secrets.json', 'assets/.trash/old.png', 'assets/._photo', 'node_modules/package/a.js'];
for (const [name, value] of [...Object.entries(files), ...privateFiles.map(name => [name, Buffer.from('private')])]) {
await mkdir(dirname(join(root, name)), { recursive: true }); await writeFile(join(root, name), value);
}
const backup = await createSiteBackup(root, { required: ['content/pages/home.json'] });
try {
const zip = new AdmZip(await readFile(backup.path));
assert.equal(zip.test(), true);
assert.deepEqual(zip.getEntries().map(e => e.entryName).sort(), Object.keys(files).sort());
for (const [name, value] of Object.entries(files)) assert.deepEqual(zip.readFile(name), value, name);
assert.equal(backup.size, (await stat(backup.path)).size);
assert.equal((await stat(backup.path)).mode & 0o777, 0o600);
} finally { await backup.cleanup(); }
await assert.rejects(stat(backup.path));
assert.equal(await readFile(join(root, '.env'), 'utf8'), 'private');
await assert.rejects(createSiteBackup(root, { required: ['missing.json'] }), /неполный/);
await symlink(join(root, '.env'), join(root, 'linked-secret'));
await assert.rejects(createSiteBackup(root), /символическими/);
await rm(join(root, 'linked-secret'));
const abort = new AbortController(); abort.abort();
await assert.rejects(createSiteBackup(root, { signal: abort.signal }), { name: 'AbortError' });
});
test('backup filename identifies the selected site and Moscow calendar date', () => {
assert.equal(siteBackupFilename('mission-core', new Date('2026-11-05T20:59:00Z')), 'NODEDC_SITE_2026-11-05_MISSION_CORE_TECH.zip');
assert.equal(siteBackupFilename('nodedc', new Date('2026-11-05T21:01:00Z')), 'NODEDC_SITE_2026-11-06_NODEDC_TECH.zip');
});
+78 -1
View File
@@ -81,6 +81,48 @@ test('independent sites, rendering, secrets and publication ownership', async t
assert.equal(await readFile(join(original,'index.html'),'utf8'),'<h1>Original</h1>');
assert.equal(await (await fetch(base+'/s/mission-core/index.html')).text(),'<h1>Mission edited</h1>');
});
await t.test('flat media spans deep asset folders and remains site-scoped', async () => {
const mission = join(projects, 'sites/mission-core');
for (const name of ['assets/top.svg','assets/arbitrary/a/b/deep.webp','assets/other/video.mp4','assets/models/rover.glb','assets/.private/hidden.png','assets/.trash/deleted.png']) {
const path = join(mission, name); await mkdir(join(path,'..'),{recursive:true}); await writeFile(path,'fixture');
}
await symlink(join(original,'index.html'),join(mission,'assets/linked.png'));
const files=(await api('/s/mission-core/api/media/assets')).files;
assert.deepEqual(files.map(f=>f.path).sort(),['assets/arbitrary/a/b/deep.webp','assets/models/rover.glb','assets/other/video.mp4','assets/top.svg']);
assert.ok(files.every(f=>f.type==='file' && f.selectable && f.writable));
assert.deepEqual(new Set(files.map(f=>f.kind)),new Set(['image','video','model']));
assert.equal((await api('/s/nodedc/api/media/assets')).files.length,0);
for (const name of ['top.svg','arbitrary','other','models','.private','.trash','linked.png']) await rm(join(mission,'assets',name),{recursive:true,force:true});
});
await t.test('media downloads keep original bytes, filename and selected-site ownership',async()=>{
for (const [site,expected] of [['nodedc','original-asset'],['mission-core','mission-asset']]) {
const response=await fetch(`${base}/s/${site}/api/media/download?path=assets%2Fproof.txt`);
assert.equal(response.status,200);
assert.match(response.headers.get('content-disposition'),/^attachment; filename="proof.txt"/);
assert.equal(response.headers.get('cache-control'),'no-store');
assert.equal(Number(response.headers.get('content-length')),Buffer.byteLength(expected));
assert.equal(await response.text(),expected);
}
const name='Сессия 1 (оригинал).mp4',bytes=Buffer.from([0,1,2,255,128,0]);
const missionRoot=join(projects,'sites/mission-core');
await writeFile(join(missionRoot,'assets',name),bytes);
const response=await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent('assets/'+name)}`);
assert.equal(response.status,200);
assert.equal(decodeURIComponent(response.headers.get('content-disposition').split("filename*=UTF-8''")[1]),name);
assert.deepEqual(Buffer.from(await response.arrayBuffer()),bytes);
assert.equal((await fetch(`${base}/s/nodedc/api/media/download?path=${encodeURIComponent('assets/'+name)}`)).status,404);
for (const path of ['../nodedc.json','assets/../../nodedc.json','content/pages/home.json','assets/.trash/private','assets/.env','/assets/proof.txt']) {
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent(path)}`)).status,403,path);
}
await symlink(original,join(missionRoot,'assets/other-site'));
await symlink(join(original,'assets/proof.txt'),join(missionRoot,'assets/linked.txt'));
for (const path of ['assets/other-site/assets/proof.txt','assets/linked.txt']) {
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=${encodeURIComponent(path)}`)).status,403,path);
}
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=assets/missing.jpg`)).status,404);
assert.equal((await fetch(`${base}/s/mission-core/api/media/download?path=assets`)).status,403);
for (const path of ['assets/other-site','assets/linked.txt','assets/'+name]) await rm(join(missionRoot,path));
});
await t.test('preview root links stay within their selected site',async()=>{
const page=await (await fetch(base+'/s/mission-core/knowledge/')).text();
assert.match(page,/href="\/s\/mission-core\/knowledge\/fleet\/"/);
@@ -110,6 +152,31 @@ test('independent sites, rendering, secrets and publication ownership', async t
assert.equal((await fetch(base+'/s/mission-core/api/project/upload-site',{method:'POST',body:invalid})).status,500);
assert.equal((await api('/s/mission-core/api/page/home')).title,'Mission edited');
});
await t.test('downloaded backup is current, isolated and can be imported unchanged',async()=>{
const beforePage=await api('/s/mission-core/api/page/home');
const prepared=await api('/s/mission-core/api/project/backup','POST');
await api('/s/mission-core/api/project/backup','POST',undefined,409);
const response=await fetch(base+'/s/mission-core'+prepared.downloadUrl);
assert.equal(response.status,200);assert.equal(response.headers.get('content-type'),'application/zip');
assert.match(response.headers.get('content-disposition'),/MISSION_CORE_TECH\.zip/);
assert.equal(response.headers.get('cache-control'),'no-store');
const bytes=Buffer.from(await response.arrayBuffer());const zip=new AdmZip(bytes);
assert.equal(bytes.length,Number(response.headers.get('content-length')));assert.equal(zip.test(),true);
assert.equal((await fetch(base+'/s/mission-core'+prepared.downloadUrl)).status,404);
assert.deepEqual(JSON.parse(zip.readAsText('content/pages/home.json')),beforePage);
assert.ok(zip.getEntry('tools/render-home.mjs'));assert.ok(zip.getEntry('templates/pages/home/shell.html'));
assert.ok(!zip.getEntries().some(e=>/\.cms-backups|\.git\/|secrets|publish-state/.test(e.entryName)));
const preparedAgent=await api('/s/nodedc/api/project/backup','POST');
assert.equal((await fetch(base+'/s/mission-core'+preparedAgent.downloadUrl)).status,404);
const agentResponse=await fetch(base+'/s/nodedc'+preparedAgent.downloadUrl);assert.equal(agentResponse.status,200);
const agentZip=new AdmZip(Buffer.from(await agentResponse.arrayBuffer()));
assert.equal(JSON.parse(agentZip.readAsText('content/pages/home.json')).title,'Agent edited');
const form=new FormData();form.append('file',new Blob([bytes],{type:'application/zip'}),'restored.zip');
const restored=await fetch(base+'/s/mission-core/api/project/upload-site',{method:'POST',body:form});
assert.equal(restored.status,200);assert.equal((await restored.json()).site.ready,true);
assert.deepEqual(await api('/s/mission-core/api/page/home'),beforePage);
assert.equal((await api('/s/nodedc/api/page/home')).title,'Agent edited');
});
await t.test('encrypted credentials transfer with source disabled',async()=>{
const config=await api('/s/nodedc/api/project/config');
await api('/s/nodedc/api/project/config','PUT',{...config,deploy:{...config.deploy,enabled:true}});
@@ -133,13 +200,23 @@ test('independent sites, rendering, secrets and publication ownership', async t
await t.test('cross-origin registry mutations are refused',async()=>{
const response=await fetch(base+'/api/sites',{method:'POST',headers:{origin:'https://untrusted.invalid','content-type':'application/json'},body:JSON.stringify({id:'attack',copyFrom:'nodedc'})});assert.equal(response.status,403);
});
await t.test('GUI preferences persist outside sites and reject cross-origin writes', async () => {
assert.equal((await api('/api/user/preferences')).exists, false);
await api('/api/user/preferences','PATCH',{gui:{modals:{'media-library':{width:1200,height:800}}}});
await api('/api/user/preferences','PATCH',{appearance:{theme:'light'}});
const response = await fetch(base+'/api/user/preferences',{method:'PATCH',headers:{origin:'https://untrusted.invalid','content-type':'application/json'},body:'{}'});
assert.equal(response.status,403);
assert.equal((await api('/api/sites')).sites.length,2);
});
await stop(); await start();
await t.test('registry and edits survive server restart',async()=>{
assert.equal((await api('/api/user/preferences')).preferences.gui.modals['media-library'].width,1200);
assert.equal((await api('/api/sites')).sites.length,2);assert.equal((await api('/s/mission-core/api/page/home')).title,'Mission edited');assert.equal((await api('/s/nodedc/api/page/home')).title,'Agent edited');
});
await stop();await start(true);
await t.test('registry, scoped content and preview retain authentication',async()=>{
for(const path of ['/api/sites','/s/mission-core/api/page/home']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
for(const path of ['/api/user/preferences','/api/sites','/s/mission-core/api/page/home','/s/mission-core/api/project/backup','/s/mission-core/api/media/download?path=assets/proof.txt']){const response=await fetch(base+path,{redirect:'manual'});assert.equal(response.status,401,path);assert.match(response.headers.get('content-type'),/json/);}
assert.equal((await fetch(base+'/s/mission-core/api/project/backup',{method:'POST',redirect:'manual'})).status,401);
assert.equal((await fetch(base+'/s/mission-core/index.html',{redirect:'manual'})).status,302);
assert.equal((await fetch(base+'/healthz')).status,200);
});
+126
View File
@@ -0,0 +1,126 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { once } from 'node:events';
import { mkdtemp, mkdir, readFile, writeFile, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join, dirname } from 'node:path';
import { createSiteApplication } from '../server/site-app.mjs';
const deferred = () => { let resolve; const promise = new Promise(r => resolve = r); return { promise, resolve }; };
test('save/render publication builds current content and reliably sends changes', async t => {
const root = await mkdtemp(join(tmpdir(), 'cms-publication-test-'));
const site = join(root, 'site');
const configPath = join(root, 'mission.json');
const fixtures = {
'content/pages/home.json': JSON.stringify({ title: 'Alpha', seo: 'SEO A', regions: [] }),
'content/knowledge.json': JSON.stringify({ title: 'Knowledge A' }),
'content/block-templates/home.json': '[]',
'templates/pages/home/shell.html': '<html></html>',
'tools/render-home.mjs': 'import {readFile,writeFile} from "node:fs/promises";const p=JSON.parse(await readFile("content/pages/home.json"));await writeFile("index.html",`<title>${p.seo}</title><h1>${p.title}</h1><img src="assets/photo.png">`);',
'tools/render-knowledge.mjs': 'import {readFile,writeFile,mkdir} from "node:fs/promises";const k=JSON.parse(await readFile("content/knowledge.json"));await mkdir("knowledge",{recursive:true});await writeFile("knowledge/index.html",`<h1>${k.title}</h1>`);',
'index.html': 'stale HTML',
'assets/photo.png': 'image-a',
};
for (const [path, value] of Object.entries(fixtures)) {
await mkdir(dirname(join(site, path)), { recursive: true });
await writeFile(join(site, path), value);
}
await writeFile(configPath, JSON.stringify({ id: 'mission', name: 'Mission', siteRoot: site, deploy: { enabled: false } }));
const remote = new Map(); const uploads = [];
let connectCount = 0, failTransfer = false, gate = null;
const app = await createSiteApplication({ projectId: 'mission', projectRoot: site, projectsRoot: root, hooks: {
transaction: fn => fn(), validateDeploy: async () => {},
writeConfig: async (_id, value) => writeFile(configPath, JSON.stringify(value)),
createSftpClient: () => ({
connect: async () => { connectCount++; }, mkdir: async () => {}, end: async () => {},
stat: async path => { if (!remote.has(path)) throw new Error('missing'); return { size: remote.get(path).length, modifyTime: 1000 }; },
fastPut: async (local, path, options) => {
if (failTransfer) throw new Error('fixture SFTP rejected transfer');
if (gate) { const current = gate; gate = null; current.entered.resolve(); await current.release.promise; }
const data = await readFile(local); remote.set(path, data); uploads.push(path); options.step(data.length);
},
}),
} });
const server = createServer(app.handle); server.listen(0, '127.0.0.1'); await once(server, 'listening');
t.after(async () => { await new Promise(resolve => server.close(resolve)); await rm(root, { recursive: true, force: true }); });
const base = `http://127.0.0.1:${server.address().port}`;
async function api(path, method = 'GET', body) {
const response = await fetch(base + path, { method, headers: { 'content-type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) });
const payload = await response.json(); assert.ok(response.ok, JSON.stringify(payload)); return payload;
}
async function configure(enabled = true, automatic = true) {
const config = await api('/api/project/config');
return api('/api/project/config', 'PUT', { ...config, deploy: { ...config.deploy, enabled, deployOnRender: automatic, method: 'sftp', host: 'fixture.invalid', port: 22, username: 'test', password: 'test-only', remotePath: 'httpdocs' } });
}
async function finished(id) {
const deadline = Date.now() + 10000;
while (Date.now() < deadline) {
const { job } = await api(`/api/project/publish/status?jobId=${id}`);
if (['completed', 'failed'].includes(job.state)) return job;
await new Promise(resolve => setTimeout(resolve, 15));
}
throw new Error('publication timeout');
}
const text = path => remote.get(`httpdocs/${path}`)?.toString();
await configure();
await t.test('manual Publish builds both pages instead of uploading stale HTML', async () => {
const { job } = await api('/api/project/publish/start', 'POST');
assert.equal((await finished(job.id)).state, 'completed');
assert.match(text('index.html'), /Alpha/); assert.equal(text('knowledge/index.html'), '<h1>Knowledge A</h1>');
assert.equal(text('assets/photo.png'), 'image-a');
assert.ok(![...remote.keys()].some(path => /content|secrets|publish-state/.test(path)));
});
await t.test('one-letter content/SEO and same-size image edits are not skipped; unchanged files are', async () => {
const before = uploads.length;
await api('/api/page/home', 'PUT', { title: 'Alphb', seo: 'SEO B', regions: [] });
await writeFile(join(site, 'assets/photo.png'), 'image-b');
const result = await api('/api/render/home', 'POST');
assert.ok(result.publishJob.id); const job = await finished(result.publishJob.id);
assert.equal(job.state, 'completed'); assert.equal(job.uploadedFiles, 2); assert.equal(job.skippedFiles, 1);
assert.match(text('index.html'), /Alphb/); assert.match(text('index.html'), /SEO B/);
assert.equal(text('assets/photo.png'), 'image-b'); assert.equal(uploads.length - before, 2);
});
await t.test('knowledge Save/render publishes its updated page', async () => {
await api('/api/knowledge', 'PUT', { title: 'Knowledge B' });
const result = await api('/api/render/knowledge', 'POST'); const job = await finished(result.publishJob.id);
assert.equal(job.state, 'completed'); assert.equal(job.uploadedFiles, 1);
assert.equal(text('knowledge/index.html'), '<h1>Knowledge B</h1>');
});
await t.test('edits saved during an active transfer trigger another pass and preserve newest revision', async () => {
await api('/api/page/home', 'PUT', { title: 'First', seo: 'SEO C', regions: [] });
const blocked = { entered: deferred(), release: deferred() }; gate = blocked;
const first = await api('/api/render/home', 'POST');
await blocked.entered.promise;
await api('/api/page/home', 'PUT', { title: 'Latest', seo: 'SEO D', regions: [] });
await writeFile(join(site, 'assets/photo.png'), 'image-c');
const second = await api('/api/render/home', 'POST');
assert.equal(first.publishJob.id, second.publishJob.id); assert.equal(second.publishJob.pendingChanges, true);
blocked.release.resolve();
assert.equal((await finished(first.publishJob.id)).state, 'completed');
assert.match(text('index.html'), /Latest/); assert.match(text('index.html'), /SEO D/); assert.equal(text('assets/photo.png'), 'image-c');
});
await t.test('SFTP failure is terminal and visible; retry rebuilds and sends pending changes', async () => {
await api('/api/knowledge', 'PUT', { title: 'Knowledge C' }); failTransfer = true;
const result = await api('/api/render/knowledge', 'POST'); const failed = await finished(result.publishJob.id);
assert.equal(failed.state, 'failed'); assert.match(failed.error, /SFTP rejected/);
assert.equal(text('knowledge/index.html'), '<h1>Knowledge B</h1>');
failTransfer = false;
const retry = await api('/api/project/publish/start', 'POST'); assert.equal((await finished(retry.job.id)).state, 'completed');
assert.equal(text('knowledge/index.html'), '<h1>Knowledge C</h1>');
});
await t.test('build failure never transfers stale pages', async () => {
const before = connectCount; await writeFile(join(site, 'tools/render-home.mjs'), 'throw new Error("broken template")');
const { job } = await api('/api/project/publish/start', 'POST');
assert.equal((await finished(job.id)).state, 'failed'); assert.equal(connectCount, before);
await writeFile(join(site, 'tools/render-home.mjs'), fixtures['tools/render-home.mjs']);
});
await t.test('disabled Agent-style deployment only rebuilds preview', async () => {
await configure(false); const before = connectCount;
await api('/api/page/home', 'PUT', { title: 'Local', seo: '', regions: [] });
const result = await api('/api/render/home', 'POST');
assert.equal(result.publish, null); assert.equal(result.publishJob, undefined); assert.equal(connectCount, before);
assert.match(await readFile(join(site, 'index.html'), 'utf8'), /Local/); assert.match(text('index.html'), /Latest/);
});
});
+33
View File
@@ -0,0 +1,33 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp, readdir, readFile, rm, stat } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { UserPreferencesStore } from '../server/user-preferences.mjs';
test('user GUI metadata is isolated, durable, private and merges independent writes', async t => {
const root = await mkdtemp(join(tmpdir(), 'cms-user-meta-')); t.after(() => rm(root, { recursive: true, force: true }));
const store = new UserPreferencesStore(root);
assert.equal((await store.read('alice')).exists, false);
await Promise.all([
store.patch('alice', { appearance: { theme: 'light', accent: '#AABBCC' } }),
store.patch('alice', { gui: { modals: { 'media-library': { width: 1250, height: 800 } } } }),
store.patch('bob', { gui: { modals: { 'media-library': { width: 640, height: 480 } } } }),
]);
const restarted = new UserPreferencesStore(root);
const alice = (await restarted.read('alice')).preferences;
assert.equal(alice.appearance.theme, 'light'); assert.equal(alice.appearance.accent, '#aabbcc');
assert.deepEqual(alice.gui.modals['media-library'], {width:1250,height:800});
assert.equal((await restarted.read('bob')).preferences.gui.modals['media-library'].width, 640);
assert.deepEqual((await restarted.patch('alice', { appearance: { theme: 'dark' } }, { ifAbsent: true })).preferences, alice);
const files = await readdir(join(root,'.user-meta')); assert.equal(files.length, 2);
for (const file of files) {
assert.match(file, /^[a-f\d]{64}\.json$/);
assert.equal((await stat(join(root,'.user-meta',file))).mode & 0o777, 0o600);
assert.ok(JSON.parse(await readFile(join(root,'.user-meta',file))).gui);
}
for (const patch of [{ user: 'bob' }, { gui: { modals: { '../evil': {width:900,height:600} } } }, { gui: {modals: {'media-library': {width:1e7,height:800}}} }, {appearance:{accent:'red'}}, JSON.parse('{"gui":{"modals":{"__proto__":null}}}')]) {
await assert.rejects(store.patch('alice', patch), {status:400});
}
await assert.rejects(store.read(''), { status: 401 });
assert.deepEqual((await store.read('alice')).preferences, alice);
});
+4 -4
View File
@@ -20,7 +20,7 @@ const header = h(AppHeader, {
brand: h("img", { src: "./nodedc-logo.svg", alt: "NODE.DC" }),
brandMonochrome: true,
left: ib("toggle-navigation", "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C \u0440\u0430\u0437\u0434\u0435\u043B\u044B", "panel"),
center: h(HeaderNavigation, { label: "\u0420\u0430\u0437\u0434\u0435\u043B\u044B CMS", value: "content", onChange: noop, items: [["content", "\u041A\u043E\u043D\u0442\u0435\u043D\u0442"], ["seo", "SEO"], ["knowledge", "\u0411\u0430\u0437\u0430 \u0437\u043D\u0430\u043D\u0438\u0439"]].map(([value, label]) => ({ value, label: h("span", { "data-cms-mode": value }, label) })) }),
center: h(HeaderNavigation, { label: "\u0420\u0430\u0437\u0434\u0435\u043B\u044B CMS", value: "content", onChange: noop, items: [["content", "\u041A\u043E\u043D\u0442\u0435\u043D\u0442"], ["seo", "SEO"], ["knowledge", "\u0411\u0430\u0437\u0430 \u0437\u043D\u0430\u043D\u0438\u0439"], ["files", "Файлы"]].map(([value, label]) => ({ value, label: h("span", { "data-cms-mode": value }, label) })) }),
right: h("span", { id: "cms-profile", className: "cms-ui-island" })
});
const siteContext = h("div", { className: "cms-site-context" },
@@ -32,11 +32,11 @@ const siteContext = h("div", { className: "cms-site-context" },
h("span", { id: "cms-add-block-parking", hidden: true }, ib("add-block", "Добавить блок", "plus"))
);
const nav = h(AdminNavigationPanel, { eyebrow: "NODE.DC / CMS", title: h("span", { id: "sidebar-title" }, "\u0410\u0434\u043C\u0438\u043D\u0438\u0441\u0442\u0440\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435"), headerActions: ib("add-project", "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442", "plus"), contextSlot: siteContext, items: [], onClose: noop, onItemChange: noop });
const actions = h("div", { className: "cms-editor-actions" }, h(StatusBadge, { id: "dirty-state", "data-dirty": "false" }, "\u0421\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E"), ib("reload", "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435", "refresh"), btn("save", "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C", "primary"), btn("render", "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442"), h(Button, { id: "publish", className: "hidden", tone: "neutral" }, "\u041E\u043F\u0443\u0431\u043B\u0438\u043A\u043E\u0432\u0430\u0442\u044C"));
const actions = h("div", { className: "cms-editor-actions" }, h(StatusBadge, { id: "dirty-state", "data-dirty": "false" }, "\u0421\u0438\u043D\u0445\u0440\u043E\u043D\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043E"), ib("reload", "\u041F\u0435\u0440\u0435\u0437\u0430\u0433\u0440\u0443\u0437\u0438\u0442\u044C \u0434\u0430\u043D\u043D\u044B\u0435", "refresh"), btn("save", "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u043C\u043E\u0434\u0435\u043B\u044C", "primary"), btn("render", "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0430\u0439\u0442"), h(Button, { id: "publish", className: "hidden", tone: "neutral" }, "\u041E\u043F\u0443\u0431\u043B\u0438\u043A\u043E\u0432\u0430\u0442\u044C"), h(Button, {id: "download-backup", variant: "secondary", tone: "neutral", className: "hidden"}, "Скачать бэкап"));
const content = h(ApplicationPanel, { eyebrow: h("span", { id: "editor-heading" }, "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 \u0441\u0430\u0439\u0442\u0430"), title: "\u041A\u043E\u043D\u0442\u0435\u043D\u0442", description: "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435 \u0440\u0430\u0437\u0434\u0435\u043B", headerTools: actions, expanded: true, onClose: noop }, h("div", { className: "cms-editor", dangerouslySetInnerHTML: { __html: await read("editor.html") } }));
const shell = html(h(ApplicationShell, { id: "cms-shell", header, stage: h("div", { className: "cms-stage" }, h("p", null, "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0430\u0439\u0442\u0430\u043C\u0438 NODE.DC"), btn("open-navigation", "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0440\u0430\u0437\u0434\u0435\u043B\u044B")), navigation: nav, content, navigationOpen: true, contentOpen: true, contentExpanded: true }));
const icons = ["close", "plus", "chevron-up", "chevron-down", "copy", "clipboard", "trash", "eye", "eye-off", "layers", "panel", "file", "settings", "folder", "image", "video", "refresh", "move", "edit"];
const templates = Object.entries({ nestedSurface: h(GlassSurface, {tone:"soft", padding:"md", materialRim:false}, h("span")), dragHandle: h(DragHandle, {label:"Перетащить блок"}), button: h(Button, null, "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435"), iconButton: h(IconButton, { label: "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435" }, icon("plus")), field: h(FieldFrame, { label: "\u041F\u043E\u043B\u0435" }, h("span", { "data-slot": "control" })), text: h(TextField, { id: "template-field", label: "\u041F\u043E\u043B\u0435" }), card: h(SettingsCard, { eyebrow: "\u0420\u0430\u0437\u0434\u0435\u043B", title: "\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435", description: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435" }, h("div", { "data-slot": "body" })), media: h(MediaSourceField, { label: "\u041C\u0435\u0434\u0438\u0430", source: "file", url: "", onSourceChange: noop, onUrlChange: noop, onFileChange: noop }), ...Object.fromEntries(icons.map((name) => ["icon-" + name, icon(name)])) }).map(([name, node]) => `<template id="ds-${name}">${html(node)}</template>`).join("\n");
const icons = ["close", "plus", "chevron-up", "chevron-down", "copy", "clipboard", "trash", "eye", "eye-off", "layers", "panel", "file", "settings", "folder", "image", "video", "refresh", "move", "edit", "grid"];
const templates = Object.entries({ settingRow: h(SettingsCard, { title: "Настройка", actions: h("span", { "data-slot": "control" }) }), nestedSurface: h(GlassSurface, {tone:"group", padding:"md", materialRim:false}, h("span")), dragHandle: h(DragHandle, {label:"Перетащить блок"}), button: h(Button, null, "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435"), iconButton: h(IconButton, { label: "\u0414\u0435\u0439\u0441\u0442\u0432\u0438\u0435" }, icon("plus")), field: h(FieldFrame, { label: "\u041F\u043E\u043B\u0435" }, h("span", { "data-slot": "control" })), text: h(TextField, { id: "template-field", label: "\u041F\u043E\u043B\u0435" }), card: h(SettingsCard, { eyebrow: "\u0420\u0430\u0437\u0434\u0435\u043B", title: "\u041D\u0430\u0437\u0432\u0430\u043D\u0438\u0435", description: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435" }, h("div", { "data-slot": "body" })), media: h(MediaSourceField, { label: "\u041C\u0435\u0434\u0438\u0430", source: "file", url: "", onSourceChange: noop, onUrlChange: noop, onFileChange: noop }), ...Object.fromEntries(icons.map((name) => ["icon-" + name, icon(name)])) }).map(([name, node]) => `<template id="ds-${name}">${html(node)}</template>`).join("\n");
const page = `<!doctype html>
<html lang="ru" data-nodedc-ui="true" data-nodedc-theme="dark" data-nodedc-appearance="mission" data-nodedc-edges="flat"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="design-system-commit" content="${lock.sourceCommit}"><title>NODE.DC \u2014 CMS</title><link rel="stylesheet" href="./admin.css"></head><body>${shell}
${await read("modals.html")}
+8 -5
View File
@@ -1,11 +1,14 @@
{
"repository": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
"sourceCommit": "3750a9420058fb76880cd73bb9f2d106d7cd10d5",
"sourceCommit": "189bb7037740f577cc65e72f2b7c07651201ef19",
"distribution": "immutable npm pack artifacts; no copied component sources",
"packages": {
"nodedc-tokens-0.6.0-mission.1.tgz": "2ed76a0e68edacac0ad6c105e8f382730f4bc87ae437728f02b17fe71c63354a",
"nodedc-ui-core-0.7.0-mission.1.tgz": "e533d936aaf46cfd0f0cc7681de2df6db47434c5cf922d456b9dc2a4d37431e8",
"nodedc-ui-dom-0.7.0-mission.1.tgz": "7865b0fabe13e08196e9edecf02bf74443385986b4aa636cb422b2f7a4bc7228",
"nodedc-ui-react-0.7.0-mission.1.tgz": "75663592cfc1cb4fab77454801a6d9e053a8f4a30b52c5ad24e6b100c231fc6c"
"nodedc-tokens-0.6.0-mission.2.tgz": "11386a46868f8e7dafa2743770d15dc201e1df46d036921f03475c15a7351b9c",
"nodedc-ui-core-0.7.0-mission.2.tgz": "6360deed064a7c3c5af9538fac38a31f9937d4521153705375c431e7afd56fe8",
"nodedc-ui-react-0.7.0-mission.2.tgz": "cecf33a767e4c998e8c5cbcc70b20936844460424790d0a81aefa847c45f662e",
"nodedc-ui-dom-0.7.0-modal.2.tgz": "85667985b73fd88855c64e446905e6bf24f7143fdf8c08920f5776940af3607e"
},
"packageSourceCommits": {
"nodedc-ui-dom-0.7.0-modal.2.tgz": "1326ec6cc9ee0a2f4f3e75eaf4e22250c3fbafe5"
}
}
+5 -2
View File
@@ -56,13 +56,12 @@
<span>Поиск</span>
<input id="media-search" type="search" autocomplete="off" placeholder="Имя, папка, путь" />
</label>
<div id="media-kind-filters" class="media-filter-row media-kind-row" aria-label="Тип файла"></div>
<div class="media-kind-row"><div id="media-kind-filters" class="media-filter-row" role="group" aria-label="Типы файлов"></div><span id="media-results" class="nodedc-description" role="status"></span><button id="media-flat-toggle" class="nodedc-icon-button" type="button" aria-label="Все файлы без папок" aria-pressed="false"></button></div>
<div id="media-root-filters" class="media-filter-row media-root-row" aria-label="Корень файлов"></div>
<button id="media-upload" class="primary-btn media-upload-btn" type="button">+ Загрузить</button>
</div>
<div id="media-drop-zone" class="media-browser media-browser-columns">
<section class="media-main">
<div id="media-breadcrumbs" class="media-breadcrumbs"></div>
<div id="media-list" class="media-columns"></div>
<div id="media-empty" class="media-empty hidden">Папка пуста.</div>
</section>
@@ -81,6 +80,7 @@
</div>
<div class="media-preview-actions">
<button id="media-select" class="primary-btn" type="button" disabled>Выбрать</button>
<button id="media-download" class="ghost-btn" type="button" disabled>Скачать</button>
<button id="media-delete" class="danger-btn media-delete-btn" type="button" aria-label="Удалить файл" title="Удалить файл" disabled>
<svg viewBox="0 0 24 24" aria-hidden="true">
<path d="M3.75 6.75h16.5" />
@@ -93,7 +93,10 @@
</div>
</aside>
</div>
<nav id="media-breadcrumbs"></nav>
<footer class="template-modal-foot media-modal-foot">
<span id="media-size-status" class="nodedc-description" role="status">Размер окна сохраняется в профиле</span>
<button id="media-size-retry" class="ghost-btn" type="button" hidden>Повторить</button>
<button id="media-refresh" class="ghost-btn" type="button">Обновить список</button>
<button id="media-modal-cancel" class="ghost-btn" type="button">Отмена</button>
</footer>
+12 -12
View File
@@ -6,10 +6,10 @@
"": {
"name": "dc-cms-ui-build",
"dependencies": {
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.1.tgz",
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.1.tgz",
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-mission.1.tgz",
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.1.tgz",
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz",
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.2.tgz",
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-modal.2.tgz",
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
"esbuild": "0.28.1",
"react": "19.2.7",
"react-dom": "19.2.7"
@@ -486,29 +486,29 @@
},
"node_modules/@nodedc/tokens": {
"version": "0.6.0",
"resolved": "file:vendor/nodedc-tokens-0.6.0-mission.1.tgz",
"integrity": "sha512-8hoq5hjMTvcCZMFRnKHD9/DYIJ4MaywBn69y7dgJI1Kwtuj2AtoxI9fRN8JTZ6hBiRv0lvmi23ogmzLkF4EWLg=="
"resolved": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz",
"integrity": "sha512-rLi+Ft8rewkfSPycnDXwHePv4cDvX91ALLmauHNrxmkmBqQWdqpEsTmnm7stLkASoEfavKVcuCdNNjMiTL9POA=="
},
"node_modules/@nodedc/ui-core": {
"version": "0.7.0",
"resolved": "file:vendor/nodedc-ui-core-0.7.0-mission.1.tgz",
"integrity": "sha512-C3/orF7aUvrFq5fAOxrWd8a+uxLvpj9QppDf1kJyERsDTScHRwWIaMDhBzxytQc5rV4lZ/Ovp5wYTMC9PyhMWQ==",
"resolved": "file:vendor/nodedc-ui-core-0.7.0-mission.2.tgz",
"integrity": "sha512-CzCdx1sUngTqhZLX4AUHh754csEiqiOp9le4hhrGI6s4ovFXd+RF4WH2vbkkanQifRJlpTl29Zfu4J40x2a6bA==",
"dependencies": {
"@nodedc/tokens": "0.6.0"
}
},
"node_modules/@nodedc/ui-dom": {
"version": "0.7.0",
"resolved": "file:vendor/nodedc-ui-dom-0.7.0-mission.1.tgz",
"integrity": "sha512-s744E1rpjhVVwGqvEzZCwewkk67hetrOz5exSfXILMKKwnz0hhFoXyhUfZhAEvO8aCiWeBr4sH56P/lCck1bIA==",
"resolved": "file:vendor/nodedc-ui-dom-0.7.0-modal.2.tgz",
"integrity": "sha512-2uR0Ufk+Ocv5t1phemMPtMub+ogSfqEp70emVKDILOJ62XxZqHQL9Seuug32AWf6AMsEjD3U7y0BoAp+XuD5lw==",
"dependencies": {
"@nodedc/ui-core": "0.7.0"
}
},
"node_modules/@nodedc/ui-react": {
"version": "0.7.0",
"resolved": "file:vendor/nodedc-ui-react-0.7.0-mission.1.tgz",
"integrity": "sha512-aJ/5dq7Yoghk9GP3+uJRxPnCQHTdhU8lgE0p/+/8OZiE+5GnT71ElFZyCwtTgFcysunM4xcnVThzfY2UXkEOmw==",
"resolved": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
"integrity": "sha512-br7JmWo1NHnUrSdW1rApJU4HSBx2evVTjeTqKWZJMRlmasfhGg+OPx/mNgjEksYfNzMchfUj0NZNQwaf+7Uv4w==",
"dependencies": {
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
+4 -4
View File
@@ -7,10 +7,10 @@
"check": "node build.mjs --check"
},
"dependencies": {
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.1.tgz",
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.1.tgz",
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-mission.1.tgz",
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.1.tgz",
"@nodedc/tokens": "file:vendor/nodedc-tokens-0.6.0-mission.2.tgz",
"@nodedc/ui-core": "file:vendor/nodedc-ui-core-0.7.0-mission.2.tgz",
"@nodedc/ui-dom": "file:vendor/nodedc-ui-dom-0.7.0-modal.2.tgz",
"@nodedc/ui-react": "file:vendor/nodedc-ui-react-0.7.0-mission.2.tgz",
"react": "19.2.7",
"react-dom": "19.2.7",
"esbuild": "0.28.1"
+360 -224
View File
File diff suppressed because it is too large Load Diff
+41
View File
@@ -1,3 +1,4 @@
@import "@nodedc/ui-dom/styles.css";
/* CMS domain layout; component geometry and materials belong to @nodedc/ui-core. */
@import "@nodedc/ui-core/styles.css";
* {
@@ -62,6 +63,7 @@ p {
min-width: 0;
}
.cms-editor,
.cms-content-section,
.block-form,
.knowledge-editor,
.project-settings-editor,
@@ -85,6 +87,19 @@ p {
.field-control {
min-width: 0;
}
.seo-media-controls {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: var(--nodedc-space-2);
}
.seo-media-controls input {
flex: 1 1 16rem;
min-width: 0;
}
.seo-media-controls button {
max-width: 100%;
}
.field-kind,
.field-path,
.block-meta {
@@ -413,7 +428,9 @@ dialog.site-dialog p {
}
.media-kind-row {
grid-column: 1/-1;
display: flex; align-items: center; gap: var(--nodedc-space-2);
}
#media-flat-toggle { margin-inline-start: auto; }
.media-root-row {
grid-column: 1;
}
@@ -435,6 +452,18 @@ dialog.site-dialog p {
gap: var(--nodedc-space-4);
min-height: 20rem;
}
.media-modal > .nodedc-window__body {
display: flex;
flex-direction: column;
min-height: 0;
}
.media-modal .media-browser { flex: 1; min-height: 12rem; }
.media-modal .media-main { display: flex; flex-direction: column; min-height: 0; }
.media-modal .media-columns { flex: 1; min-height: 0; }
.media-modal .media-column { max-height: none; }
.media-modal .media-preview-panel { overflow: auto; }
.media-modal-foot { flex-wrap: wrap; }
#media-size-status { margin-inline-end: auto; }
.media-main {
min-width: 0;
overflow: hidden;
@@ -751,3 +780,15 @@ dialog.site-dialog p {
min-width: 0;
max-width: 100%;
}
.media-gallery { display: grid; grid-template-columns: repeat(auto-fill, minmax(150px, 1fr)); gap: var(--nodedc-space-3); overflow: auto; min-height: 0; flex: 1; align-content: start; }
.media-gallery .media-entry { display: flex; flex-direction: column; align-items: stretch; position: relative; border-radius: var(--nodedc-radius-card); min-width: 0; }
.media-gallery .media-entry-icon { width: 100%; height: 8rem; border-radius: var(--nodedc-radius-control-compact); background: var(--nodedc-surface-group); }
.media-gallery .media-entry-icon img { width: 100%; height: 100%; min-height: 0; max-height: 8rem; object-fit: contain; }
.media-gallery .media-entry-icon > svg { width: 2rem; height: 2rem; }
.media-gallery .media-entry-copy { flex: none; }
.media-gallery .media-entry-path { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; order: 3; }
.media-gallery .media-entry-status { position: absolute; top: var(--nodedc-space-3); right: var(--nodedc-space-3); }
.media-gallery .media-entry-arrow { display: none; }
.media-modal .media-gallery { min-height: 0; }
.media-modal #media-breadcrumbs { margin-block-start: var(--nodedc-space-2); }
+41 -9
View File
@@ -2,9 +2,10 @@
import React from "react";
import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { Select, Switch, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react";
import { Select, Switch, ColorField, RangeControl, ProgressBar, Dropdown, IconButton, Icon, StatusBadge } from "@nodedc/ui-react";
import { installPreferences } from "./preferences.mjs";
import { createApplicationWorkspaceController, createModalController } from "@nodedc/ui-dom";
import { createApplicationWorkspaceController, createModalController, createModalSizeController } from "@nodedc/ui-dom";
import { guiPreferences } from './gui-preferences.mjs';
const h = React.createElement, $ = (s, r = document) => r.querySelector(s), all = (s, r = document) => [...r.querySelectorAll(s)];
const clone = (name) => $(`#ds-${name}`).content.firstElementChild.cloneNode(true);
function addClass(node, name) {
@@ -100,6 +101,24 @@ function ranges() {
} })));
}
}
function colors() {
for (const input of all("input[data-color-field]")) {
const item = island(input);
const label = input.dataset.colorField;
const signature = JSON.stringify([label, input.value]);
if (item.signature === signature) continue;
item.signature = signature;
flushSync(() => item.root.render(h(ColorField, {
label,
value: input.value,
onChange: value => {
input.value = value;
input.dispatchEvent(new Event("input", { bubbles: true }));
schedule();
},
})));
}
}
function progress() {
for (const track of all(".publish-progress-track")) {
const item = island(track), value = Number(track.getAttribute("aria-valuenow") || 0);
@@ -135,12 +154,10 @@ function fields() {
for (const input of all("input:not([type=hidden]):not([type=checkbox]):not([type=file]):not([type=range]),textarea")) if (!input.closest(".cms-ui-island")) addClass(input, "nodedc-field__control");
}
function cards() {
// Use the library's opaque nested surface: translucent local layers made
// collection backgrounds converge with the field material at greater depth.
for (const region of all(".collection-item-card,.json-details,.field-grid,.group-grid")) {
// As in Mission Core, fields sit directly in SettingsCard. Only independent
// collection entries and disclosures own another shared neutral group.
for (const region of all(".collection-item-card,.json-details")) {
if (region.dataset.dsSurface) continue;
// A collection already owns this surface; avoid stacking or double padding.
if (region.matches(".field-grid,.group-grid") && (region.closest(".collection-item-card") || region.querySelector(".collection-field"))) continue;
const surface = clone("nestedSurface");
for (const attribute of surface.attributes) {
if (attribute.name === "class") addClass(region, attribute.value);
@@ -151,7 +168,8 @@ function cards() {
for (const card of all(".settings-card,.content-group,.content-panel")) {
if (card.dataset.dsCard) continue;
card.dataset.dsCard = "true";
addClass(card, "nodedc-settings-card");
// The content overview is layout, not a third card around semantic groups.
addClass(card, card.querySelector(":scope > #content-fields") ? "cms-content-section" : "nodedc-settings-card");
const oldHead = $(":scope > .card-head,:scope > .group-head,:scope > .panel-head,:scope > .publish-progress-head", card);
const template = clone("card"), head = $(".nodedc-settings-card__head", template), titles = $(".nodedc-settings-card__titles", template), body = $(".nodedc-settings-card__body", template);
head.replaceChildren(titles);
@@ -313,7 +331,19 @@ function initModals() {
overlay.removeAttribute("role");
overlay.removeAttribute("aria-modal");
const controller = createModalController({ overlay, dialog, closeOnBackdrop: false, closeOnEscape: false, lockBodyScroll: false });
modalBindings.push({ overlay, dialog, controller });
let sizeController;
if (overlay.id === 'media-modal') {
sizeController = createModalSizeController({ dialog, initialSize: guiPreferences.modalSize('media-library') || { width: 1280, height: 820 }, minimum: { width: 640, height: 480 }, onSizeCommit: size => guiPreferences.setModalSize('media-library', size) });
guiPreferences.subscribe((document, status) => {
const size = document.gui.modals['media-library'];
if (size) sizeController.setSize(size);
const message = $('#media-size-status');
message.textContent = status === 'error' ? 'Не удалось сохранить размер окна.' : status === 'saving' ? 'Сохранение размера…' : 'Размер окна сохраняется в профиле';
$('#media-size-retry').hidden = status !== 'error';
});
$('#media-size-retry').addEventListener('click', () => guiPreferences.pending.length ? guiPreferences.flush() : guiPreferences.load());
}
modalBindings.push({ overlay, dialog, controller, sizeController });
}
for (const dialog of all("dialog.site-dialog")) {
const overlay = document.createElement("div");
@@ -369,6 +399,7 @@ function refresh() {
switches();
selects();
ranges();
colors();
progress();
buttons();
navItems();
@@ -382,6 +413,7 @@ function refresh() {
if (open && !binding.controller.isOpen()) {
document.body.append(binding.overlay);
binding.controller.open();
binding.sizeController?.refresh();
}
else if (!open && binding.controller.isOpen()) binding.controller.close();
}
+58
View File
@@ -0,0 +1,58 @@
const defaults = () => ({ schemaVersion: 1, appearance: { theme: 'dark', accent: null }, gui: { modals: {} } });
function merge(document, patch) {
const next = structuredClone(document);
Object.assign(next.appearance, patch.appearance);
for (const [id, size] of Object.entries(patch.gui?.modals || {})) {
if (size === null) delete next.gui.modals[id]; else next.gui.modals[id] = size;
}
return next;
}
/** Application-owned GUI metadata. The server derives identity from the session. */
export class UserGuiPreferences {
value = defaults(); status = 'loading'; listeners = new Set(); pending = []; running = false;
constructor() { this.ready = this.load(); }
subscribe(listener) { this.listeners.add(listener); listener(this.value, this.status); return () => this.listeners.delete(listener); }
notify() { for (const listener of this.listeners) listener(this.value, this.status); }
async request(method = 'GET', patch, headers = {}) {
const response = await fetch('/api/user/preferences', { method, credentials: 'same-origin', headers: { 'content-type': 'application/json', ...headers }, body: patch ? JSON.stringify(patch) : undefined });
if (!response.ok) throw new Error('Не удалось сохранить настройки интерфейса');
return response.json();
}
async load() {
try {
let result = await this.request();
// One-time import of the previous browser-only appearance. Atomic create
// prevents a second browser from replacing existing account preferences.
let legacy;
try { legacy = JSON.parse(localStorage.getItem('dc-cms.ui-preferences.v1')); } catch {}
if (!result.exists && legacy) {
const appearance = { theme: legacy.theme === 'light' ? 'light' : 'dark', accent: /^#[a-f\d]{6}$/i.test(legacy.accent || '') ? legacy.accent : null };
result = await this.request('PATCH', { appearance }, { 'if-none-match': '*' });
}
try { localStorage.removeItem('dc-cms.ui-preferences.v1'); } catch {}
this.value = this.pending.reduce(merge, result.preferences); this.status = 'saved';
} catch { this.status = 'error'; }
this.notify();
}
update(patch) {
this.pending.push(structuredClone(patch)); this.value = merge(this.value, patch); this.status = 'saving'; this.notify();
void this.flush();
}
async flush() {
await this.ready;
if (this.running) return;
this.running = true;
try {
while (this.pending.length) {
this.status = 'saving'; this.notify();
const result = await this.request('PATCH', this.pending[0]);
this.pending.shift(); this.value = this.pending.reduce(merge, result.preferences);
}
this.status = 'saved';
} catch { this.status = 'error'; }
finally { this.running = false; this.notify(); }
}
modalSize(id) { return this.value.gui.modals[id]; }
setModalSize(id, size) { this.update({ gui: { modals: { [id]: { width: Math.round(size.width), height: Math.round(size.height) } } } }); }
}
export const guiPreferences = new UserGuiPreferences();
+8 -14
View File
@@ -3,15 +3,12 @@ import { createRoot } from "react-dom/client";
import { flushSync } from "react-dom";
import { applyNodedcTheme, missionDarkTheme, missionLightTheme, clearNodedcAccent } from "@nodedc/ui-dom";
import { UserProfileMenu, FeatureSettingsWindow, SettingsCard, Select, ColorField, Button } from "@nodedc/ui-react";
import { guiPreferences } from './gui-preferences.mjs';
const h = React.createElement;
const storageKey = "dc-cms.ui-preferences.v1";
const defaults = { theme: "dark", accent: null };
function normalize(value) {
return { theme: value?.theme === "light" ? "light" : "dark", accent: /^#[\da-f]{6}$/i.test(value?.accent || "") ? value.accent.toLowerCase() : null };
}
function read() {
try { return normalize(JSON.parse(localStorage.getItem(storageKey))); } catch { return { ...defaults }; }
}
function apply(preferences) {
const accent = preferences.accent?.match(/[\da-f]{2}/gi).map(v => parseInt(v, 16));
clearNodedcAccent(document.documentElement);
@@ -24,19 +21,15 @@ function Preferences({ initial }) {
const [preferences, setPreferences] = useState(initial);
const [open, setOpen] = useState(false);
const [session, setSession] = useState(null);
const [storageError, setStorageError] = useState(false);
const [storageStatus, setStorageStatus] = useState(guiPreferences.status);
useEffect(() => {
const controller = new AbortController();
fetch("/api/me", { credentials: "same-origin", signal: controller.signal }).then(r => r.ok ? r.json() : null).then(setSession).catch(() => {});
const sync = event => { if (event.key === storageKey || event.key === null) { const value = read(); apply(value); setPreferences(value); } };
window.addEventListener("storage", sync);
return () => { controller.abort(); window.removeEventListener("storage", sync); };
const unsubscribe = guiPreferences.subscribe((document, status) => { const value = normalize(document.appearance); apply(value); setPreferences(value); setStorageStatus(status); });
return () => { controller.abort(); unsubscribe(); };
}, []);
function update(patch) {
const value = normalize({ ...preferences, ...patch });
apply(value);
setPreferences(value);
try { localStorage.setItem(storageKey, JSON.stringify(value)); setStorageError(false); } catch { setStorageError(true); }
guiPreferences.update({ appearance: patch });
}
const user = session?.user;
const name = user?.name || user?.username || "Профиль";
@@ -48,12 +41,13 @@ function Preferences({ initial }) {
footer: h(Button, { onClick: () => update(defaults), tone: "neutral" }, "Сбросить оформление") },
h("div", {className:"cms-preferences-fields"}, h(SettingsCard, { title: "Тема", description: "Светлый или тёмный интерфейс", actions: h("div", { className: "cms-preference-controls" }, h(Select, { label: "Тема интерфейса", value: preferences.theme, options: [{ value: "dark", label: "Тёмная" }, { value: "light", label: "Светлая" }], onChange: theme => update({ theme }) })) }),
h(SettingsCard, { title: "Акцентный цвет", description: "Цвет активных элементов", actions: h("div", { className: "cms-preference-controls" }, h(ColorField, { label: "Акцентный цвет", value: preferences.accent || themeAccent(), onChange: accent => update({ accent }) })) })),
h("p", { className: "nodedc-description", role: "status" }, storageError ? "Настройки действуют в этой вкладке. Браузер не разрешил сохранить их для следующего входа." : "Изменения сохраняются автоматически в этом браузере.")
h("p", { className: "nodedc-description", role: "status" }, storageStatus === 'error' ? "Не удалось сохранить настройки на сервере. Изменения остаются в этой вкладке." : storageStatus === 'saved' ? "Оформление и размеры окон сохраняются в профиле пользователя." : "Синхронизация настроек…"),
storageStatus === 'error' ? h(Button, { onClick: () => guiPreferences.pending.length ? guiPreferences.flush() : guiPreferences.load() }, "Повторить") : null
)
);
}
export function installPreferences() {
const preferences = read();
const preferences = guiPreferences.value.appearance;
apply(preferences);
flushSync(() => createRoot(document.querySelector("#cms-profile")).render(h(Preferences, { initial: preferences })));
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.