t1kit 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,73 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # t1kit
2
+
3
+ CLI-инструменты для фронтенд-проектов T1. Требуется Node.js 22 или новее.
4
+
5
+ ## Запуск
6
+
7
+ После публикации пакета, из корня микрофронта:
8
+
9
+ ```sh
10
+ npx t1kit semantic-migrate --dry-run
11
+ npx t1kit semantic-migrate
12
+ npx t1kit semantic-migrate --root /path/to/microfront
13
+ npx t1kit --help
14
+ npx t1kit semantic-migrate --help
15
+ ```
16
+
17
+ Для воспроизводимого запуска укажите версию: `npx t1kit@0.1.0 semantic-migrate`.
18
+
19
+ - [`semantic-migrate`](./src/commands/semantic-migrate/README.md) переводит проект с `front-semantic-theme` на `front-semantic-theme-ts`. Для операций с сабмодулем нужны Git, доступ к репозиторию темы и `sh` для `init.sh`, если он есть в проекте.
20
+
21
+ Из локальной копии репозитория команда доступна до публикации:
22
+
23
+ ```sh
24
+ node /path/to/scripts/bin/t1kit.mjs semantic-migrate --root /path/to/microfront --dry-run
25
+ ```
26
+
27
+ Старый запуск `node ../scripts/migrate-semantic-theme-ts/index.mjs` также работает.
28
+
29
+ ## Структура
30
+
31
+ ```text
32
+ bin/t1kit.mjs запуск и обработка ошибок
33
+ src/cli.mjs выбор команды, общая справка и версия
34
+ src/commands/index.mjs список команд с ленивыми импортами
35
+ src/commands/<name>/command.mjs аргументы и запуск конкретной команды
36
+ ```
37
+
38
+ Внутри папки команды хранятся её README, тесты и модули. Чистые преобразования текста отделены от работы с файлами и Git. Общие функции выносим только при реальном повторении между командами.
39
+
40
+ ## Добавление команды
41
+
42
+ 1. Создайте `src/commands/<name>/command.mjs` с экспортом `run(argv)`. Аргументы приходят без имени команды. Импорт модуля не должен запускать действия. Поддержите `--help` и отклоняйте неизвестные аргументы до изменения проекта.
43
+ 2. Зарегистрируйте команду в `src/commands/index.mjs`:
44
+
45
+ ```js
46
+ 'my-command': {
47
+ description: 'Описание команды',
48
+ load: () => import('./my-command/command.mjs'),
49
+ },
50
+ ```
51
+
52
+ 3. Добавьте README и необходимые тесты `*.test.mjs` рядом с командой. Выполните `npm test`.
53
+
54
+ Команда сразу появится в общей справке и будет доступна через `npx t1kit my-command` после публикации новой версии.
55
+
56
+ ## Проверка и публикация
57
+
58
+ Пакет работает без сборки и внешних npm-зависимостей.
59
+
60
+ ```sh
61
+ npm test
62
+ npm pack --dry-run
63
+ npm pack
64
+ npx --yes --package=./t1kit-0.1.0.tgz t1kit --help
65
+ ```
66
+
67
+ Для публикации под npm-аккаунтом с правом на имя `t1kit`:
68
+
69
+ ```sh
70
+ npm publish
71
+ ```
72
+
73
+ `prepublishOnly` запускает тесты перед публикацией. В архив входят CLI, модули команд, документация и обёртка старого запуска. Тесты исключены из пакета. Для следующих релизов обновляйте версию в `package.json`.
package/bin/t1kit.mjs ADDED
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import { runCli } from '../src/cli.mjs';
3
+
4
+ try {
5
+ await runCli(process.argv.slice(2));
6
+ } catch (error) {
7
+ console.error(error.message);
8
+ process.exitCode = 1;
9
+ }
@@ -0,0 +1,15 @@
1
+ # migrate-semantic-theme-ts
2
+
3
+ Совместимый со старым запуском вход в команду `semantic-migrate`:
4
+
5
+ ```sh
6
+ node ../scripts/migrate-semantic-theme-ts/index.mjs --dry-run
7
+ ```
8
+
9
+ После публикации npm-пакета:
10
+
11
+ ```sh
12
+ npx t1kit semantic-migrate --dry-run
13
+ ```
14
+
15
+ [Описание команды и её параметров](../src/commands/semantic-migrate/README.md).
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ import { pathToFileURL } from 'node:url';
3
+ import { run } from '../src/commands/semantic-migrate/command.mjs';
4
+
5
+ export { parseArgs } from '../src/commands/semantic-migrate/command.mjs';
6
+ export { componentTreeUsesPopup } from '../src/commands/semantic-migrate/host-tests.mjs';
7
+
8
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
9
+ try {
10
+ await run(process.argv.slice(2));
11
+ } catch (error) {
12
+ console.error(error.message);
13
+ process.exitCode = 1;
14
+ }
15
+ }
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
- {
2
- "name": "t1kit",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
1
+ {
2
+ "name": "t1kit",
3
+ "version": "0.1.1",
4
+ "description": "CLI tools for T1 frontend projects",
5
+ "type": "module",
6
+ "license": "UNLICENSED",
7
+ "bin": {
8
+ "t1kit": "bin/t1kit.mjs"
9
+ },
10
+ "files": [
11
+ "bin/",
12
+ "src/",
13
+ "!src/**/*.test.mjs",
14
+ "migrate-semantic-theme-ts/"
15
+ ],
16
+ "scripts": {
17
+ "test": "node --test",
18
+ "prepublishOnly": "npm test"
19
+ },
20
+ "engines": {
21
+ "node": ">=22"
22
+ },
23
+ "repository": {
24
+ "type": "git",
25
+ "url": "https://git-02.t1-group.ru/frontend/tools/scripts.git"
26
+ },
27
+ "publishConfig": {
28
+ "access": "public",
29
+ "registry": "https://registry.npmjs.org/"
30
+ }
31
+ }
package/src/cli.mjs ADDED
@@ -0,0 +1,35 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { commands } from './commands/index.mjs';
3
+
4
+ export const runCli = async argv => {
5
+ const [name, ...args] = argv;
6
+
7
+ if (!name || name === '--help' || name === '-h') {
8
+ console.log(`t1kit
9
+
10
+ Использование:
11
+ npx t1kit <command> [options]
12
+
13
+ Команды:
14
+ ${Object.entries(commands).map(([name, command]) => ` ${name} ${command.description}`).join('\n')}
15
+
16
+ npx t1kit <command> --help
17
+ npx t1kit --version`);
18
+
19
+ return;
20
+ }
21
+
22
+ if (name === '--version' || name === '-v') {
23
+ const { version } = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
24
+
25
+ console.log(version);
26
+ return;
27
+ }
28
+
29
+ if (!Object.hasOwn(commands, name)) {
30
+ throw new Error(`Неизвестная команда: ${name}. Доступные команды: ${Object.keys(commands).join(', ')}. Справка: npx t1kit --help`);
31
+ }
32
+
33
+ const command = await commands[name].load();
34
+ await command.run(args);
35
+ };
@@ -0,0 +1,6 @@
1
+ export const commands = {
2
+ 'semantic-migrate': {
3
+ description: 'Миграция с front-semantic-theme на front-semantic-theme-ts',
4
+ load: () => import('./semantic-migrate/command.mjs'),
5
+ },
6
+ };
@@ -0,0 +1,48 @@
1
+ # semantic-migrate
2
+
3
+ Команда `t1kit` для перевода микрофронта с `front-semantic-theme` на `front-semantic-theme-ts`.
4
+
5
+ После публикации пакета, из корня микрофронта:
6
+
7
+ ```sh
8
+ npx t1kit semantic-migrate
9
+ npx t1kit semantic-migrate --dry-run
10
+ npx t1kit semantic-migrate --yes
11
+ npx t1kit semantic-migrate --skip-submodule
12
+ ```
13
+
14
+ Или из любой папки:
15
+
16
+ ```sh
17
+ npx t1kit semantic-migrate --root /path/to/microfront
18
+ ```
19
+
20
+ `--root` по умолчанию равен текущей папке. В ней должен быть `package.json`. `--dry-run` показывает изменения без записи файлов и запуска Git. Неизвестные аргументы завершают команду с ошибкой до изменений. Установка зависимостей выполняется отдельно, флаг `--install` не поддерживается.
21
+
22
+ Из локальной копии репозитория можно запускать `node /path/to/scripts/bin/t1kit.mjs semantic-migrate` или старый `node /path/to/scripts/migrate-semantic-theme-ts/index.mjs` с теми же аргументами.
23
+
24
+ Перед заменой `src/semantic-ui` скрипт спрашивает подтверждение. Нужную работу в теме — commit и push в `front-semantic-theme` (stash в сабмодуле недостаточно: скрипт остановится). `--yes` / `-y` пропускает вопрос. Без TTY нужен `--yes`, иначе выход без изменений. `--skip-submodule` патчит только хост (URL в `.gitmodules`, без checkout).
25
+
26
+ ## Что меняет
27
+
28
+ - сабмодуль темы: как modules — `git rm` старый `src/semantic-ui`, `git submodule add -f ../../front-semantic-theme-ts src/semantic-ui`, `branch = main`, `sh init.sh` (промежуточный коммит не нужен: `git rm` убирает gitlink из индекса, иначе `already exists in the index`)
29
+ - README: URL темы → `front-semantic-theme-ts`
30
+ - `tsconfig.json`: `ES2022`, `moduleResolution: "bundler"`
31
+ - `vite.config.*`: `transformJsxInJs`, `optimizeDeps` `.js` → `jsx`, alias `fonts`
32
+ - `eslint.config.js`: TS без `parserOptions.project`, `eslint-import-resolver-typescript`, prettier off в `src/semantic-ui`
33
+ - `package.json`: `eslint-import-resolver-typescript@4.4.5` (дальше `yarn`, не правьте `yarn.lock` руками)
34
+
35
+ ## Тесты хоста (не сабмодуль)
36
+
37
+ `src/semantic-ui`, `src/api`, `src/modules` скрипт не трогает.
38
+
39
+ **AutoSizer / checkbox-list.** Если компонент импортирует `{ AutoSizer, List }` из `react-virtualized`, мок `react-virtualized/dist/commonjs/AutoSizer` ломается. Скрипт мокает пакет целиком, `importOriginal` / `requireActual`, подменяет только `AutoSizer` через `autoSizerProps.children({ height: 1000, width: 1000 })` — без деструктуризации `children` (`react/prop-types`). После живого AutoSizer снапшоты с пустой Grid 0×0 нужно обновить: `yarn test -u`.
40
+
41
+ **Popup + `userEvent.click`.** Portal у `semantic-ui-react` открывается по `mouseenter` через `setTimeout(0)` и не `clearTimeout` на unmount → после teardown Vitest: `ReferenceError: window is not defined`. Если тест не проверяет тултип, скрипт мокает `Popup: ({ trigger }) => trigger` через `vi.importActual('semantic-ui-react')`. Прод-код не менять.
42
+
43
+ После подтверждения скрипт **не** делает `sync`/`update` по старому имени (`front-semantic-theme`): это оставляет checkout JS-темы. Вместо этого — `deinit` + `git rm` + `submodule add -f` + `init.sh`. Коммит хоста после этого — ваш.
44
+
45
+ ## После скрипта
46
+
47
+ 1. `yarn`
48
+ 2. Прогнать тесты: `yarn test`. Если упали снапшоты списков (AutoSizer) — `yarn test -u` и проверить diff.
@@ -0,0 +1,214 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { createInterface } from 'node:readline/promises';
4
+ import { stdin, stdout } from 'node:process';
5
+ import { readIfExists, writeIfChanged } from './files.mjs';
6
+ import { patchHostTests } from './host-tests.mjs';
7
+ import { assertSemanticReplaceSafe, previewSemanticAddUrl, replaceSemanticSubmodule } from './submodule.mjs';
8
+ import {
9
+ SEMANTIC_SUBMODULE_PATH,
10
+ SEMANTIC_THEME_TS,
11
+ SEMANTIC_THEME_BRANCH,
12
+ patchEslintConfig,
13
+ patchGitmodules,
14
+ patchPackageJson,
15
+ patchTsconfig,
16
+ patchViteConfig,
17
+ } from './transforms.mjs';
18
+
19
+ const log = message => process.stdout.write(`${message}\n`);
20
+
21
+ export const parseArgs = argv => {
22
+ const args = { root: process.cwd(), dryRun: false, skipSubmodule: false, yes: false };
23
+
24
+ for (let i = 0; i < argv.length; i += 1) {
25
+ const token = argv[i];
26
+
27
+ if (token === '--dry-run') args.dryRun = true;
28
+ else if (token === '--skip-submodule') args.skipSubmodule = true;
29
+ else if (token === '--install') {
30
+ throw new Error('Флаг --install не поддерживается. После миграции выполните yarn в проекте.');
31
+ } else if (token === '--yes' || token === '-y') args.yes = true;
32
+ else if (token === '--root') {
33
+ if (!argv[i + 1] || argv[i + 1].startsWith('-')) {
34
+ throw new Error('После --root укажите путь к микрофронту.');
35
+ }
36
+ args.root = resolve(argv[i + 1]);
37
+ i += 1;
38
+ } else if (token === '--help' || token === '-h') args.help = true;
39
+ else throw new Error(`Неизвестный аргумент: ${token}. Справка: npx t1kit semantic-migrate --help`);
40
+ }
41
+
42
+ return args;
43
+ };
44
+
45
+ const printSemanticWarning = () => {
46
+ log(`
47
+ Внимание: сейчас будет замена сабмодуля ${SEMANTIC_SUBMODULE_PATH}
48
+ front-semantic-theme → ${SEMANTIC_THEME_TS}
49
+
50
+ Если в semantic есть нужная работа — закоммитьте и push в front-semantic-theme.
51
+ Stash в src/semantic-ui недостаточно: скрипт остановится, пока в теме есть
52
+ stash, грязное дерево или локальные коммиты без remote. Скрипт сам не коммитит хост.
53
+ `);
54
+ };
55
+
56
+ const printNextSteps = ({ snapshots } = { snapshots: false }) => {
57
+ log(`
58
+ Что сделать после:
59
+ 1. yarn
60
+ 2. Прогнать тесты: yarn test`);
61
+
62
+ if (snapshots) {
63
+ log(' Снапшоты списков могли измениться (AutoSizer). Если тесты упали на snapshot — yarn test -u и проверьте diff.');
64
+ }
65
+ };
66
+
67
+ const confirmSemanticReplace = async ({ yes }) => {
68
+ printSemanticWarning();
69
+
70
+ if (yes) {
71
+ log('Подтверждено флагом --yes.');
72
+ return true;
73
+ }
74
+
75
+ if (!stdin.isTTY) {
76
+ log('Нет TTY: передайте --yes, чтобы подтвердить замену, или --skip-submodule / --dry-run.');
77
+ return false;
78
+ }
79
+
80
+ const rl = createInterface({ input: stdin, output: stdout });
81
+ const answer = await rl.question('Продолжить замену semantic? Несохранённые изменения в теме будут потеряны. [y/N] ');
82
+ rl.close();
83
+
84
+ return /^(y|yes|д|да)$/i.test(answer.trim());
85
+ };
86
+
87
+ const printHelp = () => {
88
+ log(`t1kit semantic-migrate
89
+
90
+ Usage:
91
+ npx t1kit semantic-migrate [--root <microfront>] [--dry-run] [--skip-submodule] [--yes]
92
+
93
+ The project root defaults to the current working directory.
94
+
95
+ Steps:
96
+ 1. Warn and ask before switching src/semantic-ui to front-semantic-theme-ts
97
+ 2. git rm the old theme, git submodule add -f the -ts repo, branch = main, init.sh
98
+ 3. Patch tsconfig / vite / eslint / package.json for TS theme lint
99
+ 4. Rewrite host AutoSizer mocks (package mock, no children destructure)
100
+ 5. Mock semantic-ui-react Popup in click tests that do not assert a tooltip
101
+
102
+ Does not edit production host UI. --skip-submodule keeps the current theme checkout.`);
103
+ };
104
+
105
+ export const run = async argv => {
106
+ const args = parseArgs(argv);
107
+
108
+ if (args.help) {
109
+ printHelp();
110
+ return;
111
+ }
112
+
113
+ const { root, dryRun, skipSubmodule, yes } = args;
114
+
115
+ if (!existsSync(join(root, 'package.json'))) {
116
+ throw new Error(`Не найден package.json в ${root}. Запустите команду из корня микрофронта или передайте --root <путь>.`);
117
+ }
118
+
119
+ const changed = [];
120
+ const replaceSubmodule = !skipSubmodule && !dryRun;
121
+
122
+ log(`root: ${root}${dryRun ? ' (dry-run)' : ''}`);
123
+
124
+ if (dryRun && !skipSubmodule) {
125
+ printSemanticWarning();
126
+ log('(dry-run: git rm / submodule add / init.sh не выполняются)\n');
127
+ } else if (replaceSubmodule) {
128
+ const confirmed = await confirmSemanticReplace({ yes });
129
+
130
+ if (!confirmed) {
131
+ log('Отменено. Тема не тронута. Сначала сохраните изменения в semantic, затем запустите снова.');
132
+ process.exitCode = 1;
133
+ return;
134
+ }
135
+
136
+ assertSemanticReplaceSafe(root);
137
+ replaceSemanticSubmodule(root);
138
+ }
139
+
140
+ if (skipSubmodule) {
141
+ writeIfChanged({
142
+ dryRun,
143
+ path: join(root, '.gitmodules'),
144
+ previous: readIfExists(join(root, '.gitmodules')),
145
+ next: patchGitmodules(readIfExists(join(root, '.gitmodules')) || ''),
146
+ changed,
147
+ });
148
+ }
149
+
150
+ const readmePath = join(root, 'README.md');
151
+ const readme = readIfExists(readmePath);
152
+
153
+ if (readme) {
154
+ writeIfChanged({
155
+ dryRun,
156
+ path: readmePath,
157
+ previous: readme,
158
+ next: patchGitmodules(readme),
159
+ changed,
160
+ });
161
+ }
162
+
163
+ writeIfChanged({
164
+ dryRun,
165
+ path: join(root, 'tsconfig.json'),
166
+ previous: readIfExists(join(root, 'tsconfig.json')),
167
+ next: patchTsconfig(readIfExists(join(root, 'tsconfig.json')) || ''),
168
+ changed,
169
+ });
170
+
171
+ const vitePath = existsSync(join(root, 'vite.config.js')) ? join(root, 'vite.config.js') : join(root, 'vite.config.ts');
172
+ const hasJsxTransformer = existsSync(join(root, 'src/modules/plugins/jsxTransformer.js'));
173
+
174
+ writeIfChanged({
175
+ dryRun,
176
+ path: vitePath,
177
+ previous: readIfExists(vitePath),
178
+ next: patchViteConfig(readIfExists(vitePath) || '', { hasJsxTransformer }),
179
+ changed,
180
+ });
181
+
182
+ writeIfChanged({
183
+ dryRun,
184
+ path: join(root, 'eslint.config.js'),
185
+ previous: readIfExists(join(root, 'eslint.config.js')),
186
+ next: patchEslintConfig(readIfExists(join(root, 'eslint.config.js')) || ''),
187
+ changed,
188
+ });
189
+
190
+ writeIfChanged({
191
+ dryRun,
192
+ path: join(root, 'package.json'),
193
+ previous: readIfExists(join(root, 'package.json')),
194
+ next: patchPackageJson(readIfExists(join(root, 'package.json')) || '{}'),
195
+ changed,
196
+ });
197
+
198
+ const testNotes = patchHostTests({ root, dryRun, changed });
199
+
200
+ log('\nfiles:');
201
+ for (const item of changed) log(` ${item}`);
202
+
203
+ if (!replaceSubmodule && !skipSubmodule) {
204
+ const url = previewSemanticAddUrl(root);
205
+ log(`\nWould:
206
+ git submodule deinit -f -- ${SEMANTIC_SUBMODULE_PATH}
207
+ git rm -rf -- ${SEMANTIC_SUBMODULE_PATH}
208
+ git submodule add -f ${url} ${SEMANTIC_SUBMODULE_PATH}
209
+ # branch = ${SEMANTIC_THEME_BRANCH} in .gitmodules
210
+ sh init.sh`);
211
+ }
212
+
213
+ printNextSteps({ snapshots: testNotes.includes('snapshots') });
214
+ };
@@ -0,0 +1,21 @@
1
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
2
+ import { relative } from 'node:path';
3
+
4
+ export const readIfExists = path => (existsSync(path) ? readFileSync(path, 'utf8') : null);
5
+
6
+ export const writeIfChanged = ({ dryRun, path, next, previous, changed }) => {
7
+ if (previous === null) {
8
+ changed.push(`${relative(process.cwd(), path)} (missing, skipped)`);
9
+ return;
10
+ }
11
+
12
+ if (previous === next) {
13
+ changed.push(`${relative(process.cwd(), path)} (unchanged)`);
14
+ return;
15
+ }
16
+
17
+ changed.push(relative(process.cwd(), path));
18
+ if (!dryRun) {
19
+ writeFileSync(path, next);
20
+ }
21
+ };
@@ -0,0 +1,118 @@
1
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { readIfExists, writeIfChanged } from './files.mjs';
4
+ import { patchAutoSizerMocks, patchPopupMock } from './transforms.mjs';
5
+
6
+ const SKIP_DIRS = new Set([
7
+ '.git',
8
+ 'node_modules',
9
+ 'dist',
10
+ 'build',
11
+ 'coverage',
12
+ 'artifacts',
13
+ 'semantic-ui',
14
+ 'api',
15
+ 'modules',
16
+ ]);
17
+
18
+ const walk = (dir, files = []) => {
19
+ if (!existsSync(dir)) return files;
20
+
21
+ for (const entry of readdirSync(dir)) {
22
+ if (SKIP_DIRS.has(entry)) continue;
23
+
24
+ const full = join(dir, entry);
25
+ const stat = statSync(full);
26
+
27
+ if (stat.isDirectory()) walk(full, files);
28
+ else files.push(full);
29
+ }
30
+
31
+ return files;
32
+ };
33
+
34
+ const isTestFile = path => /\.(test|spec)\.[jt]sx?$/.test(path);
35
+
36
+ const readRelativeImports = (testPath, source) => {
37
+ const matches = [...source.matchAll(/from\s+['"](\.[^'"]+)['"]/g)].map(match => match[1]);
38
+ const files = [];
39
+
40
+ for (const specifier of matches) {
41
+ const base = resolve(dirname(testPath), specifier);
42
+ const candidates = [
43
+ base,
44
+ `${base}.js`,
45
+ `${base}.jsx`,
46
+ `${base}.ts`,
47
+ `${base}.tsx`,
48
+ join(base, 'index.js'),
49
+ join(base, 'index.jsx'),
50
+ join(base, 'index.ts'),
51
+ join(base, 'index.tsx'),
52
+ ];
53
+
54
+ const found = candidates.find(candidate => existsSync(candidate) && statSync(candidate).isFile());
55
+
56
+ if (found) files.push(found);
57
+ }
58
+
59
+ return files;
60
+ };
61
+
62
+ const SKIP_WALK = /[\\/](utils|actions|selectors|reducer|saga|constants|validation)([\\/.]|$)/;
63
+
64
+ const mockedSpecifiers = source =>
65
+ [...source.matchAll(/(?:vi|jest)\.mock\(\s*['"]([^'"]+)['"]/g)].map(match => match[1]);
66
+
67
+ const fileUsesSemanticPopup = path => {
68
+ const source = readIfExists(path);
69
+
70
+ if (!source) return false;
71
+
72
+ return /import\s*\{[^}]*\bPopup\b[^}]*\}\s*from\s*['"]semantic-ui-react['"]/.test(source);
73
+ };
74
+
75
+ export const componentTreeUsesPopup = (testPath, source) => {
76
+ const mocked = mockedSpecifiers(source);
77
+ const isSkipped = path =>
78
+ SKIP_WALK.test(path) ||
79
+ path.includes(`${join('src', 'semantic-ui')}`) ||
80
+ mocked.some(spec => path.replace(/\\/g, '/').includes(spec.replace(/^\.\//, '').replace(/\\/g, '/')));
81
+
82
+ const queue = readRelativeImports(testPath, source).filter(path => !isSkipped(path));
83
+ const seen = new Set();
84
+
85
+ while (queue.length) {
86
+ const path = queue.shift();
87
+
88
+ if (seen.has(path) || isSkipped(path)) continue;
89
+ seen.add(path);
90
+ if (fileUsesSemanticPopup(path)) return true;
91
+
92
+ const child = readIfExists(path);
93
+
94
+ if (child) queue.push(...readRelativeImports(path, child));
95
+ }
96
+
97
+ return false;
98
+ };
99
+
100
+ export const patchHostTests = ({ root, dryRun, changed }) => {
101
+ const src = join(root, 'src');
102
+ const notes = [];
103
+
104
+ for (const file of walk(src).filter(isTestFile)) {
105
+ const previous = readFileSync(file, 'utf8');
106
+ const withAutoSizer = patchAutoSizerMocks(previous);
107
+ const next = patchPopupMock(withAutoSizer, {
108
+ componentUsesPopup: componentTreeUsesPopup(file, withAutoSizer),
109
+ });
110
+
111
+ if (next !== previous) {
112
+ writeIfChanged({ dryRun, path: file, next, previous, changed });
113
+ if (withAutoSizer !== previous) notes.push('snapshots');
114
+ }
115
+ }
116
+
117
+ return notes;
118
+ };