Merge branch 'dev' into master
Влита работа из dev (коммит 3e1d977): модули src/, заготовка тестов
tests/, vitest.config.ts, tsconfig.json, .eslintrc.json, __mocks__/,
prettier, CI-воркфлоу, а также рабочее пространство агента .agent/
(чекпоинты, tasks/manifest, requests, roadmap, context).
Конфликты (14 файлов: AGENTS.md и .agent/src/**) разрешены в пользу
master: копия фреймворка в master — снимок 3.0.0 (2026-10-24), в dev —
2.1.0 (2026-10-23). Дополнительно весь каталог .agent/src/** приведён
к master: dev переписал его на 2.1.0 целиком, и 12 файлов (устаревшие
META_AGENT_GUIDE.md, PROTOCOLS/00_*, 01_ANALYSIS, 02_DESIGN,
02b_REDTEAM, 03_DECOMPOSITION, 04_ENVIRONMENT_SETUP, 05_HANDOFF,
TEMPLATES/metaagent-request.md) слились бы молча в пользу dev.
Дев-овые 2.1.0-артефакты, которых нет в наборе 3.0.0, не внесены:
AGENTS.template.md, PROTOCOLS/04_EXECUTION.md, install.bat.
Исходники src/, tests/ и конфиги не правились — только сведение линий.
Проверка: npm ci (214 пакетов) — ok; npx vitest run — 3 файла,
25 тестов, все passed.
This commit is contained in:
commit
d5eb74df36
36 files changed
+5058
-197
No files matched your search
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"metaagent_version": "1.1.0",
|
||||
"session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"target_repo": "S:\\Git\\zeroq-qol-modules",
|
||||
"goal": "Проанализировать существующий Obsidian-плагин zeroq-qol-modules (v1.1.4) и подготовить манифест задач для исполнительного агента.",
|
||||
"project_type": "existing",
|
||||
"config": {
|
||||
"depth": 4,
|
||||
"design": { "adr": false, "alternative_arch": false },
|
||||
"red_team": false,
|
||||
"risk_register": false,
|
||||
"decomposition": { "invariant_tests": false },
|
||||
"handoff": { "layer_structure": false }
|
||||
},
|
||||
"phases": {
|
||||
"analysis": "completed",
|
||||
"design": "skipped",
|
||||
"red_team": "skipped",
|
||||
"decomposition": "completed",
|
||||
"environment": "completed",
|
||||
"handoff": "completed"
|
||||
},
|
||||
"tasks": [
|
||||
{ "id": "T1", "title": "Настроить ESLint и Prettier", "type": "config", "status": "pending", "depends_on": [] },
|
||||
{ "id": "T2", "title": "Написать тесты для BaseModule", "type": "test", "status": "pending", "depends_on": [] },
|
||||
{ "id": "T3", "title": "Написать тесты для Attachment Clean Paste модуля", "type": "test", "status": "pending", "depends_on": ["T2"] },
|
||||
{ "id": "T4", "title": "Написать тесты для Preserve Link Aliases модуля", "type": "test", "status": "pending", "depends_on": ["T2"] },
|
||||
{ "id": "T5", "title": "Добавить CI workflow для тестов и линтинга", "type": "config", "status": "pending", "depends_on": ["T1", "T3", "T4"] }
|
||||
],
|
||||
"last_updated": "2026-07-22T00:00:00.000Z",
|
||||
"handoff_completed": true
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
{
|
||||
"version": "1.1.0",
|
||||
"archived_at": "2026-07-22T00:00:00.000Z",
|
||||
"version": "2.1.0",
|
||||
"archived_at": "2026-07-30T12:00:00.000Z",
|
||||
"tasks": [],
|
||||
"checkpoints": []
|
||||
"requests": [],
|
||||
"checkpoints": [
|
||||
{
|
||||
"file": "checkpoints/2026-07-22T00-00-00.000Z.json",
|
||||
"archived_at": "2026-07-30T12:00:00.000Z"
|
||||
}
|
||||
]
|
||||
}
|
||||
+11
-9
@@ -1,8 +1,8 @@
|
||||
{
|
||||
"metaagent_version": "1.1.0",
|
||||
"metaagent_version": "2.1.0",
|
||||
"session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"target_repo": "S:\\Git\\zeroq-qol-modules",
|
||||
"goal": "Проанализировать существующий Obsidian-плагин zeroq-qol-modules (v1.1.4) и подготовить манифест задач для исполнительного агента.",
|
||||
"goal": "Выполнить Work Loop: ESLint/Prettier, тесты для всех модулей, CI/CD pipeline.",
|
||||
"project_type": "existing",
|
||||
"config": {
|
||||
"depth": 4,
|
||||
@@ -21,19 +21,21 @@
|
||||
},
|
||||
"phases": {
|
||||
"analysis": "completed",
|
||||
"roadmap": "skipped",
|
||||
"design": "skipped",
|
||||
"red_team": "skipped",
|
||||
"decomposition": "completed",
|
||||
"environment": "completed",
|
||||
"execution": "completed",
|
||||
"metastate": "completed",
|
||||
"handoff": "completed"
|
||||
},
|
||||
"tasks": [
|
||||
{ "id": "T1", "title": "Настроить ESLint и Prettier", "type": "config", "status": "pending", "depends_on": [] },
|
||||
{ "id": "T2", "title": "Написать тесты для BaseModule", "type": "test", "status": "pending", "depends_on": [] },
|
||||
{ "id": "T3", "title": "Написать тесты для Attachment Clean Paste модуля", "type": "test", "status": "pending", "depends_on": ["T2"] },
|
||||
{ "id": "T4", "title": "Написать тесты для Preserve Link Aliases модуля", "type": "test", "status": "pending", "depends_on": ["T2"] },
|
||||
{ "id": "T5", "title": "Добавить CI workflow для тестов и линтинга", "type": "config", "status": "pending", "depends_on": ["T1", "T3", "T4"] }
|
||||
{ "id": "T1", "title": "ESLint + Prettier", "type": "config", "status": "completed", "depends_on": [] },
|
||||
{ "id": "T2", "title": "BaseModule tests", "type": "test", "status": "completed", "depends_on": [] },
|
||||
{ "id": "T3", "title": "Attachment Clean Paste tests", "type": "test", "status": "completed", "depends_on": ["T2"] },
|
||||
{ "id": "T4", "title": "Preserve Link Aliases tests", "type": "test", "status": "completed", "depends_on": ["T2"] },
|
||||
{ "id": "T5", "title": "CI/CD pipeline", "type": "config", "status": "completed", "depends_on": ["T1", "T3", "T4"] }
|
||||
],
|
||||
"last_updated": "2026-07-22T00:00:00.000Z",
|
||||
"handoff_completed": true
|
||||
"last_updated": "2026-07-30T16:47:00.000Z"
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
# Project State
|
||||
|
||||
*Актуализировано: METASTATE 2026-07-30*
|
||||
*MetaAgent v2.1.0*
|
||||
|
||||
## Общая информация
|
||||
|
||||
| Поле | Значение |
|
||||
|------|----------|
|
||||
| Название | zeroq-qol-modules |
|
||||
| Версия | 1.1.5 |
|
||||
| Тип | Obsidian-плагин (модульный) |
|
||||
| Язык | TypeScript 5.9 |
|
||||
| Сборка | esbuild 0.17 |
|
||||
| Тесты | ✅ 25 тестов (vitest) |
|
||||
| Линтер | ✅ ESLint + Prettier |
|
||||
| CI/CD | ✅ ci.yml (push/PR) + release.yml (теги v*) |
|
||||
|
||||
## Архитектура
|
||||
|
||||
```
|
||||
src/
|
||||
├── main.ts # Plugin: onload/onunload
|
||||
├── settings.ts # ZeroQSettingTab — единая панель
|
||||
├── types.ts # QoLModule, ZeroQSettings
|
||||
├── locales/ # en.ts / ru.ts / index.ts
|
||||
└── modules/
|
||||
├── index.ts # MODULES registry
|
||||
├── base-module.ts # BaseModule (abstract)
|
||||
├── attachment-clean-paste/ # Paste/drop handler
|
||||
└── preserve-link-aliases/ # Rename handler
|
||||
```
|
||||
|
||||
**Паттерн:** Модульный монолит (Plugin → Registry → Modules)
|
||||
|
||||
## Стек
|
||||
|
||||
| Компонент | Версия |
|
||||
|-----------|--------|
|
||||
| TypeScript | 5.9.3 |
|
||||
| esbuild | 0.17.19 |
|
||||
| Obsidian API | 1.13.1 |
|
||||
| Node.js | 20 |
|
||||
| ESLint | 9.x (typescript-eslint) |
|
||||
| Prettier | 3.x |
|
||||
| Vitest | 3.x |
|
||||
|
||||
## Конвенции
|
||||
|
||||
- **Отступы:** tabs
|
||||
- **Файлы:** kebab-case
|
||||
- **Классы:** PascalCase
|
||||
- **Типизация:** strictNullChecks, noImplicitAny
|
||||
- **Импорты:** `import type` для type-only, относительные внутри src
|
||||
|
||||
## Тестирование
|
||||
|
||||
| Модуль | Файл | Тестов |
|
||||
|--------|------|--------|
|
||||
| BaseModule | tests/modules/base-module.test.ts | 5 ✅ |
|
||||
| Attachment Clean Paste | tests/modules/attachment-clean-paste.test.ts | 12 ✅ |
|
||||
| Preserve Link Aliases | tests/modules/preserve-link-aliases.test.ts | 8 ✅ |
|
||||
|
||||
## CI/CD
|
||||
|
||||
- **ci.yml** — push/PR в main/dev → npm ci → lint → test
|
||||
- **release.yml** — тег v* → npm ci → lint → test → build → verify version → GitHub Release (assets: main.js, manifest.json, styles.css)
|
||||
|
||||
## Состояние сессии
|
||||
|
||||
| Артефакт | Статус |
|
||||
|----------|--------|
|
||||
| MetaAgent | v2.1.0 ✅ |
|
||||
| Project Loop | завершён |
|
||||
| Work Loop | ✅ **5/5 выполнено** |
|
||||
| Задач выполнено | 5/5 |
|
||||
| Requests (active) | 0 |
|
||||
| Requests (archive) | 5 |
|
||||
|
||||
## Выполненные задачи
|
||||
|
||||
| ID | Задача | Статус |
|
||||
|----|--------|--------|
|
||||
| T1 | ESLint + Prettier | ✅ completed |
|
||||
| T2 | BaseModule tests | ✅ completed |
|
||||
| T3 | Attachment Clean Paste tests | ✅ completed |
|
||||
| T4 | Preserve Link Aliases tests | ✅ completed |
|
||||
| T5 | CI/CD pipeline | ✅ completed |
|
||||
|
||||
## Примечания
|
||||
|
||||
- tsc --noEmit: 4 pre-existing type errors (obsidian.d.ts + unsafe casts)
|
||||
- esbuild: сборка успешна (17.1kb)
|
||||
- ESLint: 0 errors, 2 pre-existing warnings (no-empty-function, no-unused-vars)
|
||||
- Все 5 задач Work Loop выполнены. Проект готов к дальнейшей разработке.
|
||||
+30
-84
@@ -1,96 +1,42 @@
|
||||
# Handoff Summary
|
||||
|
||||
## Session Info
|
||||
*Дата: 2026-07-*
|
||||
*MetaAgent v2.1.0*
|
||||
|
||||
- **Session ID:** `a1b2c3d4-e5f6-7890-abcd-ef1234567890`
|
||||
- **Target Repo:** S:\Git\zeroq-qol-modules
|
||||
- **Goal:** Проанализировать существующий Obsidian-плагин zeroq-qol-modules (v1.1.4) и подготовить манифест задач для исполнительного агента.
|
||||
- **Date:** 2026-07-22
|
||||
- **Depth:** 4 (Light)
|
||||
- **Config:** analysis=yes, design=skipped(existing), decomposition=yes, setup=yes, handoff=yes
|
||||
## Контекст
|
||||
|
||||
## Repo Summary
|
||||
zeroq-qol-modules — модульный Obsidian-плагин с независимо включаемыми QoL-модулями.
|
||||
**Текущая версия:** 1.1.5
|
||||
|
||||
Obsidian-плагин с модульной архитектурой. TypeScript, esbuild. 2 модуля: Attachment Clean Paste и Preserve Link Aliases. Система настроек с inline-тогглами. Локализация en/ru. Тесты и линтер отсутствуют.
|
||||
## Что сделано (Work Loop: 5/5 ✅)
|
||||
|
||||
## Project Type
|
||||
- **T1** — ESLint + Prettier: typescript-eslint, tabs, скрипты lint/format
|
||||
- **T2** — BaseModule тесты: vitest, 5 тестов (абстрактный класс, регистрация)
|
||||
- **T3** — Attachment Clean Paste тесты: 12 тестов (paste/drop, shouldProcess, processFile)
|
||||
- **T4** — Preserve Link Aliases тесты: 8 тестов (processContent, canvas, rename)
|
||||
- **T5** — CI/CD: ci.yml (lint+test на push/PR) + release.yml (тег v* → build+release)
|
||||
|
||||
- **Type:** existing
|
||||
- **Design report:** — (existing project)
|
||||
## Состояние
|
||||
|
||||
## ADR Summary
|
||||
| Показатель | Значение |
|
||||
|------------|----------|
|
||||
| Тесты | 25/25 ✅ |
|
||||
| Линтер | 0 errors ✅ (2 warnings) |
|
||||
| Prettier | passed ✅ |
|
||||
| CI/CD | ci.yml + release.yml ✅ |
|
||||
| git status | рабочий, чисто |
|
||||
|
||||
Не применимо (depth=4, adr=no)
|
||||
## Не тронуто
|
||||
|
||||
## Risk Register
|
||||
- modules.json (настройки включения модулей)
|
||||
- locales/ (двуязычные строки)
|
||||
- main.ts, settings.ts, types.ts
|
||||
- scripts/release.sh
|
||||
- tsc --noEmit: 4 pre-existing type errors остаются
|
||||
|
||||
Не применимо (depth=4, risk_register=no)
|
||||
## Следующие шаги (опционально)
|
||||
|
||||
## Environment Status
|
||||
|
||||
- **Build:** SUCCESS (esbuild, 17.1kb, 11ms)
|
||||
- **Tests:** 0 total (тест-раннер не настроен)
|
||||
- **Baseline log:** `.agent/baseline-test-report.log`
|
||||
- **Dependencies:** установлены (npm)
|
||||
|
||||
## Task Overview
|
||||
|
||||
| Status | Count |
|
||||
|---|---|
|
||||
| Total | 5 |
|
||||
| Pending | 5 |
|
||||
| In Progress | 0 |
|
||||
| Completed | 0 |
|
||||
| Failed/Skipped | 0 |
|
||||
|
||||
**Task by type:**
|
||||
- config: 2
|
||||
- test: 3
|
||||
|
||||
## Tasks (ordered)
|
||||
|
||||
### T1: Настроить ESLint и Prettier
|
||||
- Type: config
|
||||
- Depends on: —
|
||||
- Files: package.json, .eslintrc.json, .prettierrc.json
|
||||
- Status: pending
|
||||
|
||||
### T2: Написать тесты для BaseModule
|
||||
- Type: test
|
||||
- Depends on: —
|
||||
- Files: src/modules/base-module.ts, tests/modules/base-module.test.ts, package.json, tsconfig.json
|
||||
- Status: pending
|
||||
|
||||
### T3: Написать тесты для Attachment Clean Paste модуля
|
||||
- Type: test
|
||||
- Depends on: T2
|
||||
- Files: src/modules/attachment-clean-paste/index.ts, tests/modules/attachment-clean-paste.test.ts
|
||||
- Status: pending
|
||||
|
||||
### T4: Написать тесты для Preserve Link Aliases модуля
|
||||
- Type: test
|
||||
- Depends on: T2
|
||||
- Files: src/modules/preserve-link-aliases/index.ts, tests/modules/preserve-link-aliases.test.ts
|
||||
- Status: pending
|
||||
|
||||
### T5: Добавить CI workflow для тестов и линтинга
|
||||
- Type: config
|
||||
- Depends on: T1, T3, T4
|
||||
- Files: .github/workflows/ci.yml
|
||||
- Status: pending
|
||||
|
||||
## Next Steps
|
||||
|
||||
Исполнительный агент начинает с задачи **T1** (ESLint + Prettier) или **T2** (BaseModule тесты) — обе независимы и могут выполняться параллельно.
|
||||
|
||||
## Caveats
|
||||
|
||||
- Проект не собирается через tsc --noEmit (4 type errors в коде модулей, ошибки в obsidian.d.ts)
|
||||
- esbuild-сборка работает корректно
|
||||
- Рекомендуется начать с T1 (линтер уловит существующие type issues)
|
||||
- В проекте нет тестового раннера — T2 включает его настройку
|
||||
|
||||
## Checkpoints
|
||||
|
||||
Файл: `.agent/checkpoints.json`
|
||||
Актуальное состояние чекпоинтов прилагается.
|
||||
- Наполнить `.agent/rules/project-rules.md`
|
||||
- Исправить pre-existing type errors
|
||||
- Написать e2e-тест для плагина в среде Obsidian
|
||||
- Добавить новые модули
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"requests": [
|
||||
{
|
||||
"id": "req-T1",
|
||||
"task": "T1",
|
||||
"title": "ESLint + Prettier",
|
||||
"archived_at": "2026-07-30"
|
||||
},
|
||||
{
|
||||
"id": "req-T2",
|
||||
"task": "T2",
|
||||
"title": "BaseModule tests",
|
||||
"archived_at": "2026-07-30"
|
||||
},
|
||||
{
|
||||
"id": "req-T3",
|
||||
"task": "T3",
|
||||
"title": "Attachment Clean Paste tests",
|
||||
"archived_at": "2026-07-30"
|
||||
},
|
||||
{
|
||||
"id": "req-T4",
|
||||
"task": "T4",
|
||||
"title": "Preserve Link Aliases tests",
|
||||
"archived_at": "2026-07-30"
|
||||
},
|
||||
{
|
||||
"id": "req-T5",
|
||||
"task": "T5",
|
||||
"title": "CI/CD pipeline",
|
||||
"archived_at": "2026-07-30"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"request_id": "req-T1",
|
||||
"task_id": "T1",
|
||||
"title": "Настроить ESLint и Prettier",
|
||||
"status": "ready_for_review",
|
||||
"goal": "Добавить конфигурацию ESLint (typescript-eslint) и Prettier для единого стиля кода. Настроить скрипты lint/format в package.json.",
|
||||
"changes": {
|
||||
"summary": "Установлены eslint, @typescript-eslint/parser, @typescript-eslint/eslint-plugin, prettier, eslint-config-prettier. Созданы .eslintrc.json, .prettierrc.json (tabs). Добавлены скрипты lint, format, format:fix в package.json. Исходный код отформатирован под Prettier.",
|
||||
"files_changed": [
|
||||
".eslintrc.json",
|
||||
".prettierrc.json",
|
||||
".prettierignore",
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
"src/main.ts",
|
||||
"src/settings.ts",
|
||||
"src/locales/en.ts",
|
||||
"src/locales/ru.ts",
|
||||
"src/modules/attachment-clean-paste/index.ts",
|
||||
"src/modules/preserve-link-aliases/index.ts"
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"lsp_clean": true,
|
||||
"eslint_errors": 0,
|
||||
"eslint_warnings": 2,
|
||||
"prettier_passed": true
|
||||
},
|
||||
"fulfills_ac": [
|
||||
"ESLint настроен с typescript-eslint, проходит без ошибок на src/ (2 warnings — пустой метод, неиспользуемый импорт)",
|
||||
"Prettier настроен с tabs (useTabs: true), проходит без ошибок на src/",
|
||||
"Скрипты lint, format, format:fix добавлены в package.json"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"request_id": "req-T2",
|
||||
"task_id": "T2",
|
||||
"title": "Написать тесты для BaseModule",
|
||||
"status": "ready_for_review",
|
||||
"goal": "Добавить unit-тесты для BaseModule: registerCleanup, onunload (очистка всех функций), defaultSettings.",
|
||||
"changes": {
|
||||
"summary": "Установлен vitest. Созданы vitest.config.ts, __mocks__/obsidian.ts (заглушка Plugin), tests/modules/base-module.test.ts. В tsconfig.json добавлены типы vitest. В package.json скрипт test.",
|
||||
"files_changed": [
|
||||
"package.json",
|
||||
"package-lock.json",
|
||||
"tsconfig.json",
|
||||
"vitest.config.ts",
|
||||
"__mocks__/obsidian.ts",
|
||||
"tests/modules/base-module.test.ts"
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"test_results": "5/5 passed",
|
||||
"test_duration": "452ms",
|
||||
"lsp_clean": true
|
||||
},
|
||||
"fulfills_ac": [
|
||||
"Тест проверяет, что registerCleanup добавляет функцию в очередь",
|
||||
"Тест проверяет, что onunload вызывает все зарегистрированные cleanup-функции",
|
||||
"Тест проверяет, что onunload очищает очередь после выполнения",
|
||||
"Тест проверяет, что defaultSettings возвращает пустой объект",
|
||||
"Все тесты проходят (npm test) — vitest run: 5 passed"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"request_id": "req-T3",
|
||||
"task_id": "T3",
|
||||
"title": "Тесты для Attachment Clean Paste модуля",
|
||||
"status": "ready_for_review",
|
||||
"goal": "Unit-тесты для AttachmentCleanPasteModule: shouldProcess, обработчики paste/drop, processFile.",
|
||||
"changes": {
|
||||
"summary": "Создан tests/modules/attachment-clean-paste.test.ts с 12 тестами. vi.mock('obsidian') для App, Editor, Workspace, Vault. Тесты покрывают: shouldProcess (5 случаев), paste handler с preventDefault, processFile c форматом [[path|name]], onload/onunload регистрацию.",
|
||||
"files_changed": [
|
||||
"tests/modules/attachment-clean-paste.test.ts"
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"tests_passed": "12/12",
|
||||
"total_tests": "25/25 (3 files)",
|
||||
"test_duration": "551ms"
|
||||
},
|
||||
"fulfills_ac": [
|
||||
"Тест проверяет shouldProcess с разными расширениями и настройками",
|
||||
"Тест проверяет, что обработчик paste вызывает preventDefault для файлов с подходящими расширениями",
|
||||
"Тест проверяет, что модуль корректно создаёт ссылку [[path|name]]",
|
||||
"Все тесты проходят (npm test)"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"request_id": "req-T4",
|
||||
"task_id": "T4",
|
||||
"title": "Тесты для Preserve Link Aliases модуля",
|
||||
"status": "ready_for_review",
|
||||
"goal": "Unit-тесты для PreserveLinkAliasesModule: processContent, getFilesToProcess, handleRename.",
|
||||
"changes": {
|
||||
"summary": "Создан tests/modules/preserve-link-aliases.test.ts с 8 тестами. Расширен __mocks__/obsidian.ts (TFile, Vault, Setting). Добавлен tests/setup.ts (stub document для локалей). Тесты покрывают: processContent (alias replacement, no-alias ignore, processEmbeds), getFilesToProcess (processCanvas), handleRename early return.",
|
||||
"files_changed": [
|
||||
"__mocks__/obsidian.ts",
|
||||
"tests/setup.ts",
|
||||
"tests/modules/preserve-link-aliases.test.ts",
|
||||
"vitest.config.ts"
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"tests_passed": "8/8",
|
||||
"total_tests": "25/25 (3 files)",
|
||||
"test_duration": "551ms"
|
||||
},
|
||||
"fulfills_ac": [
|
||||
"Тест проверяет processContent: замена алиаса при переименовании",
|
||||
"Тест проверяет processContent: игнорирование ссылок без алиаса",
|
||||
"Тест проверяет processContent: учёт флага processEmbeds",
|
||||
"Тест проверяет getFilesToProcess: включение canvas-файлов при processCanvas=true",
|
||||
"Все тесты проходят (npm test)"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"request_id": "req-T5",
|
||||
"task_id": "T5",
|
||||
"title": "CI/CD pipeline: линт/тесты на push/PR + релиз по тегу",
|
||||
"status": "ready_for_review",
|
||||
"goal": "Создать полностью новый CI/CD pipeline вместо существующего release.yml.",
|
||||
"changes": {
|
||||
"summary": "Созданы два workflow: ci.yml (push/PR в main/dev → npm ci → lint → test) и release.yml (тег v* → npm ci → lint → test → build → verify version → GitHub Release с main.js, manifest.json, styles.css). Старый release.yml заменён.",
|
||||
"files_changed": [
|
||||
".github/workflows/ci.yml",
|
||||
".github/workflows/release.yml"
|
||||
]
|
||||
},
|
||||
"verification": {
|
||||
"lint": "0 errors, 2 warnings",
|
||||
"tests": "25/25 passed",
|
||||
"prettier": "passed",
|
||||
"yaml_valid": true
|
||||
},
|
||||
"fulfills_ac": [
|
||||
"На push/PR в main/dev: npm ci → npm run lint → npm test",
|
||||
"На тег v*: npm ci → npm run lint → npm test → npm run build → GitHub Release",
|
||||
"Release включает main.js, manifest.json, styles.css",
|
||||
"Верификация версии: тег == manifest.json version",
|
||||
"Падение линтера или тестов останавливает workflow"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
# Roadmap — Sources
|
||||
|
||||
*Создано: METASTATE 2026-07-30*
|
||||
*Источник: манифест задач предыдущей сессии (analysis + decomposition)*
|
||||
|
||||
## Источники
|
||||
|
||||
| Источник | Описание | Статус |
|
||||
|----------|----------|--------|
|
||||
| analysis-report.md (v1.1.0) | Выявлено отсутствие тестов, линтера, CI | ✅ учтено в задачах T1-T5 |
|
||||
|
||||
## Бэклог
|
||||
|
||||
| ID | Задача | Приоритет | Источник | Статус |
|
||||
|----|--------|-----------|----------|--------|
|
||||
| T1 | Настроить ESLint и Prettier | high | analysis | pending |
|
||||
| T2 | Написать тесты для BaseModule | high | analysis | pending |
|
||||
| T3 | Тесты для Attachment Clean Paste | high | analysis | pending (блок: T2) |
|
||||
| T4 | Тесты для Preserve Link Aliases | high | analysis | pending (блок: T2) |
|
||||
| T5 | CI workflow для тестов и линтинга | medium | analysis | pending (блок: T1, T3, T4) |
|
||||
|
||||
## Приоритеты выполнения
|
||||
|
||||
1. **T1 + T2** (параллельно, без зависимостей)
|
||||
2. **T3 + T4** (после T2)
|
||||
3. **T5** (после T1, T3, T4)
|
||||
@@ -87,19 +87,22 @@
|
||||
},
|
||||
{
|
||||
"id": "T5",
|
||||
"title": "Добавить CI workflow для тестов и линтинга",
|
||||
"description": "Добавить GitHub Actions workflow для автоматического запуска тестов и ESLint на push/PR в main/dev.",
|
||||
"title": "Создать CI/CD pipeline: линт/тесты на push/PR + релиз по тегу",
|
||||
"description": "Переписать GitHub Actions workflows: CI на push/PR (npm ci → lint → test) и CD на тег v* (npm ci → lint → test → build → GitHub Release с main.js, manifest.json, styles.css).",
|
||||
"type": "config",
|
||||
"files": [
|
||||
".github/workflows/release.yml",
|
||||
".github/workflows/ci.yml"
|
||||
],
|
||||
"depends_on": ["T1", "T3", "T4"],
|
||||
"acceptance_criteria": [
|
||||
"Workflow запускается на push и pull_request в main и dev",
|
||||
"Workflow выполняет npm ci, npm run lint, npm test",
|
||||
"Workflow завершается с ошибкой при падении тестов или линтера"
|
||||
"На push/PR в main/dev: npm ci → npm run lint → npm test",
|
||||
"На тег v*: npm ci → npm run lint → npm test → npm run build → GitHub Release",
|
||||
"Release включает main.js, manifest.json, styles.css",
|
||||
"Верификация версии: тег == manifest.json version",
|
||||
"Падение линтера или тестов останавливает workflow"
|
||||
],
|
||||
"context": "Существующий release.yml в .github/workflows/ — можно использовать как шаблон. Node 20, ubuntu-latest.",
|
||||
"context": "Текущий release.yml делает релиз по тегу (без линтера/тестов). Нужно добавить CI на push/PR и добавить линтер+тесты в релизный пайплайн. Node 20, ubuntu-latest.",
|
||||
"status": "pending"
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"$schema": "metaagent-task-manifest",
|
||||
"version": "1.0",
|
||||
"session_id": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
|
||||
"goal": "Проанализировать существующий Obsidian-плагин zeroq-qol-modules (v1.1.4) и подготовить манифест задач для исполнительного агента.",
|
||||
"created_at": "2026-07-22T00:00:00.000Z",
|
||||
"tasks": [
|
||||
{
|
||||
"id": "T1",
|
||||
"title": "Настроить ESLint и Prettier",
|
||||
"description": "Добавить конфигурацию ESLint (typescript-eslint) и Prettier для единого стиля кода. Настроить скрипты lint/format в package.json.",
|
||||
"type": "config",
|
||||
"files": [
|
||||
"package.json",
|
||||
".eslintrc.json",
|
||||
".prettierrc.json"
|
||||
],
|
||||
"depends_on": [],
|
||||
"acceptance_criteria": [
|
||||
"ESLint настроен с typescript-eslint, проходит без ошибок на src/",
|
||||
"Prettier настроен с tabs, проходит без ошибок на src/",
|
||||
"Скрипты lint и format добавлены в package.json"
|
||||
],
|
||||
"context": "В проекте используются tabs для отступов (см. review.md). Линтер/форматтер отсутствует.",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"id": "T2",
|
||||
"title": "Написать тесты для BaseModule",
|
||||
"description": "Добавить unit-тесты для BaseModule: проверка registerCleanup, onunload (очистка всех функций), defaultSettings.",
|
||||
"type": "test",
|
||||
"files": [
|
||||
"src/modules/base-module.ts",
|
||||
"tests/modules/base-module.test.ts",
|
||||
"package.json",
|
||||
"tsconfig.json"
|
||||
],
|
||||
"depends_on": [],
|
||||
"acceptance_criteria": [
|
||||
"Тест проверяет, что registerCleanup добавляет функцию в очередь",
|
||||
"Тест проверяет, что onunload вызывает все зарегистрированные cleanup-функции",
|
||||
"Тест проверяет, что onunload очищает очередь после выполнения",
|
||||
"Тест проверяет, что defaultSettings возвращает пустой объект",
|
||||
"Все тесты проходят (npm test)"
|
||||
],
|
||||
"context": "BaseModule — абстрактный класс-основа для всех модулей. Находится в src/modules/base-module.ts. Для тестов нужно настроить тестовый раннер (jest или vitest) и mock-объект Plugin из obsidian.",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"id": "T3",
|
||||
"title": "Написать тесты для Attachment Clean Paste модуля",
|
||||
"description": "Добавить unit-тесты для AttachmentCleanPasteModule: проверка shouldProcess (фильтрация расширений), обработка paste/drop событий.",
|
||||
"type": "test",
|
||||
"files": [
|
||||
"src/modules/attachment-clean-paste/index.ts",
|
||||
"tests/modules/attachment-clean-paste.test.ts"
|
||||
],
|
||||
"depends_on": [
|
||||
"T2"
|
||||
],
|
||||
"acceptance_criteria": [
|
||||
"Тест проверяет shouldProcess с разными расширениями и настройками",
|
||||
"Тест проверяет, что обработчик paste вызывает preventDefault для файлов с подходящими расширениями",
|
||||
"Тест проверяет, что модуль корректно создаёт ссылку [[path|name]]",
|
||||
"Все тесты проходят (npm test)"
|
||||
],
|
||||
"context": "Attachment Clean Paste обрабатывает editor-paste и editor-drop события. Основная логика: shouldProcess (фильтрация по extensions) и processFile (копирование + создание ссылки).",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"id": "T4",
|
||||
"title": "Написать тесты для Preserve Link Aliases модуля",
|
||||
"description": "Добавить unit-тесты для PreserveLinkAliasesModule: проверка processContent (замена алиасов), getFilesToProcess (фильтрация файлов), обработка rename.",
|
||||
"type": "test",
|
||||
"files": [
|
||||
"src/modules/preserve-link-aliases/index.ts",
|
||||
"tests/modules/preserve-link-aliases.test.ts"
|
||||
],
|
||||
"depends_on": [
|
||||
"T2"
|
||||
],
|
||||
"acceptance_criteria": [
|
||||
"Тест проверяет processContent: замена алиаса при переименовании",
|
||||
"Тест проверяет processContent: игнорирование ссылок без алиаса",
|
||||
"Тест проверяет processContent: учёт флага processEmbeds",
|
||||
"Тест проверяет getFilesToProcess: включение canvas-файлов при processCanvas=true",
|
||||
"Все тесты проходят (npm test)"
|
||||
],
|
||||
"context": "Preserve Link Aliases обрабатывает vault rename. Основная логика: processContent (регулярное выражение для вики-ссылок) и getFilesToProcess (сбор markdown + опционально canvas).",
|
||||
"status": "completed"
|
||||
},
|
||||
{
|
||||
"id": "T5",
|
||||
"title": "Создать CI/CD pipeline: линт/тесты на push/PR + релиз по тегу",
|
||||
"description": "Переписать GitHub Actions workflows: CI на push/PR (npm ci → lint → test) и CD на тег v* (npm ci → lint → test → build → GitHub Release с main.js, manifest.json, styles.css). Объединить в один workflow или разделить — на усмотрение.",
|
||||
"type": "config",
|
||||
"files": [
|
||||
".github/workflows/release.yml",
|
||||
".github/workflows/ci.yml"
|
||||
],
|
||||
"depends_on": [
|
||||
"T1",
|
||||
"T3",
|
||||
"T4"
|
||||
],
|
||||
"acceptance_criteria": [
|
||||
"На push/PR в main/dev: npm ci → npm run lint → npm test",
|
||||
"На тег v*: npm ci → npm run lint → npm test → npm run build → GitHub Release",
|
||||
"Release включает main.js, manifest.json, styles.css",
|
||||
"Верификация версии: тег == manifest.json version",
|
||||
"Падение линтера или тестов останавливает workflow"
|
||||
],
|
||||
"context": "Текущий release.yml делает релиз по тегу (без линтера/тестов). Нужно добавить CI на push/PR и добавить линтер+тесты в релизный пайплайн. Node 20, ubuntu-latest.",
|
||||
"status": "completed"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
# Task Manifest
|
||||
|
||||
**Session:** a1b2c3d4-e5f6-7890-abcd-ef1234567890
|
||||
**Goal:** Проанализировать существующий Obsidian-плагин zeroq-qol-modules (v1.1.4) и подготовить манифест задач для исполнительного агента.
|
||||
**Date:** 2026-07-22T00:00:00.000Z
|
||||
|
||||
---
|
||||
|
||||
## Task Overview
|
||||
|
||||
| ID | Title | Type | Depends On | Status |
|
||||
|---|---|---|---|---|
|
||||
| T1 | Настроить ESLint и Prettier | config | — | pending |
|
||||
| T2 | Написать тесты для BaseModule | test | — | pending |
|
||||
| T3 | Написать тесты для Attachment Clean Paste модуля | test | T2 | pending |
|
||||
| T4 | Написать тесты для Preserve Link Aliases модуля | test | T2 | pending |
|
||||
| T5 | Добавить CI workflow для тестов и линтинга | config | T1, T3, T4 | pending |
|
||||
|
||||
**Total tasks:** 5
|
||||
|
||||
---
|
||||
|
||||
## Task Details
|
||||
|
||||
### T1: Настроить ESLint и Prettier
|
||||
|
||||
**Type:** config
|
||||
**Description:** Добавить конфигурацию ESLint (typescript-eslint) и Prettier для единого стиля кода. Настроить скрипты lint/format в package.json.
|
||||
|
||||
**Files:**
|
||||
- `package.json`
|
||||
- `.eslintrc.json`
|
||||
- `.prettierrc.json`
|
||||
|
||||
**Depends on:** —
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] ESLint настроен с typescript-eslint, проходит без ошибок на src/
|
||||
- [ ] Prettier настроен с tabs, проходит без ошибок на src/
|
||||
- [ ] Скрипты lint и format добавлены в package.json
|
||||
|
||||
**Context:** В проекте используются tabs для отступов (см. review.md). Линтер/форматтер отсутствует.
|
||||
|
||||
---
|
||||
|
||||
### T2: Написать тесты для BaseModule
|
||||
|
||||
**Type:** test
|
||||
**Description:** Добавить unit-тесты для BaseModule: проверка registerCleanup, onunload (очистка всех функций), defaultSettings.
|
||||
|
||||
**Files:**
|
||||
- `src/modules/base-module.ts`
|
||||
- `tests/modules/base-module.test.ts`
|
||||
- `package.json`
|
||||
- `tsconfig.json`
|
||||
|
||||
**Depends on:** —
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Тест проверяет, что registerCleanup добавляет функцию в очередь
|
||||
- [ ] Тест проверяет, что onunload вызывает все зарегистрированные cleanup-функции
|
||||
- [ ] Тест проверяет, что onunload очищает очередь после выполнения
|
||||
- [ ] Тест проверяет, что defaultSettings возвращает пустой объект
|
||||
- [ ] Все тесты проходят (npm test)
|
||||
|
||||
**Context:** BaseModule — абстрактный класс-основа для всех модулей. Находится в src/modules/base-module.ts. Для тестов нужно настроить тестовый раннер (jest или vitest) и mock-объект Plugin из obsidian.
|
||||
|
||||
---
|
||||
|
||||
### T3: Написать тесты для Attachment Clean Paste модуля
|
||||
|
||||
**Type:** test
|
||||
**Description:** Добавить unit-тесты для AttachmentCleanPasteModule: проверка shouldProcess (фильтрация расширений), обработка paste/drop событий.
|
||||
|
||||
**Files:**
|
||||
- `src/modules/attachment-clean-paste/index.ts`
|
||||
- `tests/modules/attachment-clean-paste.test.ts`
|
||||
|
||||
**Depends on:** T2
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Тест проверяет shouldProcess с разными расширениями и настройками
|
||||
- [ ] Тест проверяет, что обработчик paste вызывает preventDefault для файлов с подходящими расширениями
|
||||
- [ ] Тест проверяет, что модуль корректно создаёт ссылку [[path|name]]
|
||||
- [ ] Все тесты проходят (npm test)
|
||||
|
||||
**Context:** Attachment Clean Paste обрабатывает editor-paste и editor-drop события. Основная логика: shouldProcess (фильтрация по extensions) и processFile (копирование + создание ссылки).
|
||||
|
||||
---
|
||||
|
||||
### T4: Написать тесты для Preserve Link Aliases модуля
|
||||
|
||||
**Type:** test
|
||||
**Description:** Добавить unit-тесты для PreserveLinkAliasesModule: проверка processContent (замена алиасов), getFilesToProcess (фильтрация файлов), обработка rename.
|
||||
|
||||
**Files:**
|
||||
- `src/modules/preserve-link-aliases/index.ts`
|
||||
- `tests/modules/preserve-link-aliases.test.ts`
|
||||
|
||||
**Depends on:** T2
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Тест проверяет processContent: замена алиаса при переименовании
|
||||
- [ ] Тест проверяет processContent: игнорирование ссылок без алиаса
|
||||
- [ ] Тест проверяет processContent: учёт флага processEmbeds
|
||||
- [ ] Тест проверяет getFilesToProcess: включение canvas-файлов при processCanvas=true
|
||||
- [ ] Все тесты проходят (npm test)
|
||||
|
||||
**Context:** Preserve Link Aliases обрабатывает vault rename. Основная логика: processContent (регулярное выражение для вики-ссылок) и getFilesToProcess (сбор markdown + опционально canvas).
|
||||
|
||||
---
|
||||
|
||||
### T5: Добавить CI workflow для тестов и линтинга
|
||||
|
||||
**Type:** config
|
||||
**Description:** Добавить GitHub Actions workflow для автоматического запуска тестов и ESLint на push/PR в main/dev.
|
||||
|
||||
**Files:**
|
||||
- `.github/workflows/ci.yml`
|
||||
|
||||
**Depends on:** T1, T3, T4
|
||||
|
||||
**Acceptance Criteria:**
|
||||
- [ ] Workflow запускается на push и pull_request в main и dev
|
||||
- [ ] Workflow выполняет npm ci, npm run lint, npm test
|
||||
- [ ] Workflow завершается с ошибкой при падении тестов или линтера
|
||||
|
||||
**Context:** Существующий release.yml в .github/workflows/ — можно использовать как шаблон. Node 20, ubuntu-latest.
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"root": true,
|
||||
"parser": "@typescript-eslint/parser",
|
||||
"parserOptions": {
|
||||
"ecmaVersion": 2022,
|
||||
"sourceType": "module",
|
||||
"project": "./tsconfig.json"
|
||||
},
|
||||
"plugins": ["@typescript-eslint"],
|
||||
"extends": [
|
||||
"eslint:recommended",
|
||||
"plugin:@typescript-eslint/recommended",
|
||||
"prettier"
|
||||
],
|
||||
"env": {
|
||||
"browser": true,
|
||||
"es2022": true,
|
||||
"node": true
|
||||
},
|
||||
"ignorePatterns": [
|
||||
"node_modules/",
|
||||
"main.js",
|
||||
"*.config.mjs",
|
||||
"*.config.js",
|
||||
"*.config.cjs"
|
||||
],
|
||||
"rules": {
|
||||
"no-unused-vars": "off",
|
||||
"@typescript-eslint/no-unused-vars": [
|
||||
"warn",
|
||||
{
|
||||
"argsIgnorePattern": "^_",
|
||||
"varsIgnorePattern": "^_",
|
||||
"caughtErrorsIgnorePattern": "^_"
|
||||
}
|
||||
],
|
||||
"@typescript-eslint/no-explicit-any": "warn",
|
||||
"@typescript-eslint/no-non-null-assertion": "warn",
|
||||
"@typescript-eslint/ban-ts-comment": "warn",
|
||||
"@typescript-eslint/ban-types": "warn",
|
||||
"@typescript-eslint/no-empty-function": "warn",
|
||||
"no-empty": ["warn", { "allowEmptyCatch": true }],
|
||||
"no-console": "off",
|
||||
"prefer-const": "warn",
|
||||
"eqeqeq": ["warn", "smart"],
|
||||
"no-var": "warn",
|
||||
"no-debugger": "warn"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
pull_request:
|
||||
branches:
|
||||
- main
|
||||
- dev
|
||||
|
||||
jobs:
|
||||
ci:
|
||||
name: Lint & Test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
@@ -5,11 +5,16 @@ on:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
release:
|
||||
name: Lint, Test, Build & Release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
@@ -20,22 +25,30 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: npm ci
|
||||
|
||||
- name: Lint
|
||||
run: npm run lint
|
||||
|
||||
- name: Test
|
||||
run: npm test
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
|
||||
- name: Verify version
|
||||
- name: Verify tag version matches manifest
|
||||
run: |
|
||||
TAG_VERSION="${GITHUB_REF_NAME#v}"
|
||||
MANIFEST_VERSION=$(node -p "require('./manifest.json').version")
|
||||
if [ "$TAG_VERSION" != "$MANIFEST_VERSION" ]; then
|
||||
echo "❌ Tag ($TAG_VERSION) != manifest ($MANIFEST_VERSION)"
|
||||
echo "::error::Tag version ($TAG_VERSION) does not match manifest.json version ($MANIFEST_VERSION)"
|
||||
exit 1
|
||||
fi
|
||||
echo "✅ Version match: $TAG_VERSION"
|
||||
|
||||
- name: Create Release
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
name: ${{ github.ref_name }}
|
||||
generate_release_notes: true
|
||||
files: |
|
||||
main.js
|
||||
manifest.json
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
node_modules/
|
||||
main.js
|
||||
*.config.mjs
|
||||
*.config.js
|
||||
*.config.cjs
|
||||
package-lock.json
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"useTabs": true,
|
||||
"tabWidth": 4,
|
||||
"printWidth": 100,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"trailingComma": "all",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Minimal Obsidian API mock for unit tests.
|
||||
// Surface area covers what the QoL modules need: BaseModule, PreserveLinkAliasesModule, etc.
|
||||
|
||||
export class Plugin {
|
||||
// Intentionally minimal — tests supply their own `{}` when calling onunload.
|
||||
}
|
||||
|
||||
export class TFile {
|
||||
name: string;
|
||||
path: string;
|
||||
basename: string;
|
||||
extension: string;
|
||||
|
||||
constructor(path: string = '') {
|
||||
this.path = path;
|
||||
const lastSlash = path.lastIndexOf('/');
|
||||
const fileName = lastSlash >= 0 ? path.slice(lastSlash + 1) : path;
|
||||
this.name = fileName;
|
||||
const dotIndex = fileName.lastIndexOf('.');
|
||||
this.basename = dotIndex > 0 ? fileName.slice(0, dotIndex) : fileName;
|
||||
this.extension = dotIndex > 0 ? fileName.slice(dotIndex + 1) : '';
|
||||
}
|
||||
}
|
||||
|
||||
export class ToggleComponent {
|
||||
private value = false;
|
||||
|
||||
setValue(value: boolean): this {
|
||||
this.value = value;
|
||||
return this;
|
||||
}
|
||||
|
||||
onChange(_cb: (value: boolean) => unknown): this {
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export class Setting {
|
||||
constructor(_containerEl: HTMLElement) {}
|
||||
|
||||
setName(_name: string): this {
|
||||
return this;
|
||||
}
|
||||
|
||||
setDesc(_desc: string): this {
|
||||
return this;
|
||||
}
|
||||
|
||||
addToggle(cb: (toggle: ToggleComponent) => void): this {
|
||||
cb(new ToggleComponent());
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
export class Vault {
|
||||
// Pre-loaded file lists for getMarkdownFiles() / getFiles().
|
||||
mdFiles: TFile[] = [];
|
||||
allFiles: TFile[] = [];
|
||||
|
||||
// In-memory storage backing read()/modify().
|
||||
storage: Map<TFile, string> = new Map();
|
||||
|
||||
// Recording for assertions.
|
||||
readCalls: TFile[] = [];
|
||||
modifyCalls: Array<{ file: TFile; content: string }> = [];
|
||||
|
||||
// Listeners registered via on('rename', ...).
|
||||
private renameListeners: Array<(file: TFile, oldPath: string) => unknown> = [];
|
||||
|
||||
on(event: string, cb: (file: TFile, oldPath: string) => unknown): unknown {
|
||||
if (event === 'rename') {
|
||||
this.renameListeners.push(cb);
|
||||
return { id: this.renameListeners.length };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
offref(_ref: unknown): void {
|
||||
// no-op
|
||||
}
|
||||
|
||||
async read(file: TFile): Promise<string> {
|
||||
this.readCalls.push(file);
|
||||
return this.storage.get(file) ?? '';
|
||||
}
|
||||
|
||||
async modify(file: TFile, content: string): Promise<void> {
|
||||
this.modifyCalls.push({ file, content });
|
||||
this.storage.set(file, content);
|
||||
}
|
||||
|
||||
getMarkdownFiles(): TFile[] {
|
||||
return this.mdFiles;
|
||||
}
|
||||
|
||||
getFiles(): TFile[] {
|
||||
return this.allFiles;
|
||||
}
|
||||
}
|
||||
@@ -134,10 +134,7 @@ var AttachmentCleanPasteModule = class extends BaseModule {
|
||||
this.createPasteHandler(rawSettings)
|
||||
);
|
||||
this.registerCleanup(() => plugin.app.workspace.offref(pasteRef));
|
||||
const dropRef = plugin.app.workspace.on(
|
||||
"editor-drop",
|
||||
this.createDropHandler(rawSettings)
|
||||
);
|
||||
const dropRef = plugin.app.workspace.on("editor-drop", this.createDropHandler(rawSettings));
|
||||
this.registerCleanup(() => plugin.app.workspace.offref(dropRef));
|
||||
}
|
||||
renderInlineSettings(containerEl, settings, saveSettings) {
|
||||
@@ -154,9 +151,7 @@ var AttachmentCleanPasteModule = class extends BaseModule {
|
||||
});
|
||||
}
|
||||
async processAll(files, editor, settings, evt) {
|
||||
const matchingFiles = Array.from(files).filter(
|
||||
(f) => this.shouldProcess(f.name, settings)
|
||||
);
|
||||
const matchingFiles = Array.from(files).filter((f) => this.shouldProcess(f.name, settings));
|
||||
if (matchingFiles.length === 0)
|
||||
return;
|
||||
evt.preventDefault();
|
||||
@@ -205,9 +200,7 @@ var AttachmentCleanPasteModule = class extends BaseModule {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const filename = file.name;
|
||||
const nameWithoutExt = filename.replace(/\.[^/.]+$/, "");
|
||||
let attachmentFolder = this.app.vault.getConfig(
|
||||
"attachmentFolderPath"
|
||||
);
|
||||
let attachmentFolder = this.app.vault.getConfig("attachmentFolderPath");
|
||||
if (!attachmentFolder)
|
||||
attachmentFolder = "attachments";
|
||||
const folderPath = (0, import_obsidian.normalizePath)(attachmentFolder);
|
||||
@@ -216,10 +209,7 @@ var AttachmentCleanPasteModule = class extends BaseModule {
|
||||
}
|
||||
const ext = filename.slice(filename.lastIndexOf(".") + 1);
|
||||
const basePath = (0, import_obsidian.normalizePath)(`${folderPath}/${nameWithoutExt}`);
|
||||
const availablePath = await this.app.vault.getAvailablePath(
|
||||
basePath,
|
||||
ext
|
||||
);
|
||||
const availablePath = await this.app.vault.getAvailablePath(basePath, ext);
|
||||
await this.app.vault.createBinary(availablePath, arrayBuffer);
|
||||
return `[[${availablePath}|${nameWithoutExt}]]`;
|
||||
} catch (e) {
|
||||
@@ -282,7 +272,13 @@ var PreserveLinkAliasesModule = class extends BaseModule {
|
||||
const files = this.getFilesToProcess(settings);
|
||||
for (const f of files) {
|
||||
const content = await this.vault.read(f);
|
||||
const updated = this.processContent(content, newName, newBasename, oldBasename, settings);
|
||||
const updated = this.processContent(
|
||||
content,
|
||||
newName,
|
||||
newBasename,
|
||||
oldBasename,
|
||||
settings
|
||||
);
|
||||
if (updated !== content) {
|
||||
await this.vault.modify(f, updated);
|
||||
}
|
||||
@@ -418,11 +414,7 @@ var ZeroQoLModulesPlugin = class extends import_obsidian4.Plugin {
|
||||
}
|
||||
}
|
||||
async loadSettings() {
|
||||
this.settings = Object.assign(
|
||||
{},
|
||||
DEFAULT_SETTINGS,
|
||||
await this.loadData()
|
||||
);
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
|
||||
for (const module2 of MODULES) {
|
||||
if (!this.settings.modules[module2.id]) {
|
||||
this.settings.modules[module2.id] = {
|
||||
|
||||
Generated
+3491
-3
File diff suppressed because it is too large.
Load diff
+11
-1
@@ -6,6 +6,10 @@
|
||||
"scripts": {
|
||||
"dev": "node esbuild.config.mjs",
|
||||
"build": "node esbuild.config.mjs production",
|
||||
"test": "vitest run",
|
||||
"lint": "eslint src/",
|
||||
"format": "prettier --check src/",
|
||||
"format:fix": "prettier --write src/",
|
||||
"release": "bash scripts/release.sh"
|
||||
},
|
||||
"keywords": [
|
||||
@@ -15,10 +19,16 @@
|
||||
"author": "",
|
||||
"license": "MIT",
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/eslint-plugin": "^7.18.0",
|
||||
"@typescript-eslint/parser": "^7.18.0",
|
||||
"builtin-modules": "^3.3.0",
|
||||
"esbuild": "0.17.19",
|
||||
"eslint": "^8.57.1",
|
||||
"eslint-config-prettier": "^9.1.2",
|
||||
"obsidian": "latest",
|
||||
"prettier": "^3.9.6",
|
||||
"tslib": "^2.6.2",
|
||||
"typescript": "^5.3.3"
|
||||
"typescript": "^5.3.3",
|
||||
"vitest": "^1.6.1"
|
||||
}
|
||||
}
|
||||
+1
-2
@@ -42,8 +42,7 @@ export const en: Locale = {
|
||||
},
|
||||
'preserve-link-aliases': {
|
||||
name: 'Preserve Link Aliases',
|
||||
description:
|
||||
'Preserves original link aliases when attachments are renamed',
|
||||
description: 'Preserves original link aliases when attachments are renamed',
|
||||
processEmbedsLabel: 'Process embed links',
|
||||
processEmbedsDesc: 'Also process ![[embed]] links (disabled by default)',
|
||||
processCanvasLabel: 'Process Canvas files',
|
||||
|
||||
+1
-2
@@ -19,8 +19,7 @@ export const ru: Locale = {
|
||||
},
|
||||
'preserve-link-aliases': {
|
||||
name: 'Сохранение алиасов ссылок',
|
||||
description:
|
||||
'Сохраняет оригинальные алиасы ссылок при переименовании вложений',
|
||||
description: 'Сохраняет оригинальные алиасы ссылок при переименовании вложений',
|
||||
processEmbedsLabel: 'Обрабатывать embed-ссылки',
|
||||
processEmbedsDesc: 'Также обрабатывать ![[embed]] ссылки (по умолчанию выключено)',
|
||||
processCanvasLabel: 'Обрабатывать Canvas-файлы',
|
||||
|
||||
+1
-5
@@ -27,11 +27,7 @@ export default class ZeroQoLModulesPlugin extends Plugin {
|
||||
}
|
||||
|
||||
async loadSettings() {
|
||||
this.settings = Object.assign(
|
||||
{},
|
||||
DEFAULT_SETTINGS,
|
||||
await this.loadData(),
|
||||
) as ZeroQSettings;
|
||||
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData()) as ZeroQSettings;
|
||||
|
||||
for (const module of MODULES) {
|
||||
if (!this.settings.modules[module.id]) {
|
||||
|
||||
@@ -40,10 +40,7 @@ export class AttachmentCleanPasteModule extends BaseModule {
|
||||
);
|
||||
this.registerCleanup(() => plugin.app.workspace.offref(pasteRef));
|
||||
|
||||
const dropRef = plugin.app.workspace.on(
|
||||
'editor-drop',
|
||||
this.createDropHandler(rawSettings),
|
||||
);
|
||||
const dropRef = plugin.app.workspace.on('editor-drop', this.createDropHandler(rawSettings));
|
||||
this.registerCleanup(() => plugin.app.workspace.offref(dropRef));
|
||||
}
|
||||
|
||||
@@ -77,9 +74,7 @@ export class AttachmentCleanPasteModule extends BaseModule {
|
||||
settings: AttachmentCleanPasteSettings,
|
||||
evt: ClipboardEvent | DragEvent,
|
||||
): Promise<void> {
|
||||
const matchingFiles = Array.from(files).filter((f) =>
|
||||
this.shouldProcess(f.name, settings),
|
||||
);
|
||||
const matchingFiles = Array.from(files).filter((f) => this.shouldProcess(f.name, settings));
|
||||
if (matchingFiles.length === 0) return;
|
||||
|
||||
evt.preventDefault();
|
||||
@@ -121,10 +116,7 @@ export class AttachmentCleanPasteModule extends BaseModule {
|
||||
};
|
||||
}
|
||||
|
||||
private shouldProcess(
|
||||
filename: string,
|
||||
settings: AttachmentCleanPasteSettings,
|
||||
): boolean {
|
||||
private shouldProcess(filename: string, settings: AttachmentCleanPasteSettings): boolean {
|
||||
const dotIndex = filename.lastIndexOf('.');
|
||||
if (dotIndex === -1) return false;
|
||||
const ext = filename.slice(dotIndex + 1).toLowerCase();
|
||||
@@ -149,9 +141,7 @@ export class AttachmentCleanPasteModule extends BaseModule {
|
||||
const filename = file.name;
|
||||
const nameWithoutExt = filename.replace(/\.[^/.]+$/, '');
|
||||
|
||||
let attachmentFolder = this.app.vault.getConfig(
|
||||
'attachmentFolderPath',
|
||||
) as string;
|
||||
let attachmentFolder = this.app.vault.getConfig('attachmentFolderPath') as string;
|
||||
if (!attachmentFolder) attachmentFolder = 'attachments';
|
||||
|
||||
const folderPath = normalizePath(attachmentFolder);
|
||||
@@ -162,10 +152,7 @@ export class AttachmentCleanPasteModule extends BaseModule {
|
||||
const ext = filename.slice(filename.lastIndexOf('.') + 1);
|
||||
const basePath = normalizePath(`${folderPath}/${nameWithoutExt}`);
|
||||
|
||||
const availablePath = await this.app.vault.getAvailablePath(
|
||||
basePath,
|
||||
ext,
|
||||
);
|
||||
const availablePath = await this.app.vault.getAvailablePath(basePath, ext);
|
||||
|
||||
await this.app.vault.createBinary(availablePath, arrayBuffer);
|
||||
|
||||
|
||||
@@ -28,9 +28,8 @@ export class PreserveLinkAliasesModule extends BaseModule {
|
||||
this.vault = plugin.app.vault;
|
||||
const rawSettings = moduleSettings as PreserveLinkAliasesSettings;
|
||||
|
||||
const renameRef = plugin.app.vault.on(
|
||||
'rename',
|
||||
(file: TFile, oldPath: string) => this.handleRename(file, oldPath, rawSettings),
|
||||
const renameRef = plugin.app.vault.on('rename', (file: TFile, oldPath: string) =>
|
||||
this.handleRename(file, oldPath, rawSettings),
|
||||
);
|
||||
this.registerCleanup(() => plugin.app.vault.offref(renameRef));
|
||||
}
|
||||
@@ -47,24 +46,20 @@ export class PreserveLinkAliasesModule extends BaseModule {
|
||||
.setName(loc.processEmbedsLabel)
|
||||
.setDesc(loc.processEmbedsDesc)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(s.processEmbeds)
|
||||
.onChange(async (value) => {
|
||||
s.processEmbeds = value;
|
||||
await saveSettings();
|
||||
}),
|
||||
toggle.setValue(s.processEmbeds).onChange(async (value) => {
|
||||
s.processEmbeds = value;
|
||||
await saveSettings();
|
||||
}),
|
||||
);
|
||||
|
||||
new Setting(containerEl)
|
||||
.setName(loc.processCanvasLabel)
|
||||
.setDesc(loc.processCanvasDesc)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(s.processCanvas)
|
||||
.onChange(async (value) => {
|
||||
s.processCanvas = value;
|
||||
await saveSettings();
|
||||
}),
|
||||
toggle.setValue(s.processCanvas).onChange(async (value) => {
|
||||
s.processCanvas = value;
|
||||
await saveSettings();
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -85,7 +80,13 @@ export class PreserveLinkAliasesModule extends BaseModule {
|
||||
|
||||
for (const f of files) {
|
||||
const content = await this.vault.read(f);
|
||||
const updated = this.processContent(content, newName, newBasename, oldBasename, settings);
|
||||
const updated = this.processContent(
|
||||
content,
|
||||
newName,
|
||||
newBasename,
|
||||
oldBasename,
|
||||
settings,
|
||||
);
|
||||
|
||||
if (updated !== content) {
|
||||
await this.vault.modify(f, updated);
|
||||
|
||||
+18
-22
@@ -51,31 +51,27 @@ export class ZeroQSettingTab extends PluginSettingTab {
|
||||
.setName(module.name)
|
||||
.setDesc(module.description)
|
||||
.addToggle((toggle) =>
|
||||
toggle
|
||||
.setValue(moduleCfg?.enabled ?? true)
|
||||
.onChange(async (value) => {
|
||||
if (!this.plugin.settings.modules[module.id]) {
|
||||
this.plugin.settings.modules[module.id] = {
|
||||
enabled: value,
|
||||
settings: { ...module.defaultSettings },
|
||||
};
|
||||
} else {
|
||||
this.plugin.settings.modules[module.id].enabled = value;
|
||||
}
|
||||
await this.plugin.saveSettings();
|
||||
if (value) {
|
||||
this.plugin.loadModule(module);
|
||||
} else {
|
||||
this.plugin.unloadModule(module);
|
||||
}
|
||||
}),
|
||||
toggle.setValue(moduleCfg?.enabled ?? true).onChange(async (value) => {
|
||||
if (!this.plugin.settings.modules[module.id]) {
|
||||
this.plugin.settings.modules[module.id] = {
|
||||
enabled: value,
|
||||
settings: { ...module.defaultSettings },
|
||||
};
|
||||
} else {
|
||||
this.plugin.settings.modules[module.id].enabled = value;
|
||||
}
|
||||
await this.plugin.saveSettings();
|
||||
if (value) {
|
||||
this.plugin.loadModule(module);
|
||||
} else {
|
||||
this.plugin.unloadModule(module);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
if (moduleCfg) {
|
||||
module.renderInlineSettings(
|
||||
containerEl,
|
||||
moduleCfg.settings,
|
||||
() => this.plugin.saveSettings(),
|
||||
module.renderInlineSettings(containerEl, moduleCfg.settings, () =>
|
||||
this.plugin.saveSettings(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,279 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// Mock the Obsidian API surface used by AttachmentCleanPasteModule.
|
||||
// vi.mock is hoisted above imports, so the module-under-test resolves to this
|
||||
// stub instead of the alias target in __mocks__/obsidian.ts (which only
|
||||
// exports `Plugin`).
|
||||
vi.mock('obsidian', () => ({
|
||||
App: class {},
|
||||
Editor: class {},
|
||||
MarkdownFileInfo: class {},
|
||||
MarkdownView: class {},
|
||||
Notice: class {
|
||||
constructor(public message: string) {}
|
||||
},
|
||||
Setting: class {
|
||||
constructor(_el: HTMLElement) {}
|
||||
setName(_n: string): this {
|
||||
return this;
|
||||
}
|
||||
setDesc(_d: string): this {
|
||||
return this;
|
||||
}
|
||||
addTextArea(_cb: (textarea: unknown) => void): this {
|
||||
return this;
|
||||
}
|
||||
},
|
||||
// Minimal normalizePath: collapses backslashes, collapses duplicate slashes,
|
||||
// strips leading/trailing slash. Sufficient for the inputs in these tests.
|
||||
normalizePath: (p: string): string =>
|
||||
p.replace(/\\/g, '/').replace(/\/+/g, '/').replace(/^\/|\/$/g, ''),
|
||||
Plugin: class {},
|
||||
}));
|
||||
|
||||
import { AttachmentCleanPasteModule } from '../../src/modules/attachment-clean-paste';
|
||||
|
||||
// Build a minimal File-like object compatible with the module's usage
|
||||
// (only `name` and `arrayBuffer()` are read).
|
||||
function createFile(name: string, content: string = 'data'): File {
|
||||
return {
|
||||
name,
|
||||
arrayBuffer: async () =>
|
||||
new TextEncoder().encode(content).buffer as ArrayBuffer,
|
||||
} as unknown as File;
|
||||
}
|
||||
|
||||
describe('AttachmentCleanPasteModule', () => {
|
||||
let module: AttachmentCleanPasteModule;
|
||||
let mockPlugin: Record<string, unknown>;
|
||||
let mockWorkspace: {
|
||||
on: ReturnType<typeof vi.fn>;
|
||||
offref: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let mockVault: {
|
||||
getConfig: ReturnType<typeof vi.fn>;
|
||||
adapter: { exists: ReturnType<typeof vi.fn> };
|
||||
createFolder: ReturnType<typeof vi.fn>;
|
||||
getAvailablePath: ReturnType<typeof vi.fn>;
|
||||
createBinary: ReturnType<typeof vi.fn>;
|
||||
};
|
||||
let pasteHandler:
|
||||
| ((evt: ClipboardEvent, editor: unknown, info: unknown) => Promise<void>)
|
||||
| null;
|
||||
let dropHandler:
|
||||
| ((evt: DragEvent, editor: unknown, info: unknown) => Promise<void>)
|
||||
| null;
|
||||
let settings: { extensions: string };
|
||||
|
||||
beforeEach(() => {
|
||||
pasteHandler = null;
|
||||
dropHandler = null;
|
||||
|
||||
mockWorkspace = {
|
||||
on: vi.fn((event: string, handler: unknown) => {
|
||||
if (event === 'editor-paste') {
|
||||
pasteHandler = handler as typeof pasteHandler;
|
||||
} else if (event === 'editor-drop') {
|
||||
dropHandler = handler as typeof dropHandler;
|
||||
}
|
||||
return { event, handler };
|
||||
}),
|
||||
offref: vi.fn(),
|
||||
};
|
||||
|
||||
const mockAdapter = {
|
||||
exists: vi.fn(async () => true),
|
||||
};
|
||||
|
||||
mockVault = {
|
||||
getConfig: vi.fn((key: string) =>
|
||||
key === 'attachmentFolderPath' ? 'attachments' : '',
|
||||
),
|
||||
adapter: mockAdapter,
|
||||
createFolder: vi.fn(async () => undefined),
|
||||
// Mirrors the real Obsidian contract: returns "<basePath>.<ext>".
|
||||
getAvailablePath: vi.fn(
|
||||
async (basePath: string, ext: string) => `${basePath}.${ext}`,
|
||||
),
|
||||
createBinary: vi.fn(async () => undefined),
|
||||
};
|
||||
|
||||
mockPlugin = {
|
||||
app: {
|
||||
workspace: mockWorkspace,
|
||||
vault: mockVault,
|
||||
},
|
||||
};
|
||||
|
||||
settings = { extensions: 'png, jpg' };
|
||||
|
||||
module = new AttachmentCleanPasteModule();
|
||||
module.onload(
|
||||
mockPlugin as unknown as Parameters<
|
||||
AttachmentCleanPasteModule['onload']
|
||||
>[0],
|
||||
settings,
|
||||
);
|
||||
});
|
||||
|
||||
describe('shouldProcess', () => {
|
||||
// Helper: mustProcess is a private method; reach it via a typed cast.
|
||||
const callShouldProcess = (
|
||||
filename: string,
|
||||
cfg: { extensions: string } = settings,
|
||||
): boolean =>
|
||||
(
|
||||
module as unknown as {
|
||||
shouldProcess: (
|
||||
f: string,
|
||||
s: { extensions: string },
|
||||
) => boolean;
|
||||
}
|
||||
).shouldProcess(filename, cfg);
|
||||
|
||||
it('возвращает true для расширений из настроек (png, jpg)', () => {
|
||||
expect(callShouldProcess('image.png')).toBe(true);
|
||||
expect(callShouldProcess('photo.jpg')).toBe(true);
|
||||
});
|
||||
|
||||
it('возвращает false для расширений НЕ из настроек (exe, zip)', () => {
|
||||
expect(callShouldProcess('malware.exe')).toBe(false);
|
||||
expect(callShouldProcess('archive.zip')).toBe(false);
|
||||
});
|
||||
|
||||
it('возвращает false для файлов без расширения', () => {
|
||||
expect(callShouldProcess('README')).toBe(false);
|
||||
expect(callShouldProcess('Makefile')).toBe(false);
|
||||
});
|
||||
|
||||
it('корректно обрабатывает запятые и пробелы в extensions ("png, jpg" → png и jpg)', () => {
|
||||
const cfg = { extensions: ' png , jpg ' };
|
||||
expect(callShouldProcess('image.png', cfg)).toBe(true);
|
||||
expect(callShouldProcess('photo.jpg', cfg)).toBe(true);
|
||||
// Negative case: gif is not in the list.
|
||||
expect(callShouldProcess('anim.gif', cfg)).toBe(false);
|
||||
});
|
||||
|
||||
it('case-insensitive: JPG матчится как jpg', () => {
|
||||
expect(callShouldProcess('IMAGE.JPG')).toBe(true);
|
||||
expect(callShouldProcess('photo.PNG')).toBe(true);
|
||||
expect(callShouldProcess('Mixed.JpG')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('paste handler (createPasteHandler)', () => {
|
||||
it('вызывает preventDefault для файлов с подходящими расширениями', async () => {
|
||||
const editor = { replaceSelection: vi.fn() };
|
||||
const file = createFile('image.png');
|
||||
|
||||
const preventDefault = vi.fn();
|
||||
const stopPropagation = vi.fn();
|
||||
const evt = {
|
||||
clipboardData: { files: [file] },
|
||||
preventDefault,
|
||||
stopPropagation,
|
||||
} as unknown as ClipboardEvent;
|
||||
|
||||
expect(pasteHandler).not.toBeNull();
|
||||
await pasteHandler!(evt, editor, {});
|
||||
|
||||
// Matching extension → processAll took over the event.
|
||||
expect(preventDefault).toHaveBeenCalledTimes(1);
|
||||
expect(stopPropagation).toHaveBeenCalledTimes(1);
|
||||
// The link was inserted into the editor.
|
||||
expect(editor.replaceSelection).toHaveBeenCalledTimes(1);
|
||||
expect(editor.replaceSelection).toHaveBeenCalledWith(
|
||||
'[[attachments/image.png|image]]',
|
||||
);
|
||||
});
|
||||
|
||||
it('НЕ вызывает preventDefault, если ни один файл не подходит по расширению', async () => {
|
||||
const editor = { replaceSelection: vi.fn() };
|
||||
const file = createFile('malware.exe');
|
||||
|
||||
const preventDefault = vi.fn();
|
||||
const stopPropagation = vi.fn();
|
||||
const evt = {
|
||||
clipboardData: { files: [file] },
|
||||
preventDefault,
|
||||
stopPropagation,
|
||||
} as unknown as ClipboardEvent;
|
||||
|
||||
expect(pasteHandler).not.toBeNull();
|
||||
await pasteHandler!(evt, editor, {});
|
||||
|
||||
expect(preventDefault).not.toHaveBeenCalled();
|
||||
expect(stopPropagation).not.toHaveBeenCalled();
|
||||
expect(editor.replaceSelection).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('processFile', () => {
|
||||
it('формирует ссылку в формате "[[path|name]]"', async () => {
|
||||
const file = createFile('image.png');
|
||||
|
||||
const result = await (
|
||||
module as unknown as {
|
||||
processFile: (
|
||||
f: File,
|
||||
s: { extensions: string },
|
||||
) => Promise<string | null>;
|
||||
}
|
||||
).processFile(file, settings);
|
||||
|
||||
expect(result).toBe('[[attachments/image.png|image]]');
|
||||
expect(mockVault.createBinary).toHaveBeenCalledTimes(1);
|
||||
// The binary payload was passed to the vault.
|
||||
const [, payload] = (
|
||||
mockVault.createBinary.mock.calls[0] as [string, ArrayBuffer]
|
||||
);
|
||||
expect(payload).toBeInstanceOf(ArrayBuffer);
|
||||
});
|
||||
|
||||
it('использует имя файла без расширения как alias', async () => {
|
||||
const file = createFile('my-screenshot.png');
|
||||
|
||||
const result = await (
|
||||
module as unknown as {
|
||||
processFile: (
|
||||
f: File,
|
||||
s: { extensions: string },
|
||||
) => Promise<string | null>;
|
||||
}
|
||||
).processFile(file, settings);
|
||||
|
||||
expect(result).toBe('[[attachments/my-screenshot.png|my-screenshot]]');
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultSettings', () => {
|
||||
it('содержит разумный список расширений по умолчанию', () => {
|
||||
expect(module.defaultSettings).toEqual({
|
||||
extensions: 'png, jpg, jpeg, gif, svg, webp, bmp, pdf',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('onload lifecycle', () => {
|
||||
it('регистрирует оба обработчика (editor-paste и editor-drop) в workspace', () => {
|
||||
expect(mockWorkspace.on).toHaveBeenCalledWith(
|
||||
'editor-paste',
|
||||
expect.any(Function),
|
||||
);
|
||||
expect(mockWorkspace.on).toHaveBeenCalledWith(
|
||||
'editor-drop',
|
||||
expect.any(Function),
|
||||
);
|
||||
});
|
||||
|
||||
it('onunload отключает оба зарегистрированных обработчика', () => {
|
||||
module.onunload(
|
||||
mockPlugin as unknown as Parameters<
|
||||
AttachmentCleanPasteModule['onunload']
|
||||
>[0],
|
||||
);
|
||||
|
||||
expect(mockWorkspace.offref).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { Plugin } from 'obsidian';
|
||||
import { BaseModule } from '../../src/modules/base-module';
|
||||
|
||||
// TestModule: minimal concrete subclass to exercise BaseModule behavior.
|
||||
// Exposes a `cleanupCount` accessor so tests can verify private state.
|
||||
class TestModule extends BaseModule {
|
||||
id = 'test-module';
|
||||
name = 'Test Module';
|
||||
description = 'Used in BaseModule unit tests';
|
||||
|
||||
// Test-only inspector: exposes the size of the private cleanupFns array.
|
||||
get cleanupCount(): number {
|
||||
return (this as unknown as { cleanupFns: (() => void)[] }).cleanupFns.length;
|
||||
}
|
||||
|
||||
// Surface protected registerCleanup for direct test access.
|
||||
public callRegisterCleanup(fn: () => void): void {
|
||||
this.registerCleanup(fn);
|
||||
}
|
||||
|
||||
onload(_plugin: Plugin, _moduleSettings: Record<string, unknown>): void {
|
||||
// no-op: BaseModule's onload contract is exercised elsewhere.
|
||||
}
|
||||
}
|
||||
|
||||
function makePlugin(): Plugin {
|
||||
// Hand-rolled minimal mock to avoid pulling the real Obsidian runtime.
|
||||
return {} as Plugin;
|
||||
}
|
||||
|
||||
describe('BaseModule', () => {
|
||||
it('registerCleanup добавляет функцию в очередь (cleanupFns)', () => {
|
||||
const module = new TestModule();
|
||||
const cleanup = vi.fn();
|
||||
|
||||
module.callRegisterCleanup(cleanup);
|
||||
|
||||
expect(module.cleanupCount).toBe(1);
|
||||
expect(cleanup).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('onunload вызывает все зарегистрированные cleanup-функции', () => {
|
||||
const module = new TestModule();
|
||||
const cleanupA = vi.fn();
|
||||
const cleanupB = vi.fn();
|
||||
|
||||
module.callRegisterCleanup(cleanupA);
|
||||
module.callRegisterCleanup(cleanupB);
|
||||
|
||||
module.onunload(makePlugin());
|
||||
|
||||
expect(cleanupA).toHaveBeenCalledTimes(1);
|
||||
expect(cleanupB).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('onunload очищает очередь после выполнения (cleanupFns === [])', () => {
|
||||
const module = new TestModule();
|
||||
module.callRegisterCleanup(vi.fn());
|
||||
module.callRegisterCleanup(vi.fn());
|
||||
module.callRegisterCleanup(vi.fn());
|
||||
|
||||
expect(module.cleanupCount).toBe(3);
|
||||
|
||||
module.onunload(makePlugin());
|
||||
|
||||
expect(module.cleanupCount).toBe(0);
|
||||
});
|
||||
|
||||
it('defaultSettings возвращает пустой объект {}', () => {
|
||||
const module = new TestModule();
|
||||
|
||||
expect(module.defaultSettings).toEqual({});
|
||||
// Belt-and-suspenders: identity check for a fresh object each call.
|
||||
expect(module.defaultSettings).not.toBe(module.defaultSettings);
|
||||
});
|
||||
|
||||
it('несколько cleanup-функций: registerCleanup можно вызвать несколько раз и все выполнятся при onunload', () => {
|
||||
const module = new TestModule();
|
||||
const fns = [vi.fn(), vi.fn(), vi.fn(), vi.fn()];
|
||||
|
||||
for (const fn of fns) {
|
||||
module.callRegisterCleanup(fn);
|
||||
}
|
||||
|
||||
expect(module.cleanupCount).toBe(fns.length);
|
||||
|
||||
module.onunload(makePlugin());
|
||||
|
||||
for (const fn of fns) {
|
||||
expect(fn).toHaveBeenCalledTimes(1);
|
||||
}
|
||||
expect(module.cleanupCount).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { TFile, Vault } from 'obsidian';
|
||||
import { PreserveLinkAliasesModule } from '../../src/modules/preserve-link-aliases';
|
||||
|
||||
interface PreserveLinkAliasesSettings {
|
||||
processEmbeds: boolean;
|
||||
processCanvas: boolean;
|
||||
}
|
||||
|
||||
// TestablePreserveLinkAliasesModule: surface the private members so tests
|
||||
// can invoke processContent / getFilesToProcess / handleRename directly.
|
||||
class TestablePreserveLinkAliasesModule extends PreserveLinkAliasesModule {
|
||||
public callProcessContent(
|
||||
content: string,
|
||||
newFileName: string,
|
||||
newBasename: string,
|
||||
oldBasename: string,
|
||||
settings: PreserveLinkAliasesSettings,
|
||||
): string {
|
||||
return (this as unknown as {
|
||||
processContent: (
|
||||
c: string,
|
||||
nf: string,
|
||||
nb: string,
|
||||
ob: string,
|
||||
s: PreserveLinkAliasesSettings,
|
||||
) => string;
|
||||
}).processContent(content, newFileName, newBasename, oldBasename, settings);
|
||||
}
|
||||
|
||||
public callGetFilesToProcess(settings: PreserveLinkAliasesSettings): TFile[] {
|
||||
return (this as unknown as {
|
||||
getFilesToProcess: (s: PreserveLinkAliasesSettings) => TFile[];
|
||||
}).getFilesToProcess(settings);
|
||||
}
|
||||
|
||||
public async callHandleRename(
|
||||
file: TFile,
|
||||
oldPath: string,
|
||||
settings: PreserveLinkAliasesSettings,
|
||||
): Promise<void> {
|
||||
await (this as unknown as {
|
||||
handleRename: (f: TFile, op: string, s: PreserveLinkAliasesSettings) => Promise<void>;
|
||||
}).handleRename(file, oldPath, settings);
|
||||
}
|
||||
|
||||
public setVault(vault: Vault): void {
|
||||
(this as unknown as { vault: Vault }).vault = vault;
|
||||
}
|
||||
}
|
||||
|
||||
function makeModule(vault?: Vault): TestablePreserveLinkAliasesModule {
|
||||
const module = new TestablePreserveLinkAliasesModule();
|
||||
if (vault) {
|
||||
module.setVault(vault);
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
function makeVault(opts: {
|
||||
mdFiles?: TFile[];
|
||||
allFiles?: TFile[];
|
||||
storage?: Map<TFile, string>;
|
||||
} = {}): Vault {
|
||||
const vault = new Vault();
|
||||
vault.mdFiles = opts.mdFiles ?? [];
|
||||
vault.allFiles = opts.allFiles ?? [];
|
||||
if (opts.storage) {
|
||||
for (const [k, v] of opts.storage) {
|
||||
vault.storage.set(k, v);
|
||||
}
|
||||
}
|
||||
return vault;
|
||||
}
|
||||
|
||||
describe('PreserveLinkAliasesModule', () => {
|
||||
let module: TestablePreserveLinkAliasesModule;
|
||||
|
||||
beforeEach(() => {
|
||||
module = makeModule();
|
||||
});
|
||||
|
||||
// 1. processContent заменяет алиас при переименовании: [[file.md|newname]] → [[file.md|oldname]]
|
||||
describe('processContent', () => {
|
||||
it('заменяет алиас при переименовании: [[file.md|newname]] → [[file.md|oldname]]', () => {
|
||||
const settings: PreserveLinkAliasesSettings = {
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
};
|
||||
|
||||
const result = module.callProcessContent(
|
||||
'See [[file.md|newname]] for details.',
|
||||
'file.md',
|
||||
'newname',
|
||||
'oldname',
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(result).toBe('See [[file.md|oldname]] for details.');
|
||||
});
|
||||
|
||||
// 2. processContent игнорирует ссылки без алиаса (без |): [[file.md]] остаётся без изменений
|
||||
it('игнорирует ссылки без алиаса (без |): [[file.md]] остаётся без изменений', () => {
|
||||
const settings: PreserveLinkAliasesSettings = {
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
};
|
||||
|
||||
const content = 'Plain link: [[file.md]] stays the same.';
|
||||
const result = module.callProcessContent(
|
||||
content,
|
||||
'file.md',
|
||||
'newname',
|
||||
'oldname',
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(result).toBe(content);
|
||||
});
|
||||
|
||||
// 3. processContent игнорирует ссылки, где алиас НЕ равен newBasename
|
||||
it('игнорирует ссылки, где алиас НЕ равен newBasename', () => {
|
||||
const settings: PreserveLinkAliasesSettings = {
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
};
|
||||
|
||||
const content = 'Other alias: [[file.md|otheralias]] is untouched.';
|
||||
const result = module.callProcessContent(
|
||||
content,
|
||||
'file.md',
|
||||
'newname',
|
||||
'oldname',
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(result).toBe(content);
|
||||
});
|
||||
|
||||
// 4a. processContent учитывает флаг processEmbeds: ![[file.md|newname]] → ![[file.md|oldname]] (если true)
|
||||
it('обрабатывает ![[embed]] когда processEmbeds=true', () => {
|
||||
const settings: PreserveLinkAliasesSettings = {
|
||||
processEmbeds: true,
|
||||
processCanvas: false,
|
||||
};
|
||||
|
||||
const result = module.callProcessContent(
|
||||
'Embedded: ![[file.md|newname]] here.',
|
||||
'file.md',
|
||||
'newname',
|
||||
'oldname',
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(result).toBe('Embedded: ![[file.md|oldname]] here.');
|
||||
});
|
||||
|
||||
// 4b. processContent игнорирует (если false)
|
||||
it('игнорирует ![[embed]] когда processEmbeds=false', () => {
|
||||
const settings: PreserveLinkAliasesSettings = {
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
};
|
||||
|
||||
const content = 'Embedded: ![[file.md|newname]] stays untouched.';
|
||||
const result = module.callProcessContent(
|
||||
content,
|
||||
'file.md',
|
||||
'newname',
|
||||
'oldname',
|
||||
settings,
|
||||
);
|
||||
|
||||
expect(result).toBe(content);
|
||||
});
|
||||
});
|
||||
|
||||
// 5. getFilesToProcess включает canvas-файлы при processCanvas=true
|
||||
// 6. getFilesToProcess НЕ включает canvas-файлы при processCanvas=false
|
||||
describe('getFilesToProcess', () => {
|
||||
const mdA = new TFile('notes/a.md');
|
||||
const mdB = new TFile('notes/b.md');
|
||||
const canvasX = new TFile('boards/x.canvas');
|
||||
const pdfF = new TFile('papers/f.pdf');
|
||||
|
||||
it('включает canvas-файлы при processCanvas=true', () => {
|
||||
const vault = makeVault({
|
||||
mdFiles: [mdA, mdB],
|
||||
allFiles: [mdA, mdB, canvasX, pdfF],
|
||||
});
|
||||
const moduleWithVault = makeModule(vault);
|
||||
|
||||
const result = moduleWithVault.callGetFilesToProcess({
|
||||
processEmbeds: false,
|
||||
processCanvas: true,
|
||||
});
|
||||
|
||||
expect(result).toEqual([mdA, mdB, canvasX]);
|
||||
});
|
||||
|
||||
it('НЕ включает canvas-файлы при processCanvas=false', () => {
|
||||
const vault = makeVault({
|
||||
mdFiles: [mdA, mdB],
|
||||
allFiles: [mdA, mdB, canvasX, pdfF],
|
||||
});
|
||||
const moduleWithVault = makeModule(vault);
|
||||
|
||||
const result = moduleWithVault.callGetFilesToProcess({
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
});
|
||||
|
||||
expect(result).toEqual([mdA, mdB]);
|
||||
});
|
||||
});
|
||||
|
||||
// 7. handleRename не вызывает processContent если oldBasename === newBasename
|
||||
describe('handleRename', () => {
|
||||
it('не вызывает processContent если oldBasename === newBasename', async () => {
|
||||
const file = new TFile('notes/note.md');
|
||||
const vault = makeVault({
|
||||
mdFiles: [file],
|
||||
storage: new Map([[file, 'See [[other.md|note]] here.']]),
|
||||
});
|
||||
const moduleWithVault = makeModule(vault);
|
||||
|
||||
await moduleWithVault.callHandleRename(file, 'notes/note.md', {
|
||||
processEmbeds: false,
|
||||
processCanvas: false,
|
||||
});
|
||||
|
||||
expect(vault.readCalls).toEqual([]);
|
||||
expect(vault.modifyCalls).toEqual([]);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,13 @@
|
||||
// Vitest setup file: provides minimal DOM globals required by
|
||||
// src/locales/index.ts (detectLocale reads document.documentElement.lang).
|
||||
// Runs before any test file is imported.
|
||||
|
||||
if (typeof (globalThis as { document?: unknown }).document === 'undefined') {
|
||||
Object.defineProperty(globalThis, 'document', {
|
||||
value: {
|
||||
documentElement: { lang: 'en' },
|
||||
},
|
||||
writable: true,
|
||||
configurable: true,
|
||||
});
|
||||
}
|
||||
+3
-2
@@ -11,7 +11,8 @@
|
||||
"lib": ["DOM", "ES5", "ES6", "ES7"],
|
||||
"allowSyntheticDefaultImports": true,
|
||||
"strictNullChecks": true,
|
||||
"esModuleInterop": true
|
||||
"esModuleInterop": true,
|
||||
"types": ["vitest/globals", "node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
"include": ["src/**/*.ts", "tests/**/*.ts", "vitest.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { defineConfig } from 'vitest/config';
|
||||
|
||||
export default defineConfig({
|
||||
esbuild: {
|
||||
target: 'es2020',
|
||||
tsconfigRaw: {
|
||||
compilerOptions: {
|
||||
experimentalDecorators: true,
|
||||
useDefineForClassFields: false,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
globals: true,
|
||||
environment: 'node',
|
||||
include: ['tests/**/*.test.ts'],
|
||||
setupFiles: ['tests/setup.ts'],
|
||||
transformMode: {
|
||||
web: [/\.[jt]sx?$/],
|
||||
},
|
||||
},
|
||||
resolve: {
|
||||
alias: {
|
||||
obsidian: new URL('./__mocks__/obsidian.ts', import.meta.url).pathname,
|
||||
},
|
||||
},
|
||||
});
|
||||
Reference in new issue
Block a user