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.
@@ -0,0 +1,773 @@
1
+ export const ESLINT_RESOLVER_PKG = 'eslint-import-resolver-typescript';
2
+ export const ESLINT_RESOLVER_VERSION = '4.4.5';
3
+
4
+ export const AUTO_SIZER_MOCK_VI = `vi.mock('react-virtualized', async importOriginal => {
5
+ const actual = await importOriginal();
6
+
7
+ return {
8
+ ...actual,
9
+ AutoSizer: autoSizerProps => <div>{autoSizerProps.children({ height: 1000, width: 1000 })}</div>,
10
+ };
11
+ });`;
12
+
13
+ export const AUTO_SIZER_MOCK_JEST = `jest.mock('react-virtualized', () => {
14
+ const actual = jest.requireActual('react-virtualized');
15
+
16
+ return {
17
+ ...actual,
18
+ AutoSizer: autoSizerProps => <div>{autoSizerProps.children({ height: 1000, width: 1000 })}</div>,
19
+ };
20
+ });`;
21
+
22
+ export const POPUP_MOCK_VI = `vi.mock('semantic-ui-react', async () => {
23
+ const actual = await vi.importActual('semantic-ui-react');
24
+
25
+ return {
26
+ ...actual,
27
+ Popup: ({ trigger }) => trigger,
28
+ };
29
+ });`;
30
+
31
+ export const POPUP_MOCK_JEST = `jest.mock('semantic-ui-react', () => {
32
+ const actual = jest.requireActual('semantic-ui-react');
33
+
34
+ return {
35
+ ...actual,
36
+ Popup: ({ trigger }) => trigger,
37
+ };
38
+ });`;
39
+
40
+ const ESLINT_HELPER = `import { existsSync } from 'node:fs';
41
+ import { dirname, join } from 'node:path';
42
+ import { fileURLToPath } from 'node:url';
43
+ `;
44
+
45
+ const ESLINT_CONSTANTS = `
46
+ const appRoot = dirname(fileURLToPath(import.meta.url));
47
+
48
+ const isInstalled = packageName => existsSync(join(appRoot, 'node_modules', packageName));
49
+
50
+ // Installed, but not resolvable by eslint-plugin-import (ESM-only \`exports\`, CSS entry).
51
+ const alwaysUnresolvedIgnore = ['^semantic-ui-css/semantic\\\\.min\\\\.css$', '^@vitejs/plugin-react$'];
52
+
53
+ // Shared-kit / generated modules. Ignore a pattern only when the package is not installed:
54
+ // a maps microfront with \`ol\` / \`maplibre-gl\` in package.json keeps those imports checked.
55
+ const optionalUnresolvedPackages = [
56
+ { packageName: 'ol', ignore: '^ol(/|$)' },
57
+ { packageName: 'ol-react-kit', ignore: '^ol-react-kit$' },
58
+ { packageName: '@contracts/proto-js', ignore: '@contracts/proto-js' },
59
+ { packageName: '@deck.gl/core', ignore: '@deck\\\\.gl' },
60
+ { packageName: 'react-map-gl', ignore: '^react-map-gl' },
61
+ { packageName: 'maplibre-gl', ignore: '^maplibre-gl' },
62
+ { packageName: 'react-test-renderer', ignore: '^react-test-renderer$' },
63
+ { packageName: '@storybook/blocks', ignore: '^@storybook/' },
64
+ ];
65
+
66
+ const importNoUnresolvedIgnore = [
67
+ ...alwaysUnresolvedIgnore,
68
+ ...optionalUnresolvedPackages.filter(({ packageName }) => !isInstalled(packageName)).map(({ ignore }) => ignore),
69
+ ];
70
+ `;
71
+
72
+ const TS_LANGUAGE_OPTIONS = `languageOptions: {
73
+ ecmaVersion: 2020,
74
+ sourceType: 'module',
75
+ globals: {
76
+ ...globals.browser,
77
+ ...globals.es2020,
78
+ ...globals.node,
79
+ React: 'readonly',
80
+ JSX: 'readonly',
81
+ },
82
+ parser: tsParser,
83
+ parserOptions: {
84
+ ecmaVersion: 'latest',
85
+ ecmaFeatures: { jsx: true },
86
+ sourceType: 'module',
87
+ },
88
+ },`;
89
+
90
+ export const usesVi = source => /\bvi\.(mock|fn|importActual|hoisted)\b/.test(source);
91
+
92
+ export const SEMANTIC_SUBMODULE_PATH = 'src/semantic-ui';
93
+ export const SEMANTIC_THEME_TS = 'front-semantic-theme-ts';
94
+ export const SEMANTIC_THEME_BRANCH = 'main';
95
+
96
+ export const isThemeTsRemoteUrl = url => /front-semantic-theme-ts/.test(url || '');
97
+
98
+ export const isLegacyThemeRemoteUrl = url => /front-semantic-theme(?!-ts\b)/.test(url || '');
99
+
100
+ export const patchGitmodules = source =>
101
+ source.replace(/(url\s*=\s*.*)front-semantic-theme(?!-ts)(\s|$)/g, '$1front-semantic-theme-ts$2');
102
+
103
+ export const parseSemanticSubmodule = source => {
104
+ const parts = source.split(/(?=\[submodule )/);
105
+
106
+ for (const part of parts) {
107
+ if (!part.startsWith('[submodule ')) continue;
108
+
109
+ const name = part.match(/\[submodule "([^"]+)"\]/)?.[1];
110
+ const path = part.match(/^\tpath\s*=\s*(\S+)/m)?.[1];
111
+ const url = part.match(/^\turl\s*=\s*(\S+)/m)?.[1];
112
+ const branch = part.match(/^\tbranch\s*=\s*(\S+)/m)?.[1];
113
+ const isSemantic =
114
+ path === SEMANTIC_SUBMODULE_PATH ||
115
+ name === SEMANTIC_SUBMODULE_PATH ||
116
+ /front-semantic-theme/.test(name ?? '') ||
117
+ /front-semantic-theme/.test(url ?? '');
118
+
119
+ if (isSemantic) return { name, path: path || SEMANTIC_SUBMODULE_PATH, url, branch };
120
+ }
121
+
122
+ return null;
123
+ };
124
+
125
+ export const semanticAddUrl = (source, fallback = '') => {
126
+ const parsed = parseSemanticSubmodule(source || '') || parseSemanticSubmodule(fallback || '');
127
+
128
+ if (parsed?.url) {
129
+ return parsed.url.replace(/front-semantic-theme(?!-ts\b)/, SEMANTIC_THEME_TS);
130
+ }
131
+
132
+ return `../../${SEMANTIC_THEME_TS}`;
133
+ };
134
+
135
+ export const ensureSubmoduleBranch = (
136
+ source,
137
+ { path = SEMANTIC_SUBMODULE_PATH, branch = SEMANTIC_THEME_BRANCH } = {},
138
+ ) => {
139
+ const parts = source.split(/(?=\[submodule )/);
140
+
141
+ return parts
142
+ .map(part => {
143
+ if (!part.startsWith('[submodule ')) return part;
144
+
145
+ const partPath = part.match(/^\tpath\s*=\s*(\S+)/m)?.[1];
146
+
147
+ if (partPath !== path) return part;
148
+ if (/^\tbranch\s*=/m.test(part)) {
149
+ return part.replace(/^\tbranch\s*=\s*.+$/m, `\tbranch = ${branch}`);
150
+ }
151
+
152
+ const withUrl = part.replace(/^(\turl\s*=\s*\S+)[ \t]*$/m, `$1\n\tbranch = ${branch}`);
153
+
154
+ if (withUrl !== part) return withUrl;
155
+
156
+ return `${part.replace(/\s*$/, '')}\n\tbranch = ${branch}\n`;
157
+ })
158
+ .join('');
159
+ };
160
+
161
+ export const patchTsconfig = source => {
162
+ let next = source.replace(/"target":\s*"ES2020"/, '"target": "ES2022"');
163
+
164
+ next = next.replace(/"lib":\s*\["ES2020"/, '"lib": ["ES2022"');
165
+ next = next.replace(/"moduleResolution":\s*"node"/, '"moduleResolution": "bundler"');
166
+
167
+ return next;
168
+ };
169
+
170
+ export const patchPackageJson = source => {
171
+ const pkg = JSON.parse(source);
172
+
173
+ pkg.devDependencies = pkg.devDependencies || {};
174
+ if (!pkg.devDependencies[ESLINT_RESOLVER_PKG]) {
175
+ pkg.devDependencies[ESLINT_RESOLVER_PKG] = ESLINT_RESOLVER_VERSION;
176
+ }
177
+
178
+ return `${JSON.stringify(pkg, null, '\t')}\n`;
179
+ };
180
+
181
+ const newlineOf = source => (source.includes('\r\n') ? '\r\n' : '\n');
182
+
183
+ const withNewlines = (text, nl) => (nl === '\r\n' ? text.replaceAll('\n', '\r\n') : text);
184
+
185
+ const lineIndent = (source, index) => {
186
+ const lineStart = source.lastIndexOf('\n', index - 1) + 1;
187
+
188
+ return source.slice(lineStart, index).match(/^[ \t]*/)?.[0] ?? '';
189
+ };
190
+
191
+ const skipComment = (source, index) => {
192
+ if (source[index + 1] === '/') {
193
+ const nl = source.indexOf('\n', index);
194
+
195
+ return nl < 0 ? source.length : nl;
196
+ }
197
+
198
+ const close = source.indexOf('*/', index + 2);
199
+
200
+ return close < 0 ? source.length : close + 2;
201
+ };
202
+
203
+ const insideCommentOrString = source => {
204
+ const hidden = new Uint8Array(source.length);
205
+
206
+ for (let i = 0; i < source.length; i += 1) {
207
+ const char = source[i];
208
+
209
+ if (char === "'" || char === '"' || char === '`') {
210
+ const end = skipQuoted(source, i);
211
+ // The opening quote of a code token stays visible, so a real key
212
+ // ('@typescript-eslint/no-explicit-any': ...) is not treated as string text.
213
+ if (end > i + 1) hidden.fill(1, i + 1, end);
214
+ i = end - 1;
215
+ continue;
216
+ }
217
+
218
+ if (char === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
219
+ const end = skipComment(source, i);
220
+ hidden.fill(1, i, end);
221
+ i = end - 1;
222
+ }
223
+ }
224
+
225
+ return index => hidden[index] === 1;
226
+ };
227
+
228
+ const braceClose = (source, open) => {
229
+ let depth = 0;
230
+
231
+ for (let i = open; i < source.length; i += 1) {
232
+ const char = source[i];
233
+
234
+ if (char === "'" || char === '"' || char === '`') {
235
+ i = skipQuoted(source, i) - 1;
236
+ continue;
237
+ }
238
+
239
+ if (char === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
240
+ const end = skipComment(source, i);
241
+ if (end >= source.length) return -1;
242
+ i = end - 1;
243
+ continue;
244
+ }
245
+
246
+ if (char === '{') depth += 1;
247
+ else if (char === '}') {
248
+ depth -= 1;
249
+ if (depth === 0) return i;
250
+ }
251
+ }
252
+
253
+ return -1;
254
+ };
255
+
256
+ const braceDepthAt = (source, index) => {
257
+ let depth = 0;
258
+
259
+ for (let i = 0; i < index; i += 1) {
260
+ const char = source[i];
261
+
262
+ if (char === "'" || char === '"' || char === '`') {
263
+ i = skipQuoted(source, i) - 1;
264
+ continue;
265
+ }
266
+
267
+ if (char === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
268
+ const end = skipComment(source, i);
269
+ if (end >= source.length) break;
270
+ i = end - 1;
271
+ continue;
272
+ }
273
+
274
+ if (char === '{') depth += 1;
275
+ else if (char === '}') depth -= 1;
276
+ }
277
+
278
+ return depth;
279
+ };
280
+
281
+ const findProperty = (
282
+ source,
283
+ key,
284
+ { withBrace = false, from = 0, to = source.length, hidden = insideCommentOrString(source) } = {},
285
+ ) => {
286
+ const re = new RegExp(`\\b${key}\\s*:${withBrace ? '\\s*\\{' : ''}`, 'g');
287
+ re.lastIndex = from;
288
+ let match = re.exec(source);
289
+
290
+ while (match && match.index < to) {
291
+ if (!hidden(match.index)) return match;
292
+ match = re.exec(source);
293
+ }
294
+
295
+ return null;
296
+ };
297
+
298
+ const findShallowestBlock = (source, key) => {
299
+ const hidden = insideCommentOrString(source);
300
+ const re = new RegExp(`\\b${key}\\s*:\\s*\\{`, 'g');
301
+ let match = re.exec(source);
302
+ let best = null;
303
+
304
+ while (match) {
305
+ if (!hidden(match.index)) {
306
+ const open = match.index + match[0].lastIndexOf('{');
307
+ const close = braceClose(source, open);
308
+
309
+ if (close > open) {
310
+ const depth = braceDepthAt(source, match.index);
311
+ if (!best || depth < best.depth) best = { open, close, depth };
312
+ }
313
+ }
314
+
315
+ match = re.exec(source);
316
+ }
317
+
318
+ return best;
319
+ };
320
+
321
+ const findBlockInside = (source, parent, key) => {
322
+ const match = findProperty(source, key, { withBrace: true, from: parent.open + 1, to: parent.close });
323
+
324
+ if (!match) return null;
325
+
326
+ const open = match.index + match[0].lastIndexOf('{');
327
+ const close = braceClose(source, open);
328
+
329
+ if (close < 0 || close > parent.close) return null;
330
+
331
+ return { open, close };
332
+ };
333
+
334
+ const spliceAfterOpen = (source, open, lines) => {
335
+ const close = braceClose(source, open);
336
+ if (close < 0) return source;
337
+
338
+ const nl = newlineOf(source);
339
+ const inner = source.slice(open + 1, close);
340
+ const keyIndent = lineIndent(source, open);
341
+ const childIndent = inner.match(/\n([ \t]+)\S/)?.[1] ?? `${keyIndent}\t`;
342
+ const rendered = lines.map(line => `${childIndent}${line}`).join(nl);
343
+
344
+ if (!inner.includes('\n')) {
345
+ if (lines.length === 1) {
346
+ const property = inner.trim() ? lines[0] : lines[0].replace(/,$/, '');
347
+ const rest = inner.startsWith(' ') || !inner.trim() ? inner : ` ${inner}`;
348
+
349
+ return `${source.slice(0, open + 1)} ${property}${rest}${source.slice(close)}`;
350
+ }
351
+
352
+ const tail = inner.trim() ? `${nl}${childIndent}${inner.trim()}` : '';
353
+
354
+ return `${source.slice(0, open + 1)}${nl}${rendered}${tail}${nl}${keyIndent}${source.slice(close)}`;
355
+ }
356
+
357
+ return `${source.slice(0, open + 1)}${nl}${rendered}${source.slice(open + 1)}`;
358
+ };
359
+
360
+ const loaderMapsJsToJsx = (source, loader) => {
361
+ let text = '';
362
+
363
+ for (let i = loader.open + 1; i < loader.close; i += 1) {
364
+ const char = source[i];
365
+
366
+ if (char === "'" || char === '"' || char === '`') {
367
+ const end = Math.min(skipQuoted(source, i), loader.close);
368
+ text += source.slice(i, end);
369
+ i = end - 1;
370
+ continue;
371
+ }
372
+
373
+ if (char === '/' && (source[i + 1] === '/' || source[i + 1] === '*')) {
374
+ i = Math.min(skipComment(source, i), loader.close) - 1;
375
+ continue;
376
+ }
377
+
378
+ text += char;
379
+ }
380
+
381
+ return /['"]\.js['"]\s*:\s*['"]jsx['"]/.test(text);
382
+ };
383
+
384
+ const insertFreshOptimizeDeps = source => {
385
+ const replacement = withNewlines(
386
+ "exclude: ['node_modules', 'dist'],\n\t},\n\toptimizeDeps: {\n\t\tesbuildOptions: {\n\t\t\tloader: {\n\t\t\t\t'.js': 'jsx',\n\t\t\t},\n\t\t},\n\t},\n\tserver:",
387
+ newlineOf(source),
388
+ );
389
+
390
+ return source.replace(/exclude:\s*\['node_modules', 'dist'\],\r?\n\t\},\r?\n\tserver:/, replacement);
391
+ };
392
+
393
+ const ensureOptimizeDepsJsxLoader = source => {
394
+ const block = findShallowestBlock(source, 'optimizeDeps');
395
+
396
+ if (!block) {
397
+ if (findProperty(source, 'optimizeDeps')) return source;
398
+
399
+ return insertFreshOptimizeDeps(source);
400
+ }
401
+
402
+ const esbuild = findBlockInside(source, block, 'esbuildOptions');
403
+
404
+ if (!esbuild) {
405
+ return spliceAfterOpen(source, block.open, [
406
+ 'esbuildOptions: {',
407
+ '\tloader: {',
408
+ "\t\t'.js': 'jsx',",
409
+ '\t},',
410
+ '},',
411
+ ]);
412
+ }
413
+
414
+ const loader = findBlockInside(source, esbuild, 'loader');
415
+
416
+ if (!loader) {
417
+ return spliceAfterOpen(source, esbuild.open, ['loader: {', "\t'.js': 'jsx',", '},']);
418
+ }
419
+
420
+ if (loaderMapsJsToJsx(source, loader)) return source;
421
+
422
+ return spliceAfterOpen(source, loader.open, ["'.js': 'jsx',"]);
423
+ };
424
+
425
+ export const patchViteConfig = (source, { hasJsxTransformer } = { hasJsxTransformer: true }) => {
426
+ let next = source;
427
+ const nl = newlineOf(next);
428
+
429
+ if (hasJsxTransformer && !next.includes('jsxTransformer')) {
430
+ next = next.replace(
431
+ /import eslint from 'vite-plugin-eslint';/,
432
+ withNewlines(
433
+ "import eslint from 'vite-plugin-eslint';\nimport transformJsxInJs from './src/modules/plugins/jsxTransformer';",
434
+ nl,
435
+ ),
436
+ );
437
+ }
438
+
439
+ if (hasJsxTransformer && !next.includes('transformJsxInJs(')) {
440
+ next = next.replace(/plugins:\s*\[\s*\r?\n(\s*)eslint\(/, (_match, indent) =>
441
+ withNewlines(`plugins: [\n${indent}transformJsxInJs(mode === 'production'),\n${indent}eslint(`, nl),
442
+ );
443
+ }
444
+
445
+ next = ensureOptimizeDepsJsxLoader(next);
446
+
447
+ if (!next.includes("find: 'fonts'")) {
448
+ next = next.replace(
449
+ /alias:\s*\[\s*\r?\n\s*\{\s*\r?\n\s*find: '\.\.\/\.\.\/theme\.config'/,
450
+ withNewlines(
451
+ "alias: [\n\t\t\t{\n\t\t\t\tfind: 'fonts',\n\t\t\t\treplacement: resolve(__dirname, 'src/semantic-ui/site/globals/fonts'),\n\t\t\t},\n\t\t\t{\n\t\t\t\tfind: '../../theme.config'",
452
+ nl,
453
+ ),
454
+ );
455
+ }
456
+
457
+ return next;
458
+ };
459
+
460
+ const insert = replacement => () => replacement;
461
+
462
+ const replaceOutsideCommentOrString = (source, pattern, replacer) => {
463
+ const literal = typeof pattern === 'string';
464
+ const sourcePattern = literal ? pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : pattern.source;
465
+ const flags = literal || !pattern.flags.includes('g') ? 'g' : pattern.flags;
466
+ const re = new RegExp(sourcePattern, flags);
467
+ const hidden = insideCommentOrString(source);
468
+ const matches = [];
469
+ let match = re.exec(source);
470
+
471
+ while (match) {
472
+ if (!hidden(match.index)) {
473
+ matches.push(match);
474
+ if (literal || !pattern.flags.includes('g')) break;
475
+ } else {
476
+ let resume = match.index;
477
+
478
+ while (resume < source.length && hidden(resume)) resume += 1;
479
+ re.lastIndex = resume > match.index ? resume : match.index + 1;
480
+ }
481
+
482
+ match = re.exec(source);
483
+ }
484
+
485
+ if (!matches.length) return source;
486
+
487
+ const apply = item => {
488
+ const replacement = typeof replacer === 'function' ? replacer(...item, item.index, source) : replacer;
489
+
490
+ return `${source.slice(0, item.index)}${replacement}${source.slice(item.index + item[0].length)}`;
491
+ };
492
+
493
+ if (literal || !pattern.flags.includes('g')) return apply(matches[0]);
494
+
495
+ return matches.reduceRight((next, item) => {
496
+ const replacement = typeof replacer === 'function' ? replacer(...item, item.index, source) : replacer;
497
+
498
+ return `${next.slice(0, item.index)}${replacement}${next.slice(item.index + item[0].length)}`;
499
+ }, source);
500
+ };
501
+
502
+ const appearsInCode = (source, pattern) => {
503
+ const literal = typeof pattern === 'string';
504
+ const sourcePattern = literal ? pattern.replace(/[.*+?^${}()|[\]\\]/g, '\\$&') : pattern.source;
505
+ const flags = literal || !pattern.flags.includes('g') ? 'g' : pattern.flags;
506
+ const re = new RegExp(sourcePattern, flags);
507
+ const hidden = insideCommentOrString(source);
508
+ let match = re.exec(source);
509
+
510
+ while (match) {
511
+ if (!hidden(match.index)) return true;
512
+
513
+ let resume = match.index;
514
+
515
+ while (resume < source.length && hidden(resume)) resume += 1;
516
+ re.lastIndex = resume > match.index ? resume : match.index + 1;
517
+ match = re.exec(source);
518
+ }
519
+
520
+ return false;
521
+ };
522
+
523
+ const insertEslintConstants = source => {
524
+ if (!source || appearsInCode(source, 'const importNoUnresolvedIgnore')) return source;
525
+
526
+ const nl = newlineOf(source);
527
+ const block = withNewlines(ESLINT_CONSTANTS, nl);
528
+ const afterTsPlugin = replaceOutsideCommentOrString(
529
+ source,
530
+ /(import tsPlugin from '@typescript-eslint\/eslint-plugin';)(\r?\n)/,
531
+ (_match, importLine, lineEnd) => `${importLine}${lineEnd}${block}`,
532
+ );
533
+
534
+ if (afterTsPlugin !== source) return afterTsPlugin;
535
+
536
+ const beforeExport = replaceOutsideCommentOrString(
537
+ source,
538
+ /(\r?\n)(export default \[)/,
539
+ (_match, lineEnd, exp) => `${lineEnd}${block}${lineEnd}${exp}`,
540
+ );
541
+
542
+ if (beforeExport !== source) return beforeExport;
543
+
544
+ if (!appearsInCode(source, /export default|tsPlugin|import\/no-unresolved/)) return source;
545
+
546
+ throw new Error(
547
+ 'Не смог вставить const importNoUnresolvedIgnore в eslint.config.js. Нужен import tsPlugin или `export default [`.',
548
+ );
549
+ };
550
+
551
+ export const patchEslintConfig = source => {
552
+ let next = source;
553
+
554
+ if (!next.includes("from 'node:fs'")) {
555
+ next = replaceOutsideCommentOrString(next, "import js from '@eslint/js';", insert(`${ESLINT_HELPER}import js from '@eslint/js';`));
556
+ }
557
+
558
+ next = insertEslintConstants(next);
559
+
560
+ if (!next.includes("'artifacts/**'")) {
561
+ next = replaceOutsideCommentOrString(
562
+ next,
563
+ "ignores: ['dist/**', 'build/**', 'coverage/**', 'node_modules/**', '.git', '.vscode', '.idea']",
564
+ insert(`ignores: [
565
+ 'dist/**',
566
+ 'build/**',
567
+ 'coverage/**',
568
+ 'node_modules/**',
569
+ 'artifacts/**',
570
+ 'src/api/openapi/**/generated/**',
571
+ '.git',
572
+ '.vscode',
573
+ '.idea',
574
+ ]`),
575
+ );
576
+ }
577
+
578
+ next = replaceOutsideCommentOrString(
579
+ next,
580
+ /ignore:\s*\[[^\]]*semantic-ui-css[^\]]*\]/g,
581
+ insert('ignore: importNoUnresolvedIgnore'),
582
+ );
583
+
584
+ next = replaceOutsideCommentOrString(
585
+ next,
586
+ /languageOptions:\s*\{\s*parser:\s*tsParser,[\s\S]*?parserOptions:\s*\{\s*project:\s*'[^']+',\s*\},\s*\},/,
587
+ insert(TS_LANGUAGE_OPTIONS),
588
+ );
589
+
590
+ next = replaceOutsideCommentOrString(
591
+ next,
592
+ /'jsx-a11y\/click-events-have-key-events': 'off',\r?\n(\t\t\t'import\/prefer-default-export': 'off',)/,
593
+ (match, importRule) => {
594
+ const nl = match.includes('\r\n') ? '\r\n' : '\n';
595
+ return `'jsx-a11y/click-events-have-key-events': 'off',${nl}\t\t\t'jsx-a11y/no-autofocus': 'off',${nl}${importRule}`;
596
+ },
597
+ );
598
+
599
+ if (!next.includes("'@typescript-eslint/no-redeclare'")) {
600
+ next = replaceOutsideCommentOrString(
601
+ next,
602
+ "'@typescript-eslint/no-explicit-any': 'warn',",
603
+ insert(`'@typescript-eslint/no-explicit-any': 'warn',
604
+ 'no-redeclare': 'off',
605
+ '@typescript-eslint/no-redeclare': ['error'],
606
+ '@typescript-eslint/consistent-type-imports': [
607
+ 'error',
608
+ {
609
+ prefer: 'type-imports',
610
+ disallowTypeAnnotations: false,
611
+ fixStyle: 'inline-type-imports',
612
+ },
613
+ ],`),
614
+ );
615
+ }
616
+
617
+ if (next.includes("files: ['**/*.{ts,tsx}']") && !next.includes('typescript: { alwaysTryTypes: true }')) {
618
+ next = replaceOutsideCommentOrString(
619
+ next,
620
+ /'import\/resolver': \{\s*node: \{\s*extensions: \['\.js', '\.jsx', '\.ts', '\.tsx', '\.mjs'\],\s*moduleDirectory: \['node_modules'\],\s*typescript: \{\},\s*\},\s*typescript: \{\s*alwaysTryTypes: true,\s*\},\s*\}/,
621
+ insert(`'import/resolver': {
622
+ typescript: { alwaysTryTypes: true },
623
+ node: {
624
+ extensions: ['.js', '.jsx', '.ts', '.tsx'],
625
+ },
626
+ }`),
627
+ );
628
+ }
629
+
630
+ if (!next.includes("'prettier/prettier': 'off'")) {
631
+ next = replaceOutsideCommentOrString(
632
+ next,
633
+ /files: \['src\/semantic-ui\/\*\*\/\*\.\{js,jsx,ts,tsx\}'\],\s*rules: \{\s*'react-hooks\/rules-of-hooks': 'off',/,
634
+ insert(`files: ['src/semantic-ui/**/*.{js,jsx,ts,tsx}'],
635
+ rules: {
636
+ 'react-hooks/rules-of-hooks': 'off',
637
+ 'prettier/prettier': 'off',`),
638
+ );
639
+ }
640
+
641
+ return next;
642
+ };
643
+
644
+ const skipQuoted = (source, start) => {
645
+ const quote = source[start];
646
+ let i = start + 1;
647
+
648
+ while (i < source.length) {
649
+ if (source[i] === '\\') {
650
+ i += 2;
651
+ continue;
652
+ }
653
+
654
+ if (source[i] === quote) return i + 1;
655
+ i += 1;
656
+ }
657
+
658
+ return source.length;
659
+ };
660
+
661
+ const callEndIndex = (source, openParen) => {
662
+ let depth = 0;
663
+ let i = openParen;
664
+
665
+ while (i < source.length) {
666
+ const char = source[i];
667
+
668
+ if (char === "'" || char === '"' || char === '`') {
669
+ i = skipQuoted(source, i);
670
+ continue;
671
+ }
672
+
673
+ if (char === '(') depth += 1;
674
+ else if (char === ')') {
675
+ depth -= 1;
676
+ if (depth === 0) {
677
+ const trailing = source.slice(i + 1).match(/^\s*;/);
678
+ return i + 1 + (trailing ? trailing[0].length : 0);
679
+ }
680
+ }
681
+
682
+ i += 1;
683
+ }
684
+
685
+ return -1;
686
+ };
687
+
688
+ const eachMockCall = (source, visit) => {
689
+ const matcher = /(?:vi|jest)\.mock\(/g;
690
+ let match = matcher.exec(source);
691
+
692
+ while (match) {
693
+ const start = match.index;
694
+ const end = callEndIndex(source, start + match[0].length - 1);
695
+
696
+ if (end < 0) break;
697
+
698
+ visit({ start, end, call: source.slice(start, end) });
699
+ matcher.lastIndex = end;
700
+ match = matcher.exec(source);
701
+ }
702
+ };
703
+
704
+ const shouldReplaceAutoSizerMock = call => {
705
+ const isPath = /['"]react-virtualized\/dist\/commonjs\/AutoSizer['"]/.test(call);
706
+ const isPackage = /['"]react-virtualized['"]/.test(call);
707
+ const destructuresChildren = /AutoSizer:\s*(?:async\s*)?\(\s*\{\s*children\s*\}/.test(call);
708
+
709
+ return isPath || (isPackage && destructuresChildren);
710
+ };
711
+
712
+ export const patchAutoSizerMocks = source => {
713
+ const mock = usesVi(source) ? AUTO_SIZER_MOCK_VI : AUTO_SIZER_MOCK_JEST;
714
+ const replacements = [];
715
+
716
+ eachMockCall(source, ({ start, end, call }) => {
717
+ if (shouldReplaceAutoSizerMock(call)) replacements.push({ start, end });
718
+ });
719
+
720
+ if (replacements.length) {
721
+ let next = source;
722
+
723
+ for (let i = replacements.length - 1; i >= 0; i -= 1) {
724
+ const { start, end } = replacements[i];
725
+ next = `${next.slice(0, start)}${mock}${next.slice(end)}`;
726
+ }
727
+
728
+ return next;
729
+ }
730
+
731
+ if (/AutoSizer:\s*\(\s*\{\s*children\s*\}/.test(source) && /react-virtualized/.test(source)) {
732
+ return source.replace(
733
+ /AutoSizer:\s*\(\s*\{\s*children\s*\}\s*\)[^\n]*/g,
734
+ 'AutoSizer: autoSizerProps => <div>{autoSizerProps.children({ height: 1000, width: 1000 })}</div>,',
735
+ );
736
+ }
737
+
738
+ return source;
739
+ };
740
+
741
+ export const themeGitUnsafeReasons = ({ status, stashList, unpublished }) => {
742
+ const reasons = [];
743
+
744
+ if ((status || '').trim()) reasons.push('незакоммиченные изменения в src/semantic-ui');
745
+ if ((stashList || '').trim()) reasons.push('git stash в теме');
746
+ if ((unpublished || '').trim()) reasons.push('локальные коммиты темы, которых нет на remote');
747
+
748
+ return reasons;
749
+ };
750
+
751
+ export const testsTooltip = source =>
752
+ /mockPopupComponent|popupText|getByText\(\s*['"`]Линейка|content:\s*['"`]Линейка/.test(source);
753
+
754
+ export const alreadyMocksPopup = source =>
755
+ /mock\(\s*['"]semantic-ui-react['"][\s\S]{0,800}Popup\s*:/.test(source);
756
+
757
+ export const patchPopupMock = (source, { componentUsesPopup } = {}) => {
758
+ if (!componentUsesPopup) return source;
759
+ if (!/userEvent\.click/.test(source)) return source;
760
+ if (alreadyMocksPopup(source)) return source;
761
+ if (testsTooltip(source)) return source;
762
+
763
+ const mock = usesVi(source) || !/\bjest\.(mock|fn)\b/.test(source) ? POPUP_MOCK_VI : POPUP_MOCK_JEST;
764
+ const importBlock = source.match(/^(?:\/\*[\s\S]*?\*\/\s*|\/\/.*\n|\s|import[\s\S]*?;\n)+/);
765
+
766
+ if (!importBlock) {
767
+ return `${mock}\n\n${source}`;
768
+ }
769
+
770
+ const insertAt = importBlock[0].length;
771
+
772
+ return `${source.slice(0, insertAt)}\n${mock}\n${source.slice(insertAt)}`;
773
+ };