@dxtmisha/scripts 0.10.6 → 0.10.8
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/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,18 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [0.10.8] - 2026-07-28
|
|
6
|
+
|
|
7
|
+
### Added / Updated
|
|
8
|
+
- **AI Prompt Templates**: Overhauled global AI prompt templates (`aiCodeGlobalPrompt.en.md`, `aiCodeGlobalPrompt.ru.md`) with streamlined rules, mandatory deep study workflows (`view_file`), prohibition of superficial code scans, and full-file self-audit requirements.
|
|
9
|
+
- **DesignReplace**: Escaped dollar sign (`$`) characters in replacement value strings in `DesignReplace` to prevent regex capture group interpolation issues during template processing.
|
|
10
|
+
- **DesignTypes**: Added JavaScript File Validator and improved TypeScript schema generation and translation logic.
|
|
11
|
+
|
|
12
|
+
## [0.10.7] - 2026-07-06
|
|
13
|
+
|
|
14
|
+
### Changed
|
|
15
|
+
- **DesignTypes**: Updated the AI prompt in `DesignTypes.toAiEdit` to translate Russian JSDocs/comments to English instead of just removing them, if an English version is missing.
|
|
16
|
+
|
|
5
17
|
## [0.10.6] - 2026-07-05
|
|
6
18
|
|
|
7
19
|
### Changed
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dxtmisha/scripts",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.8",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "Development scripts and CLI tools for DXT UI projects - automated component generation, library building and project management tools",
|
|
7
7
|
"keywords": [
|
|
@@ -45,9 +45,12 @@ export class DesignTypes {
|
|
|
45
45
|
console.log('DesignTypes: making AI types...')
|
|
46
46
|
|
|
47
47
|
const files = this.getListByFilter()
|
|
48
|
+
const jsFiles = this.getListByFilterJs()
|
|
49
|
+
|
|
48
50
|
const fullContent = this.toOneFile(files)
|
|
51
|
+
const fullJsContent = this.toOneFile(jsFiles)
|
|
49
52
|
|
|
50
|
-
const aiContent = await this.toAiEdit(fullContent)
|
|
53
|
+
const aiContent = await this.toAiEdit(fullContent, fullJsContent)
|
|
51
54
|
this.save(aiContent)
|
|
52
55
|
|
|
53
56
|
const aiDescription = await this.toAiDescription(fullContent)
|
|
@@ -75,6 +78,16 @@ export class DesignTypes {
|
|
|
75
78
|
)
|
|
76
79
|
}
|
|
77
80
|
|
|
81
|
+
/**
|
|
82
|
+
* Checks if the file is a valid JavaScript or TypeScript file.
|
|
83
|
+
*
|
|
84
|
+
* Проверяет, является ли файл валидным JavaScript или TypeScript файлом.
|
|
85
|
+
* @param file file name / имя файла
|
|
86
|
+
*/
|
|
87
|
+
protected isFileJs(file: string): boolean {
|
|
88
|
+
return file.endsWith('.js')
|
|
89
|
+
}
|
|
90
|
+
|
|
78
91
|
/**
|
|
79
92
|
* Checks if the content contains type definitions.
|
|
80
93
|
*
|
|
@@ -108,15 +121,16 @@ export class DesignTypes {
|
|
|
108
121
|
}
|
|
109
122
|
|
|
110
123
|
/**
|
|
111
|
-
* Gets a list of files filtered by
|
|
124
|
+
* Gets a list of files filtered by a provided checker function.
|
|
112
125
|
*
|
|
113
|
-
* Получает список файлов, отфильтрованный
|
|
126
|
+
* Получает список файлов, отфильтрованный переданной функцией проверки.
|
|
127
|
+
* @param checkFile function to check if the file matches criteria / функция проверки соответствия файла критериям
|
|
114
128
|
*/
|
|
115
|
-
protected
|
|
129
|
+
protected getListBy(checkFile: (file: string) => boolean): DesignTypesList {
|
|
116
130
|
return forEach(
|
|
117
131
|
this.getList(),
|
|
118
132
|
(file) => {
|
|
119
|
-
if (
|
|
133
|
+
if (checkFile(file)) {
|
|
120
134
|
const content = this.readFile(file)
|
|
121
135
|
|
|
122
136
|
if (this.isContent(content)) {
|
|
@@ -132,6 +146,24 @@ export class DesignTypes {
|
|
|
132
146
|
) as DesignTypesList
|
|
133
147
|
}
|
|
134
148
|
|
|
149
|
+
/**
|
|
150
|
+
* Gets a list of files filtered by criteria.
|
|
151
|
+
*
|
|
152
|
+
* Получает список файлов, отфильтрованный по критериям.
|
|
153
|
+
*/
|
|
154
|
+
protected getListByFilter(): DesignTypesList {
|
|
155
|
+
return this.getListBy(file => this.isFile(file))
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* Gets a list of JS files filtered by criteria.
|
|
160
|
+
*
|
|
161
|
+
* Получает список JS файлов, отфильтрованный по критериям.
|
|
162
|
+
*/
|
|
163
|
+
protected getListByFilterJs(): DesignTypesList {
|
|
164
|
+
return this.getListBy(file => this.isFileJs(file))
|
|
165
|
+
}
|
|
166
|
+
|
|
135
167
|
/**
|
|
136
168
|
* Reads the content of a file.
|
|
137
169
|
*
|
|
@@ -201,14 +233,23 @@ export class DesignTypes {
|
|
|
201
233
|
* Отправляет контент и промпт ИИ для обработки.
|
|
202
234
|
* @param content content for processing / контент для обработки
|
|
203
235
|
* @param prompt instructions for the AI / инструкции для ИИ
|
|
236
|
+
* @param code code to optimize / код для оптимизации
|
|
204
237
|
*/
|
|
205
|
-
protected async toAi(
|
|
238
|
+
protected async toAi(
|
|
239
|
+
content: string,
|
|
240
|
+
prompt: string,
|
|
241
|
+
code?: string
|
|
242
|
+
): Promise<string | undefined> {
|
|
206
243
|
const ai = useAi()
|
|
207
244
|
|
|
208
245
|
if (ai) {
|
|
209
246
|
ai.addPrompt(prompt)
|
|
210
247
|
ai.addPrompt(`File Content: ${content}`)
|
|
211
248
|
|
|
249
|
+
if (code) {
|
|
250
|
+
ai.addPrompt(`File JS Code: ${code}`)
|
|
251
|
+
}
|
|
252
|
+
|
|
212
253
|
const generate = await ai.generate('go!')
|
|
213
254
|
|
|
214
255
|
if (generate) {
|
|
@@ -224,14 +265,18 @@ export class DesignTypes {
|
|
|
224
265
|
*
|
|
225
266
|
* Отправляет контент ИИ для оптимизации.
|
|
226
267
|
* @param content content to optimize / контент для оптимизации
|
|
268
|
+
* @param code code to optimize / код для оптимизации
|
|
227
269
|
*/
|
|
228
|
-
protected async toAiEdit(content: string): Promise<string> {
|
|
270
|
+
protected async toAiEdit(content: string, code: string): Promise<string> {
|
|
229
271
|
const generate = await this.toAi(
|
|
230
272
|
content,
|
|
231
|
-
'
|
|
232
|
-
+ '
|
|
233
|
-
+ '
|
|
234
|
-
+ 'Remove
|
|
273
|
+
'TRANSLATE all non-English comments (including JSDocs and inline comments) to English. '
|
|
274
|
+
+ 'Optimize the provided type definitions, improve and supplement them if necessary. '
|
|
275
|
+
+ 'Carefully study the provided JS code to understand its logic and what the code does. '
|
|
276
|
+
+ 'Remove redundant or self-explanatory JSDoc comments for any entity (types, properties, variables, functions, methods, etc.) if their meaning is obvious from their name or signature and does not require documentation. '
|
|
277
|
+
+ 'Keep or add clear English JSDoc comments for entities that are complex, non-obvious, or require explanation. '
|
|
278
|
+
+ 'CRITICAL: Always keep all JSDoc "@example", "@remarks", "@note", and any other notes or warnings. Their contents must NOT be modified, altered, or rewritten—keep them exactly as written, only translating them to English if they are not in English. '
|
|
279
|
+
+ 'CRITICAL: Remove all imports. Remove all local internal re-exports (e.g., `export * from "./..."`), but strictly KEEP any exports from external libraries or packages. '
|
|
235
280
|
+ 'Remove all non-public content: delete all private and protected class methods and properties, and any non-exported elements. The final output must contain only the members and entities that are accessible from outside. '
|
|
236
281
|
+ 'Remove any code segments or data that do not provide useful information for an AI assistant. '
|
|
237
282
|
+ 'You may remove abstract classes or other structures that provide no practical value for code generation, but do so with extreme caution. Maintain a strict balance: if there is even a 5% chance the item might be relevant for understanding the API or generating code, keep it. Think carefully before every deletion. '
|
|
@@ -239,9 +284,12 @@ export class DesignTypes {
|
|
|
239
284
|
+ 'Your goal is to create a compact, context-rich file that enables any AI coding assistant to generate high-quality code for a developer. '
|
|
240
285
|
+ 'Ensure that no public API surface, essential data types, or required logic is lost. '
|
|
241
286
|
+ 'Do not delete any "type" definitions; they are strictly required. '
|
|
242
|
-
+ '
|
|
287
|
+
+ 'Remove all regular comments and inline comments (lines starting with "//" or "/* ... */"). '
|
|
288
|
+
+ 'Do not include empty lines; keep the output compact and tight without blank lines. '
|
|
289
|
+
+ 'CRITICAL: Do NOT return the provided JS code in your response. '
|
|
243
290
|
+ 'All instructions are mandatory and must be executed perfectly. '
|
|
244
|
-
+ 'Return ONLY the resulting code. No markdown code blocks, no tags, no explanations, and no additional comments from the AI. NOTHING but the pure code.'
|
|
291
|
+
+ 'Return ONLY the resulting optimized type definitions code. No markdown code blocks, no tags, no explanations, and no additional comments from the AI. NOTHING but the pure code.',
|
|
292
|
+
code
|
|
245
293
|
)
|
|
246
294
|
|
|
247
295
|
return generate ?? content
|
|
@@ -1,78 +1,21 @@
|
|
|
1
1
|
### Global Development Principles (AI Code Promise)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
0. **Mandatory Deep Study**:
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
- Generate code that can be copied and run without a single manual edit.
|
|
23
|
-
- All imports must be absolute or correct relative paths.
|
|
24
|
-
- No `// ... rest of the code`, no `// imports here`. Only the complete, working file.
|
|
25
|
-
|
|
26
|
-
2. **Zero Tolerance for Hallucinations**:
|
|
27
|
-
- Use only the libraries and versions specified in the project's `package.json`.
|
|
28
|
-
- Do not invent API methods that do not exist in the current versions of dependencies.
|
|
29
|
-
- If information is insufficient, it is better to ask or point out the limitation than to hallucinate.
|
|
30
|
-
|
|
31
|
-
3. **Clean Code Standards**:
|
|
32
|
-
- **DRY & KISS**: Avoid duplication, write as simply and clearly as possible.
|
|
33
|
-
- **SOLID**: Every module, class, or function must have one clear responsibility.
|
|
34
|
-
- **Declarative Approach**: Prefer a declarative programming style (array functional methods, composition).
|
|
35
|
-
- **No Abbreviations**: Do not use shortened or abbreviated names for variables, properties, arguments, methods, classes, etc. (e.g., do not use `el`, `rect1`/`r1`, `dx`/`dy`, `val`, `temp`). All identifiers must be descriptive, complete, and self-explanatory.
|
|
36
|
-
- **Optimization and Clarity**: Write code that is highly optimized, performant, and clean, ensuring it is easy to read and understand.
|
|
37
|
-
- **Single Responsibility (KISS/SOLID)**: Avoid creating large "mega-functions" or monolithic blocks. Each function must be concise and perform exactly one focused task (1 function = 1 functionality).
|
|
38
|
-
|
|
39
|
-
4. **Uncompromising TypeScript**:
|
|
40
|
-
- No `any`. Use `unknown` if the type is truly unknown, or create generic types.
|
|
41
|
-
- Never use `@ts-ignore`. If a type check suppression is absolutely necessary due to external limitations, use `@ts-expect-error` with a descriptive comment explaining why.
|
|
42
|
-
- Always define interfaces for input and output data.
|
|
43
|
-
- Use `as const`, `readonly`, and enums/union types to increase reliability.
|
|
44
|
-
|
|
45
|
-
5. **Professional Documentation (TSDoc)**:
|
|
46
|
-
- Accompany all exported entities with TSDoc comments in the [wikiLanguage] language.
|
|
47
|
-
- Describe the purpose, parameters, return values, and potential exceptions.
|
|
48
|
-
- Usage examples in comments are encouraged for complex functions.
|
|
49
|
-
|
|
50
|
-
6. **Architectural Consistency**:
|
|
51
|
-
- Respect the project structure. If it is standard in the project to move logic into `composables` or `utils`, follow that pattern.
|
|
52
|
-
- Reuse existing infrastructure: Always check if the required functionality (e.g., API requests, state management, utilities) already exists in the project's core packages (like `@dxtmisha/functional` or `@dxtmisha/functional-basic`) before implementing it from scratch.
|
|
53
|
-
- Do not modify global styles or styles of base UI components unless explicitly requested.
|
|
54
|
-
|
|
55
|
-
7. **Security and Performance**:
|
|
56
|
-
- Write error-proof code (guard clauses, optional chaining `?.`, nullish coalescing `??`).
|
|
57
|
-
- Use explicit `try-catch` blocks for asynchronous operations. Never swallow errors silently; handle them appropriately or throw meaningful error messages.
|
|
58
|
-
- Avoid redundant calculations in loops and heavy operations in reactive dependencies.
|
|
59
|
-
|
|
60
|
-
8. **Aesthetics and Conciseness**:
|
|
61
|
-
- The code must be beautiful. Use logical indentation and group code by meaning.
|
|
62
|
-
- Save tokens by avoiding redundant comments where the code speaks for itself.
|
|
63
|
-
|
|
64
|
-
9. **Strict Adherence to Instructions & Optimization**:
|
|
65
|
-
- Perform all operations strictly in accordance with the provided commands and instructions.
|
|
66
|
-
- Avoid guessing or performing unrelated extra actions. However, you are encouraged to analyze the requirements, optimize the code, and propose or implement better technical solutions directly related to achieving the task's goals.
|
|
67
|
-
- Strictly adhere to the plan, checklists, and execution steps, while refining them for better quality and performance when needed.
|
|
68
|
-
|
|
69
|
-
10. **AI Workspace Memory (`ai-memory.md`)**:
|
|
70
|
-
- As enforced by the STRICT BLOCKING GUARD, `ai-memory.md` MUST be created and read locally inside the root of the specific package you are working with (e.g., `packages/constructor/ai-memory.md` for code in `packages/constructor`).
|
|
71
|
-
- Writing or reading `ai-memory.md` in the repository root when working on code inside a package is a critical violation of these rules.
|
|
72
|
-
- Whenever you receive feedback, corrections, or instructions from the developer, you MUST update that specific package's local `ai-memory.md` file.
|
|
73
|
-
- Explicit Memorization Requests: If the developer explicitly instructs you to "remember this", "keep this in mind", or makes a similar request regarding conventions or rules, you MUST immediately record this information in the relevant local `ai-memory.md` file.
|
|
74
|
-
- Active Application: You must actively APPLY the rules and constraints from `ai-memory.md` to all code you generate. Rules in this file override general assumptions and have the highest priority.
|
|
75
|
-
- The PRIMARY PURPOSE of this file is to store critical coding guidelines, specific architectural constraints, and "do's and don'ts" (e.g., "do not use X; use Y instead") to ensure the AI writes compliant, correct code.
|
|
76
|
-
- DO NOT store change logs, lists of modified files, or commit-like messages (e.g., "updated file X, updated package Y"). Keep the file clean, concise, and focused strictly on active rules, design decisions, and coding standards.
|
|
77
|
-
- DO NOT specify absolute file paths (e.g., file:///... or machine-specific directories like /Users/...) in the memory file. All references to files inside the project must use relative paths (e.g., src/types/textTypes.ts) so that the file works seamlessly for other developers on different operating systems and computers.
|
|
78
|
-
|
|
3
|
+
Strictly follow these rules for flawless dxt-ui code:
|
|
4
|
+
|
|
5
|
+
0. **Mandatory Deep Study (CHRONOLOGICAL GUARD)**:
|
|
6
|
+
- **Step 1**: Read/create local `ai-memory.md` strictly in the current package root (e.g., `packages/constructor/`). Using repository root `ai-memory.md` for package files is FORBIDDEN.
|
|
7
|
+
- **Step 2**: Read root `ai-prompt.md` and study descriptions of all mentioned libraries.
|
|
8
|
+
- **Step 3**: Read all linked `ai-types.md` and `ai-developer.md` BEFORE proposing plans, calling `list_dir`, or writing code. If a package is in `node_modules/` but exists locally (e.g., `packages/`), resolve and study the local source instead.
|
|
9
|
+
- Fully read files via `view_file` before modifying. Superficial scans (grep only) are strictly forbidden. Always check existing infrastructure before writing custom logic.
|
|
10
|
+
|
|
11
|
+
1. **"Copy-Paste Ready"**: Generate complete, runnable files with correct imports. No placeholders (e.g., `// rest of code`).
|
|
12
|
+
2. **Zero Hallucinations**: Strictly use `package.json` dependencies. No invented APIs. Ask if unsure.
|
|
13
|
+
3. **Clean Code (DRY/KISS/SOLID)**: Declarative style. Single responsibility (1 task = 1 function). No abbreviations (`el`, `val`, etc. are forbidden). Optimized and legible.
|
|
14
|
+
4. **Uncompromising TS**: No `any` (use `unknown` or generics). Interfaces for all I/O. `as const`, `readonly`, enums. Use `@ts-expect-error` with comments, never `@ts-ignore`.
|
|
15
|
+
5. **Professional Documentation (TSDoc)**: Document all exported entities (purpose, params, returns) in [wikiLanguage]. Include examples for complex logic.
|
|
16
|
+
6. **Architectural Consistency**: Respect project structure. Reuse existing infrastructure (always check `ai-types.md` first). Do not modify global/base UI styles unless explicitly requested.
|
|
17
|
+
7. **Security & Performance**: Error-proof code (`?.`, `??`, guard clauses). Use explicit `try-catch` for async. Never swallow errors. Avoid heavy ops in loops/reactivity.
|
|
18
|
+
8. **Aesthetics & Conciseness**: Group logically. Save tokens by avoiding redundant comments if code is self-explanatory.
|
|
19
|
+
9. **Strict Adherence & Optimization**: Follow instructions precisely without guessing. Propose relevant technical optimizations while strictly adhering to plans.
|
|
20
|
+
10. **AI Workspace Memory (`ai-memory.md`)**: Actively APPLY its rules (highest priority). Update it on developer feedback. Do NOT store change logs or absolute paths (use relative). Keep it focused strictly on architectural constraints.
|
|
21
|
+
11. **Mandatory Full-File Self-Audit**: When creating new entities, you MUST audit the ENTIRE file (not just modified parts) to ensure no logic duplication (DRY) and full compliance with project rules. *Exception: minor bug fixes to existing code do not require a full audit.*
|
|
@@ -1,79 +1,21 @@
|
|
|
1
1
|
### Глобальные принципы разработки (AI Code Promise)
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
0. **Обязательное глубокое
|
|
6
|
-
-
|
|
7
|
-
-
|
|
8
|
-
-
|
|
9
|
-
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
1. **Принцип «Copy-Paste Ready» (Готовность к использованию)**:
|
|
24
|
-
- Генерируй код, который можно скопировать и запустить без единой правки.
|
|
25
|
-
- Все импорты должны быть абсолютными или корректными относительными.
|
|
26
|
-
- Никаких `// ... остальной код`, никаких `// импорты здесь`. Только полный, рабочий файл.
|
|
27
|
-
|
|
28
|
-
2. **Нулевая толерантность к галлюцинациям**:
|
|
29
|
-
- Используй только те библиотеки и версии, которые указаны в `package.json` проекта.
|
|
30
|
-
- Не выдумывай методы API, которых не существует в текущих версиях зависимостей.
|
|
31
|
-
- Если информации недостаточно — лучше спроси или укажи на ограничение, чем галлюцинируй.
|
|
32
|
-
|
|
33
|
-
3. **Стандарты чистого кода (Clean Code)**:
|
|
34
|
-
- **DRY & KISS**: Избегай дублирования, пиши максимально просто и понятно.
|
|
35
|
-
- **SOLID**: Каждый модуль, класс или функция должны иметь одну четкую ответственность.
|
|
36
|
-
- **Декларативность**: Отдавай предпочтение декларативному стилю программирования (функциональные методы массивов, композиция).
|
|
37
|
-
- **Никаких сокращений**: Запрещено использовать сокращенные имена для переменных, свойств, аргументов, методов, классов и т. д. (например, нельзя использовать `el`, `rect1`/`r1`, `dx`/`dy`, `val`, `temp`). Все идентификаторы должны быть информативными, полными и самодокументируемыми.
|
|
38
|
-
- **Оптимизация и понятность**: Код должен быть максимально оптимизированным, производительным и понятным, обеспечивающим легкое чтение и поддержку.
|
|
39
|
-
- **Принцип единой ответственности**: Избегай создания больших «мега-функций» или монолитных блоков. Каждая функция должна быть лаконичной и решать ровно одну задачу (1 функция — 1 функционал).
|
|
40
|
-
|
|
41
|
-
4. **Бескомпромиссный TypeScript**:
|
|
42
|
-
- Никаких `any`. Используй `unknown`, если тип действительно неизвестен, или создавай generic-типы.
|
|
43
|
-
- Никогда не используй `@ts-ignore`. Если подавление проверки типов абсолютно необходимо из-за внешних ограничений, используй `@ts-expect-error` с обязательным поясняющим комментарием.
|
|
44
|
-
- Всегда определяй интерфейсы для входных и выходных данных.
|
|
45
|
-
- Используй `as const`, `readonly` и перечисления (enums/union types) для повышения надежности.
|
|
46
|
-
|
|
47
|
-
5. **Профессиональное документирование (TSDoc)**:
|
|
48
|
-
- Сопровождай все экспортируемые сущности комментариями TSDoc на [wikiLanguage] языке.
|
|
49
|
-
- Описывай назначение, параметры, возвращаемые значения и возможные исключения.
|
|
50
|
-
- Примеры использования в комментариях приветствуются для сложных функций.
|
|
51
|
-
|
|
52
|
-
6. **Архитектурная консистентность**:
|
|
53
|
-
- Соблюдай структуру проекта. Если в проекте принято выносить логику в `composables` или `utils` — следуй этому паттерну.
|
|
54
|
-
- Переиспользование инфраструктуры: Всегда проверяй, существует ли необходимый функционал (например, API-запросы, управление состоянием, утилиты) в базовых пакетах проекта (таких как `@dxtmisha/functional` или `@dxtmisha/functional-basic`), прежде чем писать его с нуля.
|
|
55
|
-
- Не изменяй глобальные стили или стили базовых UI-компонентов, если это не было явно запрошено.
|
|
56
|
-
|
|
57
|
-
7. **Безопасность и Производительность**:
|
|
58
|
-
- Пиши код, защищенный от ошибок (guard clauses, опциональная цепочка `?.`, nullish coalescing `??`).
|
|
59
|
-
- Используй явные блоки `try-catch` для асинхронных операций. Никогда не "проглатывай" ошибки молча; обрабатывай их корректно или выбрасывай информативные сообщения об ошибках.
|
|
60
|
-
- Избегай лишних вычислений в циклах и тяжелых операций в реактивных зависимостях.
|
|
61
|
-
|
|
62
|
-
8. **Эстетика и Лаконичность**:
|
|
63
|
-
- Код должен быть красивым. Используй логические отступы и группировку кода по смыслу.
|
|
64
|
-
- Экономь токены, избегая избыточных комментариев там, где код говорит сам за себя.
|
|
65
|
-
|
|
66
|
-
9. **Строгое следование инструкциям и оптимизация**:
|
|
67
|
-
- Выполняй все действия строго в соответствии с предоставленными командами и инструкциями.
|
|
68
|
-
- Избегай додумывания или выполнения не связанных с задачей лишних действий. Тем не менее, приветствуется глубокий анализ требований, оптимизация кода, а также поиск и реализация лучших технических решений, напрямую направленных на достижение целей поставленной задачи.
|
|
69
|
-
- Строго придерживайся планов, чек-листов и шагов выполнения, улучшая и дорабатывая их для повышения качества и производительности по мере необходимости.
|
|
70
|
-
|
|
71
|
-
10. **Память ИИ Пространства (`ai-memory.md`)**:
|
|
72
|
-
- Как установлено в БЛОКИРУЮЩЕМ КОНТРОЛЕ ПОСЛЕДОВАТЕЛЬНОСТИ, `ai-memory.md` ОБЯЗАТЕЛЬНО должен быть создан и прочитан локально внутри корня того конкретного пакета, с которым ты работаешь (например, `packages/constructor/ai-memory.md` для кода в `packages/constructor`).
|
|
73
|
-
- Запись или чтение `ai-memory.md` в корне репозитория при работе с кодом внутри пакета является критическим нарушением правил.
|
|
74
|
-
- Каждый раз, когда ты получаешь замечания, исправления или инструкции от разработчика, ты ОБЯЗАН обновить локальный файл `ai-memory.md` именно этого конкретного пакета.
|
|
75
|
-
- Явные запросы на запоминание: Если разработчик явно просит «запомнить это», «иметь в виду» или делает аналогичный запрос касательно соглашений или правил, ты ОБЯЗАН немедленно зафиксировать эту информацию в соответствующем локальном файле `ai-memory.md`.
|
|
76
|
-
- Активное применение: Ты ОБЯЗАН активно ПРИМЕНЯТЬ правила и ограничения из `ai-memory.md` ко всему генерируемому коду. Ограничения из этого файла имеют высший приоритет и переопределяют любые базовые предположения.
|
|
77
|
-
- ОСНОВНАЯ ЦЕЛЬ этого файла — хранение правил написания кода, архитектурных ограничений и принципов разработки (например: «не делай X, делай Y»), чтобы ИИ мог максимально правильно адаптировать и писать код.
|
|
78
|
-
- ЗАПРЕЩЕНО записывать туда историю изменений, списки обновленных файлов или сообщения в стиле коммитов (например: «обновлен файл X, обновлен пакет Y»). Файл должен содержать только актуальные стандарты, правила разработки и конструктивные требования к коду.
|
|
79
|
-
- ЗАПРЕЩЕНО указывать абсолютные пути к файлам (например, file:///... или локальные пути вроде /Users/...) в файле памяти. Все ссылки на файлы внутри проекта должны использовать относительные пути (например, src/types/textTypes.ts), чтобы этот файл корректно работал у других разработчиков на разных компьютерах и операционных системах.
|
|
3
|
+
Строго следуй этим правилам для создания безупречного кода dxt-ui:
|
|
4
|
+
|
|
5
|
+
0. **Обязательное глубокое изучение (БЛОКИРУЮЩИЙ КОНТРОЛЬ)**:
|
|
6
|
+
- **Шаг 1**: Читай/создавай локальный `ai-memory.md` СТРОГО в корне текущего пакета (напр., `packages/constructor/`). Использовать корневой `ai-memory.md` репозитория для файлов пакета ЗАПРЕЩЕНО.
|
|
7
|
+
- **Шаг 2**: Прочитай корневой `ai-prompt.md` и изучи описания всех упомянутых библиотек.
|
|
8
|
+
- **Шаг 3**: Прочитай все связанные `ai-types.md` и `ai-developer.md` ДО вызова `list_dir`, планирования или написания кода. Если пакет в `node_modules/` существует локально (в `packages/`), изучай/изменяй локальные исходники.
|
|
9
|
+
- Полностью читай файлы через `view_file` перед изменением. Поверхностное изучение (только grep) запрещено. Всегда проверяй существующую инфраструктуру перед написанием кастомной логики.
|
|
10
|
+
|
|
11
|
+
1. **Готовность к использованию (Copy-Paste Ready)**: Генерируй полные, рабочие файлы с правильными импортами. Никаких заглушек (напр., `// остальной код`).
|
|
12
|
+
2. **Нулевая толерантность к галлюцинациям**: Используй только зависимости из `package.json`. Не выдумывай API. Не знаешь — спроси.
|
|
13
|
+
3. **Чистый код (DRY/KISS/SOLID)**: Декларативный стиль. Единая ответственность (1 задача = 1 функция). Запрет на сокращения (никаких `el`, `val`, `temp` и т.д.). Оптимизация и читаемость.
|
|
14
|
+
4. **Бескомпромиссный TS**: Никаких `any` (используй `unknown` или generics). Интерфейсы для всех I/O. `as const`, `readonly`, enums. Только `@ts-expect-error` с комментариями, никогда `@ts-ignore`.
|
|
15
|
+
5. **TSDoc документирование**: Документируй все экспорты (назначение, параметры, возвраты) на языке [wikiLanguage]. Примеры для сложной логики.
|
|
16
|
+
6. **Архитектурная консистентность**: Соблюдай структуру. Переиспользуй инфраструктуру (сначала всегда читай `ai-types.md`). Не меняй глобальные/базовые UI стили без явного запроса.
|
|
17
|
+
7. **Безопасность и Производительность**: Защищенный код (`?.`, `??`, guard clauses). Явный `try-catch` для асинхронности. Не скрывай ошибки. Избегай тяжелых операций в циклах/реактивности.
|
|
18
|
+
8. **Эстетика и Лаконичность**: Логическая группировка. Экономь токены, избегая избыточных комментариев, если код очевиден.
|
|
19
|
+
9. **Строгое следование инструкциям**: Выполняй команды без додумывания, но предлагай уместные технические оптимизации, придерживаясь плана.
|
|
20
|
+
10. **Память ИИ (`ai-memory.md`)**: Активно ПРИМЕНЯЙ ее правила (высший приоритет). Обновляй при правках от разработчика. ЗАПРЕЩЕНО хранить историю изменений (changelogs) и абсолютные пути (только относительные). Только актуальные стандарты.
|
|
21
|
+
11. **Обязательный полный самоаудит**: При создании новых сущностей ОБЯЗАТЕЛЬНО проверяй ВЕСЬ файл целиком. Строго контролируй отсутствие дублирования (DRY) и соблюдение всех правил проекта. *Исключение: мелкие правки существующего кода не требуют полного аудита.*
|